{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Agents\n", "\n", "```{include} ../warning.md\n", "```\n", "\n", "AutoGen AgentChat 提供了一组预设代理,每个代理在响应消息的方式上都有所不同。\n", "所有代理都共享以下属性和方法:\n", "\n", "- {py:attr}`~autogen_agentchat.agents.BaseChatAgent.name`: 代理的唯一名称。\n", "- {py:attr}`~autogen_agentchat.agents.BaseChatAgent.description`: 代理的文本描述。\n", "- {py:meth}`~autogen_agentchat.agents.BaseChatAgent.on_messages`: 向代理发送一系列{py:class}`~autogen_agentchat.messages.ChatMessage` 并获得 {py:class}`~autogen_agentchat.base.Response`.\n", "- {py:meth}`~autogen_agentchat.agents.BaseChatAgent.on_messages_stream`: 与{py:meth}`~autogen_agentchat.agents.BaseChatAgent.on_messages` 相同,但返回一个迭代器,包含{py:class}`~autogen_agentchat.messages.AgentMessage` ,最后一项是 {py:class}`~autogen_agentchat.base.Response` 。\n", "- {py:meth}`~autogen_agentchat.agents.BaseChatAgent.on_reset`: 将代理重置为初始状态。\n", "\n", "有关 AgentChat 消息类型的更多信息,请参见 {py:mod}`autogen_agentchat.messages`。\n", "\n", "\n", "## Assistant Agent\n", "\n", "{py:class}`~autogen_agentchat.agents.AssistantAgent` 是一个内置代理,\n", "它使用具有使用工具能力的语言模型。" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "from autogen_agentchat.agents import AssistantAgent\n", "from autogen_agentchat.messages import TextMessage\n", "from autogen_core.base import CancellationToken\n", "from autogen_ext.models import OpenAIChatCompletionClient\n", "\n", "# Define a tool that searches the web for information.\n", "async def web_search(query: str) -> str:\n", " \"\"\"Find information on the web\"\"\"\n", " return \"AutoGen is a programming framework for building multi-agent applications.\"\n", "\n", "# Create an agent that uses the OpenAI GPT-4o model.\n", "model_client = OpenAIChatCompletionClient(\n", " model=\"gpt-4o\",\n", " api_key=\"sk-\",\n", ")\n", "agent = AssistantAgent(\n", " name=\"assistant\",\n", " model_client=model_client,\n", " tools=[web_search],\n", " system_message=\"Use tools to solve tasks.\",\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "我们可以调用 {py:meth}`~autogen_agentchat.agents.AssistantAgent.on_messages` \n", "方法来获取代理对消息的响应。" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[ToolCallMessage(source='assistant', models_usage=RequestUsage(prompt_tokens=61, completion_tokens=15), content=[FunctionCall(id='call_90iZvYWtw8YLOvzPIhyYFCaw', arguments='{\"query\":\"AutoGen\"}', name='web_search')]), ToolCallResultMessage(source='assistant', models_usage=None, content=[FunctionExecutionResult(content='AutoGen is a programming framework for building multi-agent applications.', call_id='call_90iZvYWtw8YLOvzPIhyYFCaw')])]\n", "source='assistant' models_usage=RequestUsage(prompt_tokens=92, completion_tokens=14) content='AutoGen is a programming framework used for building multi-agent applications.'\n" ] } ], "source": [ "async def assistant_run() -> None:\n", " response = await agent.on_messages(\n", " [TextMessage(content=\"Find information on AutoGen\", source=\"user\")],\n", " cancellation_token=CancellationToken(),\n", " )\n", " print(response.inner_messages)\n", " print(response.chat_message)\n", "\n", "\n", "# Use asyncio.run(assistant_run()) when running in a script.\n", "await assistant_run()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "调用 {py:meth}`~autogen_agentchat.agents.AssistantAgent.on_messages` 方法\n", "会返回一个 {py:class}`~autogen_agentchat.base.Response`,\n", "其中包含代理的最终响应(在 {py:attr}`~autogen_agentchat.base.Response.chat_message` 属性中),\n", "以及一个内部消息列表(在 {py:attr}`~autogen_agentchat.base.Response.inner_messages` 属性中),\n", "这些内部消息存储了代理产生最终响应的\"思考过程\"。\n", "\n", "### 流式消息\n", "\n", "我们还可以使用 {py:meth}`~autogen_agentchat.agents.AssistantAgent.on_messages_stream` 方法\n", "来实时流式获取代理生成的每条消息,\n", "并使用 {py:class}`~autogen_agentchat.task.Console` 将消息\n", "实时打印到控制台。" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "---------- assistant ----------\n", "[FunctionCall(id='call_VfVDAK3OBqB9BQ6emRoraTKe', arguments='{\"query\":\"AutoGen programming framework\"}', name='web_search')]\n", "[Prompt tokens: 127, Completion tokens: 17]\n", "---------- assistant ----------\n", "[FunctionExecutionResult(content='AutoGen is a programming framework for building multi-agent applications.', call_id='call_VfVDAK3OBqB9BQ6emRoraTKe')]\n", "---------- assistant ----------\n", "AutoGen is a programming framework designed for developing multi-agent applications.\n", "[Prompt tokens: 160, Completion tokens: 14]\n", "---------- Summary ----------\n", "Number of inner messages: 2\n", "Total prompt tokens: 287\n", "Total completion tokens: 31\n", "Duration: 1.88 seconds\n" ] } ], "source": [ "from autogen_agentchat.task import Console\n", "\n", "\n", "async def assistant_run_stream() -> None:\n", " # Option 1: read each message from the stream.\n", " # async for message in agent.on_messages_stream(\n", " # [TextMessage(content=\"Find information on AutoGen\", source=\"user\")],\n", " # cancellation_token=CancellationToken(),\n", " # ):\n", " # print(message)\n", "\n", " # Option 2: use Console to print all messages as they appear.\n", " await Console(\n", " agent.on_messages_stream(\n", " [TextMessage(content=\"Find information on AutoGen\", source=\"user\")],\n", " cancellation_token=CancellationToken(),\n", " )\n", " )\n", "\n", "\n", "# Use asyncio.run(assistant_run_stream()) when running in a script.\n", "await assistant_run_stream()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "{py:meth}`~autogen_agentchat.agents.AssistantAgent.on_messages_stream` 方法返回一个异步生成器,它会生成代理产生的每条内部消息,\n", "最后一项是 {py:attr}`~autogen_agentchat.base.Response.chat_message` 属性中的最终响应消息。\n", "\n", "从消息中可以看到,助手代理使用了 `web_search` 工具来搜索信息,并使用搜索结果进行响应。\n", "\n", "### 理解工具调用\n", "\n", "大型语言模型(LLMs)通常仅限于生成文本或代码响应。然而,许多复杂任务都能从使用外部工具执行特定操作中受益,比如从 API 或数据库获取数据。\n", "\n", "为了解决这个限制,现代 LLMs 现在可以接受一个可用工具模式列表(工具及其参数的描述)并生成工具调用消息。这种能力被称为**Tool Calling**或**Function Calling**,正在成为构建智能代理应用程序的流行模式。\n", "\n", "有关工具调用的更多信息,请参阅 [OpenAI](https://platform.openai.com/docs/guides/function-calling) 和 [Anthropic](https://docs.anthropic.com/en/docs/build-with-claude/tool-use) 的文档。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 其他预设代理\n", "\n", "以下预设代理可供使用:\n", "\n", "- {py:class}`~autogen_agentchat.agents.CodeExecutorAgent`: 一个可以执行代码的代理。\n", "- {py:class}`~autogen_ext.agents.MultimodalWebSurfer`: 一个多模态代理,可以搜索网页并访问网页获取信息。\n", "\n", "## 下一步\n", "\n", "现在我们已经讨论了如何使用 {py:class}`~autogen_agentchat.agents.AssistantAgent`,\n", "我们可以继续下一节来学习如何使用 AgentChat 的团队功能。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] } ], "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.12.3" } }, "nbformat": 4, "nbformat_minor": 2 }