为你的小程序加入Agent

获取AI免费额度

微信推出的AI助长计划白嫖 https://developers.weixin.qq.com/miniprogram/dev/wxcloudservice/wxcloud/billing/ai-inspire-plan.html

创建Agent

在微信公众平台 小程序中找到Agent
行业能力/AI 小程序成长计划
点击去使用免费Token进入腾讯云CloudBase创建一个云函数
agent
腾讯云就自动帮你创建了一个Agent云函数,后续可以在云函数内修改Agent,在小程序客户端调用即可。

小程序调用Agent

  1. 初始化

    1
    2
    3
    wx.cloud.init({
    env: "cloud1-1g5s2onp8616ac93"
    });
  2. 调用云函数方法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    const res = await wx.cloud.extend.AI.bot.sendMessage({
    data: {
    // botId 必填,标识调用的 Agent
    "botId": '你的agent名',
    "threadId": "550e8400-e29b-41d4-a716-446655440000",
    "runId": "run_001",
    "messages": [
    { "id": "msg-1", "role": "user", "content": "你好" }
    ],
    "tools": [],
    "context": [],
    "state": {},
    "forwardedProps": {}
    }
    });

    // 记录完整响应
    let text = '';

    for await (let event of res.eventStream) {
    const data = JSON.parse(event.data);

    // 根据事件类型输出,响应事件参考文档:
    // https://docs.cloudbase.net/ai/agent/http-agent-protocol#%E5%93%8D%E5%BA%94%E4%BA%8B%E4%BB%B6
    switch (data.type) {
    case 'TEXT_MESSAGE_CONTENT':
    text += data.delta;
    console.log(data.delta); // 实时输出
    break;

    case 'RUN_ERROR':
    console.error('运行出错:', data.message);
    break;

    // 收到结束事件,终止循环
    case 'RUN_FINISHED':
    // 运行结束
    break;
    }
    }
    console.log('完整响应:', text);

请求参数详解

HTTP Agent 完全兼容

AGUI协议 AGUI协议(Agent-User Interaction Protocol)是一种轻量级、事件驱动的协议,旨在规范AI智能体与用户界面之间的交互,提升用户体验。

请求体

1
2
3
4
5
6
7
8
9
10
interface RunAgentInput {
threadId: string; // 会话线程 ID
runId: string; // 本次运行的唯一 ID
parentRunId?: string; // 可选,父运行 ID(用于分支/回溯场景)
state?: any; // 可选,当前状态
messages: Message[]; // 消息历史
tools: Tool[]; // 客户端工具列表
context: Context[]; // 上下文信息
forwardedProps?: any; // 可选,透传属性
}

参考链接

https://docs.cloudbase.net/ai/agent/http-agent-protocol