Skip to content
CrewAI 文档版本 跟随上游 源快照 b76c99a4 更新于 2026-10-18

前端操作

让你的 CrewAI 智能体调用在用户浏览器中运行的函数,从切换主题到在你的应用中导航。

让智能体对应用执行操作

前端操作是智能体调用的工具,它在浏览器中运行代码而不是在服务器上。模型决定调用它;你的处理程序切换主题、导航、高亮元素或更新应用数据;结果再流回智能体。

它使用与基于工具的生成式 UI 相同的 hook:useFrontendTool。区别在于你传入的内容:一个运行代码的 handler,而不是(或同时伴随)绘制 UI 的 render。

NOTE

前端操作对 Crew 和 Flow 都适用。任何将 copilotkit.actions 绑定到其 LLM 调用中的智能体都可以调用它们。

构建一个前端操作

下面的示例让智能体在收到请求时将应用切换为深色模式。

Register the action on the frontend

调用 useFrontendTool 并传入一个 handler。当智能体调用该工具时,处理程序在浏览器中运行,它返回的字符串会被回传给智能体。

tsx
"use client";
import { useFrontendTool } from "@copilotkit/react-core/v2";
import { z } from "zod";

useFrontendTool({
  agentId: "assistant",
  name: "set_theme",
  description: "Switch the app between light and dark mode.",
  parameters: z.object({
    theme: z.enum(["light", "dark"]),
  }),
  followUp: false,
  handler: async ({ theme }) => {
    document.documentElement.dataset.theme = theme; // runs in the browser
    return `Theme set to ${theme}.`;
  },
});

参数如下:

  • name —— 模型调用的工具名称(set_theme)。
  • description —— 对工具功能的简短说明。模型会阅读它来决定何时调用工具,因此要写得具体。省略它会让模型仅凭名称猜测。
  • parameters —— 一个 zod schema,描述模型必须提供的参数。CopilotKit 会将其转换为工具的 JSON schema 并校验传入的调用。
  • handler(args) —— 在浏览器中带着已解析的参数运行。在此执行你的副作用(设置主题、导航、更新状态)。你返回的字符串会作为工具结果交还给智能体。
  • followUp: false —— 阻止智能体在操作运行后再进行一轮。当你希望智能体在操作后作出回应时,省略它(或设为 true)。

Bind the frontend tools on the backend

智能体只能调用已提供给它的工具。在你的 Flow 中,使用 *self.state.copilotkit.actions 将前端注册的工具传入 LLM 的 tools 列表。

python
from crewai.flow.flow import Flow, start
from litellm import acompletion
from ag_ui_crewai.sdk import copilotkit_stream, CopilotKitState

class AssistantFlow(Flow[CopilotKitState]):
    @start()
    async def chat(self):
        response = await copilotkit_stream(
            await acompletion(
                model="openai/gpt-4o",
                messages=[
                    {"role": "system", "content": "Help the user. Use the tools available to control the app."},
                    *self.state.messages,
                ],
                tools=[*self.state.copilotkit.actions],  # tools the frontend registered
                parallel_tool_calls=False,
                stream=True,
            )
        )
        message = response.choices[0].message
        self.state.messages.append(message)

self.state.copilotkit.actions 保存了所有通过 useFrontendTool 注册的前端操作的工具定义。将它们展开到 LLM 的 tools 列表中,正是让智能体能够调用浏览器端操作的关键。copilotkit_stream 将响应(包括工具调用)流式输出回前端,CopilotKit 在那里运行匹配的处理程序。

Serve the Flow

通过 add_crewai_flow_fastapi_endpoint(...) 将 Flow 暴露在 AG-UI 之上,并在 CopilotKit 运行时中注册它,与 前端概览 中完全一致。两者都运行后,让助手"切换到深色模式"就会触发 set_theme,页面随之翻转。

操作与生成式 UI 的对比

useFrontendTool 覆盖了一个谱系的两端,你可以按工具选择:

你提供它的作用
handler在浏览器中运行代码(前端操作)
render为工具调用绘制 UI(生成式 UI)

你可以只提供其中一个,或两者都提供。同时带有 render 的 handler 会执行操作并在运行时绘制 UI。对于仅展示智能体操作结果的纯渲染工具,请参见 基于工具的生成式 UI。

相关

BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。