Skip to content
On this page

AG-UI 插件

AG-UI 插件(@tencent/ssv-ai-sdk-plugin-agui)是 v2.0 的核心插件,实现了 AG-UI 协议——一套标准化的 Agent 前后端通信协议。

配合 useAgent / AgentMixin / AgentBehavior 使用,提供:

  • AG-UI 事件流解析(RUN_STARTED、TEXT_MESSAGE_CONTENT、TOOL_CALL_* 等)
  • 工具注册与执行(Frontend / Backend 两种类型)
  • 自动构造 Parts 时序消息结构

安装

注意该 npm 包为 Coding Npm 的私有源,请先确定已正确配置了 Coding Npm

bash
npm install @tencent/ssv-ai-sdk-plugin-agui --save

快速使用

jsx
import { useAgent } from '@tencent/ssv-ai-sdk-react';
import { AGUIPlugin } from '@tencent/ssv-ai-sdk-plugin-agui';

const { messages, send, on, off, setTools } = useAgent({
  api: {
    chatEndpoint: { url: 'your-agui-endpoint' },
  },
  plugins: [new AGUIPlugin()],
});
vue
<script setup>
import { useAgent } from '@tencent/ssv-ai-sdk-vue';
import { AGUIPlugin } from '@tencent/ssv-ai-sdk-plugin-agui';

const { messages, send, on, off, setTools } = useAgent({
  api: {
    chatEndpoint: { url: 'your-agui-endpoint' },
  },
  plugins: [new AGUIPlugin()],
});
</script>
js
import { AgentMixin } from '@tencent/ssv-ai-sdk-vue2';
import { AGUIPlugin } from '@tencent/ssv-ai-sdk-plugin-agui';

export default {
  mixins: [
    AgentMixin({
      api: {
        chatEndpoint: { url: 'your-agui-endpoint' },
      },
      plugins: [new AGUIPlugin()],
    }),
  ],
};
js
const { AgentBehavior } = require('@tencent/ssv-ai-sdk-miniprogram');
const { AGUIPlugin } = require('@tencent/ssv-ai-sdk-plugin-agui');

Component({
  behaviors: [
    AgentBehavior({
      api: {
        chatEndpoint: { url: 'your-agui-endpoint' },
      },
      plugins: [new AGUIPlugin()],
    }),
  ],
});

工具注册

注册时机

推荐在组件生命周期中注册工具,这样 handler 可以通过闭包直接访问组件实例,无需全局变量:

jsx
useEffect(() => {
  setTools([
    {
      name: 'setThemeColor',
      type: 'frontend',
      description: '设置主题颜色',
      parameters: {
        type: 'object',
        properties: {
          color: { type: 'string', description: '颜色值,如 #ff0000' },
        },
        required: ['color'],
      },
      handler: async (args) => {
        document.documentElement.style.setProperty('--theme-color', args.color);
        return { success: true };
      },
    },
  ]);
}, []);
vue
onMounted(() => {
  setTools([
    {
      name: 'setThemeColor',
      type: 'frontend',
      description: '设置主题颜色',
      parameters: { /* ... */ },
      handler: async (args) => {
        // 可直接访问组件作用域的变量
        themeColor.value = args.color;
        return { success: true };
      },
    },
  ]);
});
js
mounted() {
  this.agent.setTools([
    {
      name: 'setThemeColor',
      type: 'frontend',
      description: '设置主题颜色',
      parameters: { /* ... */ },
      handler: async (args) => {
        // 可直接访问 this
        this.themeColor = args.color;
        return { success: true };
      },
    },
  ]);
}
js
lifetimes: {
  attached() {
    this.agent.setTools([
      {
        name: 'setThemeColor',
        type: 'frontend',
        description: '设置主题颜色',
        parameters: { /* ... */ },
        handler: async (args) => {
          // 可直接访问 this
          this.setData({ themeColor: args.color });
          return { success: true };
        },
      },
    ]);
  }
}

Frontend 工具

由浏览器/小程序端执行的工具,适用于 UI 操作、本地计算等场景:

typescript
{
  name: 'get_current_location',
  type: 'frontend',             // 显式声明为前端工具
  description: '获取用户当前位置',
  parameters: {
    type: 'object',
    properties: {},
  },
  /**
   * @param args    解析后的参数对象
   * @param context { toolCallId, toolName }
   * @returns 返回值会更新到 ToolCallPart.result,用于 UI 展示
   */
  handler: async (args, context) => {
    return new Promise((resolve) => {
      navigator.geolocation.getCurrentPosition((pos) => {
        resolve({
          lat: pos.coords.latitude,
          lng: pos.coords.longitude,
        });
      });
    });
  },
}

前端工具执行完成后,SDK 会触发 toolExecuted 事件,业务层需要监听此事件并决定是否将结果发送给 Agent

Backend 工具

由后端服务器执行的工具,前端只需提供可选的结果转换 handler:

typescript
{
  name: 'get_weather',
  type: 'backend',              // 可省略,默认为 backend
  description: '查询天气',
  parameters: {
    type: 'object',
    properties: {
      city: { type: 'string', description: '城市名称' },
    },
    required: ['city'],
  },
  /**
   * 可选:对后端返回的结果进行 UI 适配转换
   * @param args          解析后的参数对象
   * @param backendResult 后端返回的原始结果
   * @returns 转换后的结果,更新到 ToolCallPart.result 用于展示
   */
  handler: async (args, backendResult) => {
    // 转换为适合 UI 展示的格式
    return {
      temperature: backendResult.temp,
      description: backendResult.weather_desc,
      icon: getWeatherIcon(backendResult.code),
    };
  },
}

处理工具结果

toolExecuted 事件流程

前端工具执行完成后,业务层通过 toolExecuted 事件接收结果,并决定是否发送给 Agent:

js
// 在组件生命周期中注册监听
on('toolExecuted', (event) => {
  const { toolCallId, toolCallName, result } = event;

  // UI-only 工具(如动画、主题)不需要发送结果给 Agent
  const UI_ONLY_TOOLS = ['launchRocket', 'setThemeColor'];
  if (UI_ONLY_TOOLS.includes(toolCallName)) return;

  // 将工具结果发送给 Agent,继续 Agent Run
  send({
    toolResults: [{ toolCallId, result }],
  });
});

完整工具调用流程

用户发送消息

Agent 分析,决定调用工具 → toolCallStart 事件

参数流式传输 → toolCallArgs 事件

参数接收完成 → toolCallEnd 事件

[Frontend 工具] handler 执行 → toolExecuted 事件 → 业务层调用 send({ toolResults })
[Backend 工具]  后端执行完成 → toolCallResult 事件 → handler 转换结果(可选)

Agent 收到工具结果,继续生成回复

runFinished 事件

插件配置项

typescript
interface AGUIPluginOptions {
  /** 初始工具列表(也可在运行时通过 setTools 注册) */
  tools?: AGUIExecutableTool[];
  /** 工具执行超时时间(毫秒) */
  toolTimeout?: number;
  /** 状态变化回调 */
  onAgentStateChange?: (state: AgentState, prevState: AgentState) => void;
}

工具类型定义

typescript
interface AGUIExecutableTool {
  /** 工具名称(唯一标识) */
  name: string;
  /** 工具描述(供 LLM 理解工具用途) */
  description: string;
  /** 参数 JSON Schema */
  parameters: object;
  /**
   * 工具类型
   * - 'frontend':前端执行,handler(args, context) 在 TOOL_CALL_END 时调用
   * - 'backend':后端执行,handler(args, result) 在 TOOL_CALL_RESULT 时转换数据(可选)
   * @default 'backend'
   */
  type?: 'frontend' | 'backend';
  /** 工具处理器 */
  handler?: FrontendToolHandler | BackendToolHandler;
}

Released under the MIT License.