CrewAI Python 适配器
让 CrewAI Flow 支持 AG-UI 协议。
什么是 AG-UI?
AG-UI 是一个开放、轻量级、基于事件的协议,用于标准化 AI Agent 与用户界面的交互。它让 Agent 可以:
- 实时流式对话
- 双向状态同步
- 前端工具集成(Client Tools)
- 人机协作(Human-in-the-loop)
这个包解决什么问题?
- 让 CrewAI Flow 支持 AG-UI 协议:将 CrewAI Flow 实例适配为 AG-UI 兼容的 Agent
- 事件桥接:将 CrewAI flow 事件转换为 AG-UI 事件
- 状态管理:提供状态转换器和 CopilotKit 集成辅助工具
核心概念
| 导出 | 说明 |
|---|---|
CrewAIAgent | 将 CrewAI Flow 实例包装为 AG-UI 兼容的 Agent |
CopilotKitState | 支持 AG-UI 的 CrewAI flow 状态模型 |
copilotkit_stream | LiteLLM 响应流式处理辅助函数 |
crewai_prepare_inputs | 将 AG-UI 输入转换为 CrewAI 格式 |
配合使用
| 包名 | 作用 |
|---|---|
cloudbase-agent-server | 将 Agent 部署为 AG-UI 兼容的 HTTP 服务 |
crewai | CrewAI flow 框架 |
litellm | 多提供商 LLM 集成 |
架构图
安装
pip install cloudbase-agent-crewai cloudbase-agent-server crewai litellm
快速开始
1. 创建 CrewAI Flow
# agent.py
import os
from dotenv import load_dotenv
from crewai.flow.flow import Flow, start
from crewai.flow.persistence import persist
from litellm import completion
load_dotenv()
from cloudbase_agent.crewai import CopilotKitState, copilotkit_stream, CrewAIAgent
@persist()
class ChatFlow(Flow[CopilotKitState]):
"""使用 CrewAI 的对话聊天流程"""
@start()
async def chat(self) -> None:
"""处理聊天消息并生成流式响应"""
system_prompt = "你是一位乐于助人的助手。"
try:
# 准备完成参数
completion_params = {
"model": f"openai/{os.getenv('OPENAI_MODEL', 'gpt-4o-mini')}",
"messages": [
{"role": "system", "content": system_prompt},
*self.state.messages
],
"stream": True,
}
# 如果有可用工具则添加
if self.state.copilotkit.actions:
completion_params["tools"] = [*self.state.copilotkit.actions]
completion_params["parallel_tool_calls"] = False
# 使用 copilotkit_stream 包装器流式响应
response = await copilotkit_stream(completion(**completion_params))
message = response.choices[0].message
# 添加到对话历史
self.state.messages.append(message)
except Exception as e:
print(f"[CrewAI Flow Chat] {e}")
def build_workflow():
"""构建并返回新的聊天工作流实例"""
return ChatFlow()
# 导出 create_agent 函数
def create_agent():
flow = build_workflow()
agent = CrewAIAgent(
name="ChatBot",
description="一个乐于助人的对话助手",
flow=flow,
)
return {"agent": agent}