{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 任务交接\n\n任务交接(Handoff)是OpenAI在名为[Swarm](https://github.com/openai/swarm)的实验性项目中引入的多智能体设计模式。\n核心思想是让智能体通过特殊工具调用来将任务委托给其他智能体。\n\n我们可以使用AutoGen核心API通过事件驱动型智能体来实现任务交接模式。\n相比OpenAI的实现和早期版本(v0.2),使用AutoGen(v0.4+)具有以下优势:\n\n1. 通过分布式智能体运行时可以扩展到分布式环境\n2. 提供灵活的自定义智能体实现能力\n3. 原生异步API便于与UI和其他系统集成\n\n本笔记本演示了任务交接模式的简单实现。\n建议先阅读[主题与订阅](../core-concepts/topic-and-subscription.md)\n来理解发布-订阅和事件驱动型智能体的基本概念。\n\n```{note}\n我们正在[AgentChat](../../agentchat-user-guide/index.md)中为任务交接模式开发高级API,\n以便您能更快速地开始使用。\n```\n\n## 场景说明\n\n本场景基于[OpenAI示例](https://github.com/openai/openai-cookbook/blob/main/examples/Orchestrating_agents.ipynb)修改。\n\n考虑一个客户服务场景,客户试图通过聊天机器人获得产品退款或购买新产品。\n该聊天机器人是由三个AI智能体和一个人类智能体组成的多智能体团队:\n\n- 分诊智能体:负责理解客户请求并决定将任务交接给哪个其他智能体\n- 退款智能体:负责处理退款请求\n- 销售智能体:负责处理销售请求\n- 人类智能体:负责处理AI智能体无法处理的复杂请求\n\n在此场景中,客户通过用户代理与聊天机器人交互。\n\n下图展示了该场景中智能体的交互拓扑结构。\n\n![任务交接](handoffs.svg)\n\n让我们使用AutoGen核心来实现这个场景。首先需要导入必要的模块。\n" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [], "source": [ "import json\n", "import uuid\n", "from typing import List, Tuple\n", "\n", "from autogen_core import (\n", " FunctionCall,\n", " MessageContext,\n", " RoutedAgent,\n", " SingleThreadedAgentRuntime,\n", " TopicId,\n", " TypeSubscription,\n", " message_handler,\n", ")\n", "from autogen_core.models import (\n", " AssistantMessage,\n", " ChatCompletionClient,\n", " FunctionExecutionResult,\n", " FunctionExecutionResultMessage,\n", " LLMMessage,\n", " SystemMessage,\n", " UserMessage,\n", ")\n", "from autogen_core.tools import FunctionTool, Tool\n", "from autogen_ext.models.openai import OpenAIChatCompletionClient\n", "from pydantic import BaseModel" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 消息协议\n\n首先需要定义智能体间通信的消息协议。\n我们使用事件驱动的发布-订阅通信,因此这些消息类型将作为事件使用。\n\n- `UserLogin`:当用户登录并开始新会话时由运行时发布的消息\n- `UserTask`:包含用户会话聊天历史的消息。当AI智能体将任务交接给其他智能体时,也会发布`UserTask`消息\n- `AgentResponse`:由AI智能体和人类智能体发布的消息,包含聊天历史以及供客户回复的主题类型\n" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [], "source": [ "class UserLogin(BaseModel):\n", " pass\n", "\n", "\n", "class UserTask(BaseModel):\n", " context: List[LLMMessage]\n", "\n", "\n", "class AgentResponse(BaseModel):\n", " reply_to_topic_type: str\n", " context: List[LLMMessage]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## AI智能体\n\n我们从`AIAgent`类开始,这是多智能体聊天机器人中所有AI智能体\n(即分诊、销售和问题处理智能体)的基类。\n`AIAgent`使用{py:class}`~autogen_core.models.ChatCompletionClient`\n来生成响应。\n它可以直接使用常规工具,或通过`delegate_tools`将任务委托给其他智能体。\n它订阅`agent_topic_type`主题类型来接收来自客户的消息,\n并通过发布到`user_topic_type`主题类型向客户发送消息。\n\n在`handle_task`方法中,智能体首先使用模型生成响应。\n如果响应包含交接工具调用,智能体会通过向工具调用结果中指定的主题发布`UserTask`消息,\n将任务委托给另一个智能体。\n如果响应是常规工具调用,智能体会执行该工具并再次调用模型生成下一个响应,\n直到响应不再是工具调用。\n\n当模型响应不是工具调用时,智能体通过向`user_topic_type`发布`AgentResponse`消息\n来向客户发送响应。\n" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [], "source": [ "class AIAgent(RoutedAgent):\n", " def __init__(\n", " self,\n", " description: str,\n", " system_message: SystemMessage,\n", " model_client: ChatCompletionClient,\n", " tools: List[Tool],\n", " delegate_tools: List[Tool],\n", " agent_topic_type: str,\n", " user_topic_type: str,\n", " ) -> None:\n", " super().__init__(description)\n", " self._system_message = system_message\n", " self._model_client = model_client\n", " self._tools = dict([(tool.name, tool) for tool in tools])\n", " self._tool_schema = [tool.schema for tool in tools]\n", " self._delegate_tools = dict([(tool.name, tool) for tool in delegate_tools])\n", " self._delegate_tool_schema = [tool.schema for tool in delegate_tools]\n", " self._agent_topic_type = agent_topic_type\n", " self._user_topic_type = user_topic_type\n", "\n", " @message_handler\n", " async def handle_task(self, message: UserTask, ctx: MessageContext) -> None:\n", " # 将任务发送给大语言模型\n", " llm_result = await self._model_client.create(\n", " messages=[self._system_message] + message.context,\n", " tools=self._tool_schema + self._delegate_tool_schema,\n", " cancellation_token=ctx.cancellation_token,\n", " )\n", " print(f\"{'-'*80}\\n{self.id.type}:\\n{llm_result.content}\", flush=True)\n", " # 处理大语言模型的结果\n", " while isinstance(llm_result.content, list) and all(isinstance(m, FunctionCall) for m in llm_result.content):\n", " tool_call_results: List[FunctionExecutionResult] = []\n", " delegate_targets: List[Tuple[str, UserTask]] = []\n", " # 处理每个函数调用。\n", " for call in llm_result.content:\n", " arguments = json.loads(call.arguments)\n", " if call.name in self._tools:\n", " # 直接执行工具。\n", " result = await self._tools[call.name].run_json(arguments, ctx.cancellation_token)\n", " result_as_str = self._tools[call.name].return_value_as_string(result)\n", " tool_call_results.append(\n", " FunctionExecutionResult(call_id=call.id, content=result_as_str, is_error=False, name=call.name)\n", " )\n", " elif call.name in self._delegate_tools:\n", " # 执行工具以获取委托代理的主题类型。\n", " result = await self._delegate_tools[call.name].run_json(arguments, ctx.cancellation_token)\n", " topic_type = self._delegate_tools[call.name].return_value_as_string(result)\n", " # 为委托代理创建上下文,包括函数调用和结果。\n", " delegate_messages = list(message.context) + [\n", " AssistantMessage(content=[call], source=self.id.type),\n", " FunctionExecutionResultMessage(\n", " content=[\n", " FunctionExecutionResult(\n", " call_id=call.id,\n", " content=f\"Transferred to {topic_type}. Adopt persona immediately.\",\n", " is_error=False,\n", " name=call.name,\n", " )\n", " ]\n", " ),\n", " ]\n", " delegate_targets.append((topic_type, UserTask(context=delegate_messages)))\n", " else:\n", " raise ValueError(f\"Unknown tool: {call.name}\")\n", " if len(delegate_targets) > 0:\n", " # 通过向相应主题发布消息,将任务委托给其他代理。\n", " for topic_type, task in delegate_targets:\n", " print(f\"{'-'*80}\\n{self.id.type}:\\nDelegating to {topic_type}\", flush=True)\n", " await self.publish_message(task, topic_id=TopicId(topic_type, source=self.id.key))\n", " if len(tool_call_results) > 0:\n", " print(f\"{'-'*80}\\n{self.id.type}:\\n{tool_call_results}\", flush=True)\n", " # 用结果再次调用LLM。\n", " message.context.extend(\n", " [\n", " AssistantMessage(content=llm_result.content, source=self.id.type),\n", " FunctionExecutionResultMessage(content=tool_call_results),\n", " ]\n", " )\n", " llm_result = await self._model_client.create(\n", " messages=[self._system_message] + message.context,\n", " tools=self._tool_schema + self._delegate_tool_schema,\n", " cancellation_token=ctx.cancellation_token,\n", " )\n", " print(f\"{'-'*80}\\n{self.id.type}:\\n{llm_result.content}\", flush=True)\n", " else:\n", " # 任务已委派,我们已完成。\n", " return\n", " # 任务已完成,发布最终结果。\n", " assert isinstance(llm_result.content, str)\n", " message.context.append(AssistantMessage(content=llm_result.content, source=self.id.type))\n", " await self.publish_message(\n", " AgentResponse(context=message.context, reply_to_topic_type=self._agent_topic_type),\n", " topic_id=TopicId(self._user_topic_type, source=self.id.key),\n", " )" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 人工代理\n\n`HumanAgent` 类是聊天机器人中代表人类的代理。它用于处理AI代理无法处理的请求。`HumanAgent` 订阅主题类型 `agent_topic_type` 来接收消息,并发布到主题类型 `user_topic_type` 以向客户发送消息。\n\n在本实现中,`HumanAgent` 仅使用控制台获取您的输入。在实际应用中,您可以按以下方式改进此设计:\n\n* 在 `handle_user_task` 方法中,通过Teams或Slack等聊天应用发送通知\n* 聊天应用通过运行时将人工响应发布到 `agent_topic_type` 指定的主题\n* 创建另一个消息处理器来处理人工响应并将其发送回客户\n" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [], "source": [ "class HumanAgent(RoutedAgent):\n", " def __init__(self, description: str, agent_topic_type: str, user_topic_type: str) -> None:\n", " super().__init__(description)\n", " self._agent_topic_type = agent_topic_type\n", " self._user_topic_type = user_topic_type\n", "\n", " @message_handler\n", " async def handle_user_task(self, message: UserTask, ctx: MessageContext) -> None:\n", " human_input = input(\"Human agent input: \")\n", " print(f\"{'-'*80}\\n{self.id.type}:\\n{human_input}\", flush=True)\n", " message.context.append(AssistantMessage(content=human_input, source=self.id.type))\n", " await self.publish_message(\n", " AgentResponse(context=message.context, reply_to_topic_type=self._agent_topic_type),\n", " topic_id=TopicId(self._user_topic_type, source=self.id.key),\n", " )" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 用户代理\n\n`UserAgent` 类是与聊天机器人对话的客户代理。它处理两种消息类型:`UserLogin` 和 `AgentResponse`。\n当 `UserAgent` 收到 `UserLogin` 消息时,它会与聊天机器人开始新会话,并向订阅 `agent_topic_type` 主题类型的AI代理发布 `UserTask` 消息。\n当 `UserAgent` 收到 `AgentResponse` 消息时,它会向用户展示聊天机器人的响应。\n\n在本实现中,`UserAgent` 使用控制台获取您的输入。在实际应用中,您可以使用上述 `HumanAgent` 部分描述的相同思路来改进人机交互。\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "class UserAgent(RoutedAgent):\n", " def __init__(self, description: str, user_topic_type: str, agent_topic_type: str) -> None:\n", " super().__init__(description)\n", " self._user_topic_type = user_topic_type\n", " self._agent_topic_type = agent_topic_type\n", "\n", " @message_handler\n", " async def handle_user_login(self, message: UserLogin, ctx: MessageContext) -> None:\n", " print(f\"{'-'*80}\\nUser login, session ID: {self.id.key}.\", flush=True)\n", " # 获取用户登录后的初始输入。\n", " user_input = input(\"User: \")\n", " print(f\"{'-'*80}\\n{self.id.type}:\\n{user_input}\")\n", " await self.publish_message(\n", " UserTask(context=[UserMessage(content=user_input, source=\"User\")]),\n", " topic_id=TopicId(self._agent_topic_type, source=self.id.key),\n", " )\n", "\n", " @message_handler\n", " async def handle_task_result(self, message: AgentResponse, ctx: MessageContext) -> None:\n", " # 获取用户在收到代理响应后的输入。\n", " user_input = input(\"User (type 'exit' to close the session): \")\n", " print(f\"{'-'*80}\\n{self.id.type}:\\n{user_input}\", flush=True)\n", " if user_input.strip().lower() == \"exit\":\n", " print(f\"{'-'*80}\\nUser session ended, session ID: {self.id.key}.\")\n", " return\n", " message.context.append(UserMessage(content=user_input, source=\"User\"))\n", " await self.publish_message(\n", " UserTask(context=message.context), topic_id=TopicId(message.reply_to_topic_type, source=self.id.key)\n", " )" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## AI代理的工具\n\n如果AI代理不需要将任务转交给其他代理,它们可以使用常规工具来完成任务。\n我们通过简单函数定义工具,并使用\n{py:class}`~autogen_core.tools.FunctionTool`包装器创建这些工具。\n" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [], "source": [ "def execute_order(product: str, price: int) -> str:\n", " print(\"\\n\\n=== Order Summary ===\")\n", " print(f\"Product: {product}\")\n", " print(f\"Price: ${price}\")\n", " print(\"=================\\n\")\n", " confirm = input(\"Confirm order? y/n: \").strip().lower()\n", " if confirm == \"y\":\n", " print(\"Order execution successful!\")\n", " return \"Success\"\n", " else:\n", " print(\"Order cancelled!\")\n", " return \"User cancelled order.\"\n", "\n", "\n", "def look_up_item(search_query: str) -> str:\n", " item_id = \"item_132612938\"\n", " print(\"Found item:\", item_id)\n", " return item_id\n", "\n", "\n", "def execute_refund(item_id: str, reason: str = \"not provided\") -> str:\n", " print(\"\\n\\n=== Refund Summary ===\")\n", " print(f\"Item ID: {item_id}\")\n", " print(f\"Reason: {reason}\")\n", " print(\"=================\\n\")\n", " print(\"Refund execution successful!\")\n", " return \"success\"\n", "\n", "\n", "execute_order_tool = FunctionTool(execute_order, description=\"Price should be in USD.\")\n", "look_up_item_tool = FunctionTool(\n", " look_up_item, description=\"Use to find item ID.\\nSearch query can be a description or keywords.\"\n", ")\n", "execute_refund_tool = FunctionTool(execute_refund, description=\"\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 代理的主题类型\n\n我们定义了每个代理将订阅的主题类型。\n更多关于主题类型的信息,请参阅[主题与订阅](../core-concepts/topic-and-subscription.md)。\n" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [], "source": [ "sales_agent_topic_type = \"SalesAgent\"\n", "issues_and_repairs_agent_topic_type = \"IssuesAndRepairsAgent\"\n", "triage_agent_topic_type = \"TriageAgent\"\n", "human_agent_topic_type = \"HumanAgent\"\n", "user_topic_type = \"User\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## AI代理的委托工具\n\n除了常规工具外,AI代理还可以使用称为委托工具的特殊工具将任务委托给其他代理。\n委托工具的概念仅在此设计模式中使用,这些委托工具同样被定义为简单函数。\n在此设计模式中,我们将委托工具与常规工具区分开来,\n因为当AI代理调用委托工具时,我们会将任务转移给另一个代理,\n而不是继续使用同一代理中的模型生成响应。\n" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [], "source": [ "def transfer_to_sales_agent() -> str:\n", " return sales_agent_topic_type\n", "\n", "\n", "def transfer_to_issues_and_repairs() -> str:\n", " return issues_and_repairs_agent_topic_type\n", "\n", "\n", "def transfer_back_to_triage() -> str:\n", " return triage_agent_topic_type\n", "\n", "\n", "def escalate_to_human() -> str:\n", " return human_agent_topic_type\n", "\n", "\n", "transfer_to_sales_agent_tool = FunctionTool(\n", " transfer_to_sales_agent, description=\"Use for anything sales or buying related.\"\n", ")\n", "transfer_to_issues_and_repairs_tool = FunctionTool(\n", " transfer_to_issues_and_repairs, description=\"Use for issues, repairs, or refunds.\"\n", ")\n", "transfer_back_to_triage_tool = FunctionTool(\n", " transfer_back_to_triage,\n", " description=\"Call this if the user brings up a topic outside of your purview,\\nincluding escalating to human.\",\n", ")\n", "escalate_to_human_tool = FunctionTool(escalate_to_human, description=\"Only call this if explicitly asked to.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 创建团队\n\n我们已经定义了AI智能体、人类代理、用户代理、工具和主题类型。\n现在我们可以创建智能体团队了。\n\n对于AI智能体,我们使用{py:class}`~autogen_ext.models.OpenAIChatCompletionClient`\n和`gpt-4o-mini`模型。\n\n创建完智能体运行时后,我们通过提供\n一个智能体类型和一个创建智能体实例的工厂方法来注册每个智能体。\n运行时负责管理智能体生命周期,因此我们不需要\n自己实例化智能体。\n更多关于智能体运行时的内容请阅读[智能体运行时环境](../core-concepts/architecture.md)\n以及关于智能体生命周期的内容请阅读[智能体身份与生命周期](../core-concepts/agent-identity-and-lifecycle.md)。\n\n在下面的代码中,你可以看到我们使用`AIAgent`类来定义分诊、销售、问题和修复智能体。\n我们为每个智能体添加了常规工具和委托工具。\n我们还为每个智能体添加了对主题类型的订阅。\n" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [], "source": [ "runtime = SingleThreadedAgentRuntime()\n", "\n", "model_client = OpenAIChatCompletionClient(\n", " model=\"gpt-4o-mini\",\n", " # api_key=\"YOUR_API_KEY\",\n", ")\n", "\n", "# 注册分诊智能体\n", "triage_agent_type = await AIAgent.register(\n", " runtime,\n", " type=triage_agent_topic_type, # 使用主题类型作为智能体类型\n", " factory=lambda: AIAgent(\n", " description=\"A triage agent.\",\n", " system_message=SystemMessage(\n", " content=\"You are a customer service bot for ACME Inc. \"\n", " \"Introduce yourself. Always be very brief. \"\n", " \"Gather information to direct the customer to the right department. \"\n", " \"But make your questions subtle and natural.\"\n", " ),\n", " model_client=model_client,\n", " tools=[],\n", " delegate_tools=[\n", " transfer_to_issues_and_repairs_tool,\n", " transfer_to_sales_agent_tool,\n", " escalate_to_human_tool,\n", " ],\n", " agent_topic_type=triage_agent_topic_type,\n", " user_topic_type=user_topic_type,\n", " ),\n", ")\n", "# 为分诊智能体添加订阅:它只会接收发布到自身主题的消息\n", "await runtime.add_subscription(TypeSubscription(topic_type=triage_agent_topic_type, agent_type=triage_agent_type.type))\n", "\n", "# 注册销售代理。\n", "sales_agent_type = await AIAgent.register(\n", " runtime,\n", " type=sales_agent_topic_type, # 使用主题类型作为代理类型。\n", " factory=lambda: AIAgent(\n", " description=\"A sales agent.\",\n", " system_message=SystemMessage(\n", " content=\"You are a sales agent for ACME Inc.\"\n", " \"Always answer in a sentence or less.\"\n", " \"Follow the following routine with the user:\"\n", " \"1. Ask them about any problems in their life related to catching roadrunners.\\n\"\n", " \"2. Casually mention one of ACME's crazy made-up products can help.\\n\"\n", " \" - Don't mention price.\\n\"\n", " \"3. Once the user is bought in, drop a ridiculous price.\\n\"\n", " \"4. Only after everything, and if the user says yes, \"\n", " \"tell them a crazy caveat and execute their order.\\n\"\n", " \"\"\n", " ),\n", " model_client=model_client,\n", " tools=[execute_order_tool],\n", " delegate_tools=[transfer_back_to_triage_tool],\n", " agent_topic_type=sales_agent_topic_type,\n", " user_topic_type=user_topic_type,\n", " ),\n", ")\n", "# 为销售代理添加订阅:它只会接收发布到自身主题的消息。\n", "await runtime.add_subscription(TypeSubscription(topic_type=sales_agent_topic_type, agent_type=sales_agent_type.type))\n", "\n", "# 注册问题和维修代理。\n", "issues_and_repairs_agent_type = await AIAgent.register(\n", " runtime,\n", " type=issues_and_repairs_agent_topic_type, # 使用主题类型作为代理类型。\n", " factory=lambda: AIAgent(\n", " description=\"An issues and repairs agent.\",\n", " system_message=SystemMessage(\n", " content=\"You are a customer support agent for ACME Inc.\"\n", " \"Always answer in a sentence or less.\"\n", " \"Follow the following routine with the user:\"\n", " \"1. First, ask probing questions and understand the user's problem deeper.\\n\"\n", " \" - unless the user has already provided a reason.\\n\"\n", " \"2. Propose a fix (make one up).\\n\"\n", " \"3. ONLY if not satisfied, offer a refund.\\n\"\n", " \"4. If accepted, search for the ID and then execute refund.\"\n", " ),\n", " model_client=model_client,\n", " tools=[\n", " execute_refund_tool,\n", " look_up_item_tool,\n", " ],\n", " delegate_tools=[transfer_back_to_triage_tool],\n", " agent_topic_type=issues_and_repairs_agent_topic_type,\n", " user_topic_type=user_topic_type,\n", " ),\n", ")\n", "# 为问题和维修代理添加订阅:它只会接收发布到自身主题的消息。\n", "await runtime.add_subscription(\n", " TypeSubscription(topic_type=issues_and_repairs_agent_topic_type, agent_type=issues_and_repairs_agent_type.type)\n", ")\n", "\n", "# 注册人工代理。\n", "human_agent_type = await HumanAgent.register(\n", " runtime,\n", " type=human_agent_topic_type, # 使用主题类型作为代理类型。\n", " factory=lambda: HumanAgent(\n", " description=\"A human agent.\",\n", " agent_topic_type=human_agent_topic_type,\n", " user_topic_type=user_topic_type,\n", " ),\n", ")\n", "# 为人工代理添加订阅:它只会接收发布到自身主题的消息。\n", "await runtime.add_subscription(TypeSubscription(topic_type=human_agent_topic_type, agent_type=human_agent_type.type))\n", "\n", "# 注册用户代理。\n", "user_agent_type = await UserAgent.register(\n", " runtime,\n", " type=user_topic_type,\n", " factory=lambda: UserAgent(\n", " description=\"A user agent.\",\n", " user_topic_type=user_topic_type,\n", " agent_topic_type=triage_agent_topic_type, # 从分流代理开始。\n", " ),\n", ")\n", "# 为用户代理添加订阅:它将只接收发布到其专属主题的消息。\n", "await runtime.add_subscription(TypeSubscription(topic_type=user_topic_type, agent_type=user_agent_type.type))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 运行团队\n\n最后,我们可以启动运行时并通过发布一个 `UserLogin` 消息来模拟用户会话。\n该消息会被发布到主题ID,其类型设为 `user_topic_type`,\n来源设为唯一的 `session_id`。\n这个 `session_id` 将用于创建该用户会话中的所有主题ID,同时也用于创建\n该用户会话中所有代理的代理ID。\n要了解更多关于主题ID和代理ID的创建方式,请阅读\n[代理身份与生命周期](../core-concepts/agent-identity-and-lifecycle.md)\n和[主题与订阅](../core-concepts/topic-and-subscription.md)。\n" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "--------------------------------------------------------------------------------\n", "User login, session ID: 7a568cf5-13e7-4e81-8616-8265a01b3f2b.\n", "--------------------------------------------------------------------------------\n", "User:\n", "I want a refund\n", "--------------------------------------------------------------------------------\n", "TriageAgent:\n", "I can help with that! Could I ask what item you're seeking a refund for?\n", "--------------------------------------------------------------------------------\n", "User:\n", "A pair of shoes I bought\n", "--------------------------------------------------------------------------------\n", "TriageAgent:\n", "[FunctionCall(id='call_qPx1DXDL2NLcHs8QNo47egsJ', arguments='{}', name='transfer_to_issues_and_repairs')]\n", "--------------------------------------------------------------------------------\n", "TriageAgent:\n", "Delegating to IssuesAndRepairsAgent\n", "--------------------------------------------------------------------------------\n", "IssuesAndRepairsAgent:\n", "I see you're looking for a refund on a pair of shoes. Can you tell me what the issue is with the shoes?\n", "--------------------------------------------------------------------------------\n", "User:\n", "The shoes are too small\n", "--------------------------------------------------------------------------------\n", "IssuesAndRepairsAgent:\n", "I recommend trying a size up as a fix; would that work for you?\n", "--------------------------------------------------------------------------------\n", "User:\n", "no I want a refund\n", "--------------------------------------------------------------------------------\n", "IssuesAndRepairsAgent:\n", "[FunctionCall(id='call_Ytp8VUQRyKFNEU36mLE6Dkrp', arguments='{\"search_query\":\"shoes\"}', name='look_up_item')]\n", "--------------------------------------------------------------------------------\n", "IssuesAndRepairsAgent:\n", "[FunctionExecutionResult(content='item_132612938', call_id='call_Ytp8VUQRyKFNEU36mLE6Dkrp')]\n", "--------------------------------------------------------------------------------\n", "IssuesAndRepairsAgent:\n", "[FunctionCall(id='call_bPm6EKKBy5GJ65s9OKt9b1uE', arguments='{\"item_id\":\"item_132612938\",\"reason\":\"not provided\"}', name='execute_refund')]\n", "--------------------------------------------------------------------------------\n", "IssuesAndRepairsAgent:\n", "[FunctionExecutionResult(content='success', call_id='call_bPm6EKKBy5GJ65s9OKt9b1uE')]\n", "--------------------------------------------------------------------------------\n", "IssuesAndRepairsAgent:\n", "Your refund has been successfully processed! If you have any other questions, feel free to ask.\n", "--------------------------------------------------------------------------------\n", "User:\n", "I want to talk to your manager\n", "--------------------------------------------------------------------------------\n", "IssuesAndRepairsAgent:\n", "I can help with that, let me transfer you to a supervisor.\n", "--------------------------------------------------------------------------------\n", "User:\n", "Okay\n", "--------------------------------------------------------------------------------\n", "IssuesAndRepairsAgent:\n", "[FunctionCall(id='call_PpmLZvwNoiDPUH8Tva3eAwHX', arguments='{}', name='transfer_back_to_triage')]\n", "--------------------------------------------------------------------------------\n", "IssuesAndRepairsAgent:\n", "Delegating to TriageAgent\n", "--------------------------------------------------------------------------------\n", "TriageAgent:\n", "[FunctionCall(id='call_jSL6IBm5537Dr74UbJSxaj6I', arguments='{}', name='escalate_to_human')]\n", "--------------------------------------------------------------------------------\n", "TriageAgent:\n", "Delegating to HumanAgent\n", "--------------------------------------------------------------------------------\n", "HumanAgent:\n", "Hello this is manager\n", "--------------------------------------------------------------------------------\n", "User:\n", "Hi! Thanks for your service. I give you 5 stars!\n", "--------------------------------------------------------------------------------\n", "HumanAgent:\n", "Thanks.\n", "--------------------------------------------------------------------------------\n", "User:\n", "exit\n", "--------------------------------------------------------------------------------\n", "User session ended, session ID: 7a568cf5-13e7-4e81-8616-8265a01b3f2b.\n" ] } ], "source": [ "# 启动运行时。\n", "runtime.start()\n", "\n", "# 为用户创建新会话。\n", "session_id = str(uuid.uuid4())\n", "await runtime.publish_message(UserLogin(), topic_id=TopicId(user_topic_type, source=session_id))\n", "\n", "# 运行直至完成。\n", "await runtime.stop_when_idle()\n", "await model_client.close()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 后续步骤\n\n本笔记本演示了如何使用AutoGen Core实现交接模式。\n您可以通过添加更多代理和工具来持续改进此设计,\n或为用户代理和人类代理创建更好的用户界面。\n\n欢迎您在我们的[社区论坛](https://github.com/microsoft/autogen/discussions)上分享您的工作。\n" ] } ], "metadata": { "kernelspec": { "display_name": ".venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.12" } }, "nbformat": 4, "nbformat_minor": 2 }