在开发智能体应用时,我们常常会遇到这样的场景:智能体团队在执行复杂任务时需要人类的即时反馈,比如创意审核、关键决策或数据验证。这时候,AutoGen 框架提供的 "人在回路"(Human-in-the-Loop)机制就成为了连接智能体与人类专家的桥梁。今天,我们就来系统拆解这一机制的两种核心交互模式,帮助你在智能体应用中实现更灵活的人机协作。
UserProxyAgent 是 AutoGen 中专门用于收集用户反馈的内置智能体,它能在团队运行过程中主动请求人类介入:
python
from autogen_agentchat.agents import AssistantAgent, UserProxyAgent
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_ext.models.openai import OpenAIChatCompletionClient
# 初始化模型客户端
model_client = OpenAIChatCompletionClient(model="gpt-4o-mini")
# 创建创作智能体
assistant = AssistantAgent("assistant", model_client=model_client)
# 创建用户代理智能体(使用input函数获取控制台输入)
user_proxy = UserProxyAgent("user_proxy", input_func=input)
# 设置终止条件(用户输入APPROVE时结束)
termination = TextMentionTermination("APPROVE")
# 构建包含用户代理的团队
team = RoundRobinGroupChat(
agents=[assistant, user_proxy],
termination_condition=termination
)
# 运行团队任务
stream = team.run_stream(task="创作一首关于海洋的四行诗")
await Console(stream)
运行这段代码后,你会看到这样的交互流程:
text
In endless blue where whispers play,
The ocean's waves dance night and day.
A world of depths, both calm and wild,
Nature's heart, forever beguiled.
在实际项目中,我们通常需要将反馈接口集成到 Web 应用中。以下是使用 FastAPI 框架的示例:
python
from fastapi import FastAPI, WebSocket
from autogen_agentchat.agents import UserProxyAgent
from autogen_agentchat.teams import RoundRobinGroupChat
app = FastAPI()
# WebSocket接口处理用户反馈
@app.websocket("/ws/chat")
async def chat(websocket: WebSocket):
await websocket.accept()
# 自定义输入函数(从WebSocket获取用户消息)
async def user_input(prompt: str, cancellation_token):
data = await websocket.receive_json()
return data["content"]
# 创建带自定义输入函数的用户代理
user_proxy = UserProxyAgent(
"web_user",
input_func=user_input
)
# 初始化团队(此处简化处理,实际项目需完整配置)
team = RoundRobinGroupChat(agents=[...], termination_condition=...)
# 运行团队并处理交互
# ... 完整逻辑参考AgentChat FastAPI示例
这种集成方式适用于:
使用运行中反馈时需要注意:
通过设置 max_turns 参数,我们可以让团队在指定轮次后暂停,等待用户反馈:
python
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_ext.models.openai import OpenAIChatCompletionClient
# 创建智能体
model_client = OpenAIChatCompletionClient(model="gpt-4o-mini")
assistant = AssistantAgent("assistant", model_client=model_client)
# 创建每轮后暂停的团队(max_turns=1)
team = RoundRobinGroupChat([assistant], max_turns=1)
# 循环运行团队,收集迭代反馈
task = "创作一首关于海洋的四行诗"
while True:
stream = team.run_stream(task=task)
await Console(stream)
# 获取用户反馈
user_feedback = input("Enter your feedback (type 'exit' to leave): ")
if user_feedback.lower().strip() == "exit":
break
task = user_feedback
运行结果展示了典型的迭代过程:
text
Endless waves in a dance with the shore,
Whispers of secrets in tales from the roar,
Beneath the vast sky, where horizons blend,
The ocean’s embrace is a timeless friend.
text
She walks along the tide, where dreams intertwine,
With every crashing wave, her heart feels aligned,
In the ocean's embrace, her worries dissolve,
A symphony of solace, where her spirit evolves.
HandoffTermination 允许智能体在需要时主动移交控制权给用户:
python
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.conditions import HandoffTermination, TextMentionTermination
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_ext.models.openai import OpenAIChatCompletionClient
# 创建会主动移交的智能体
model_client = OpenAIChatCompletionClient(model="gpt-4o")
lazy_agent = AssistantAgent(
"lazy_assistant",
model_client=model_client,
handoffs=[Handoff(target="user", message="Transfer to user.")],
system_message="若无法完成任务,移交用户;否则用TERMINATE结束"
)
# 设置双重终止条件
handoff_termination = HandoffTermination(target="user")
text_termination = TextMentionTermination("TERMINATE")
team = RoundRobinGroupChat(
[lazy_agent],
termination_condition=handoff_termination | text_termination
)
# 运行任务(智能体因无天气工具而移交用户)
await Console(team.run_stream(task="What is the weather in New York?"))
# 用户提供天气信息后继续运行
await Console(team.run_stream(task="The weather in New York is sunny."))
在 AutoGen 的AssistantAgent
中,handoffs
参数用于定义智能体在何种条件下将任务移交给其他实体
这里配置的handoffs
会在以下场景触发:
system_message
判断需要移交时,会生成对应的工具调用FunctionCall
来执行handoffs
定义的移交逻辑在示例中,lazy_agent
的系统提示明确要求 "若无法完成任务则移交用户",因此当模型检测到缺少天气查询工具时,会自动触发handoffs
中定义的移交行为,生成向用户移交的消息。
代码中使用的handoff_termination | text_termination
是典型的逻辑或组合,意味着团队会在满足以下任意条件时终止:
在TextMentionTermination("TERMINATE")
中,"TERMINATE" 是触发终止的关键词,其作用如下:
反馈模式 | 适用场景 | 核心优势 |
---|---|---|
运行中反馈 | 实时审核、紧急决策 | 即时干预、避免错误累积 |
运行后反馈 | 迭代优化、深度修改 | 非阻塞处理、可批量反馈 |
通过本文的分享,我们系统学习了 AutoGen 人在回路机制的两种核心模式:运行中实时反馈和运行后迭代优化。这些机制让智能体团队不再是黑盒,而是可以被人类专家精准调控的协作伙伴。在实际项目中,合理运用这些技术可以提升智能体输出质量 30% 以上,同时降低错误率。
如果本文对你有帮助,别忘了点赞收藏,关注我,一起探索更高效的开发方式~