通过 AgentChat,您可以使用预设的代理快速构建应用程序。为了说明这一点,我们将从创建一个可以使用工具的单个代理开始。

首先,我们需要安装 AgentChat 和 Extension 包。

pip install -U "autogen-agentchat" "autogen-ext[openai,azure]"

此示例使用 OpenAI 模型,但您也可以使用其他模型。只需使用所需的模型或模型客户端类更新 model_client 即可。

要使用 Azure OpenAI 模型和 AAD 身份验证,您可以按照此处的说明进行操作。要使用其他模型,请参阅模型

from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.ui import Console
from autogen_ext.models.openai import OpenAIChatCompletionClient

# Define a model client. You can use other model client that implements
# the `ChatCompletionClient` interface.
model_client = OpenAIChatCompletionClient(
    model="gpt-4o",
    # api_key="YOUR_API_KEY",
)

# Define a simple function tool that the agent can use.
# For this example, we use a fake weather tool for demonstration purposes.
async def get_weather(city: str) -> str:
    """Get the weather for a given city."""
    return f"The weather in {city} is 73 degrees and Sunny."

# Define an AssistantAgent with the model, tool, system message, and reflection enabled.
# The system message instructs the agent via natural language.
agent = AssistantAgent(
    name="weather_agent",
    model_client=model_client,
    tools=[get_weather],
    system_message="You are a helpful assistant.",
    reflect_on_tool_use=True,
    model_client_stream=True,  # Enable streaming tokens from the model client.
)

# Run the agent and stream the messages to the console.
async def main() -> None:
    await Console(agent.run_stream(task="What is the weather in New York?"))
    # Close the connection to the model client.
    await model_client.close()

# NOTE: if running this inside a Python script you'll need to use asyncio.run(main()).
await main()
---------- user ----------
What is the weather in New York?
---------- weather_agent ----------
[FunctionCall(id='call_bE5CYAwB7OlOdNAyPjwOkej1', arguments='{"city":"New York"}', name='get_weather')]
---------- weather_agent ----------
[FunctionExecutionResult(content='The weather in New York is 73 degrees and Sunny.', call_id='call_bE5CYAwB7OlOdNAyPjwOkej1', is_error=False)]
---------- weather_agent ----------
The current weather in New York is 73 degrees and sunny.

源代码如下:

{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Quickstart"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Via AgentChat, you can build applications quickly using preset agents.\n",
    "To illustrate this, we will begin with creating a single agent that can\n",
    "use tools.\n",
    "\n",
    "First, we need to install the AgentChat and Extension packages."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "vscode": {
     "languageId": "shellscript"
    }
   },
   "outputs": [],
   "source": [
    "pip install -U \"autogen-agentchat\" \"autogen-ext[openai,azure]\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This example uses an OpenAI model, however, you can use other models as well.\n",
    "Simply update the `model_client` with the desired model or model client class.\n",
    "\n",
    "To use Azure OpenAI models and AAD authentication,\n",
    "you can follow the instructions [here](./tutorial/models.ipynb#azure-openai).\n",
    "To use other models, see [Models](./tutorial/models.ipynb)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "---------- user ----------\n",
      "What is the weather in New York?\n",
      "---------- weather_agent ----------\n",
      "[FunctionCall(id='call_bE5CYAwB7OlOdNAyPjwOkej1', arguments='{\"city\":\"New York\"}', name='get_weather')]\n",
      "---------- weather_agent ----------\n",
      "[FunctionExecutionResult(content='The weather in New York is 73 degrees and Sunny.', call_id='call_bE5CYAwB7OlOdNAyPjwOkej1', is_error=False)]\n",
      "---------- weather_agent ----------\n",
      "The current weather in New York is 73 degrees and sunny.\n"
     ]
    }
   ],
   "source": [
    "from autogen_agentchat.agents import AssistantAgent\n",
    "from autogen_agentchat.ui import Console\n",
    "from autogen_ext.models.openai import OpenAIChatCompletionClient\n",
    "\n",
    "# Define a model client. You can use other model client that implements\n",
    "# the `ChatCompletionClient` interface.\n",
    "model_client = OpenAIChatCompletionClient(\n",
    "    model=\"gpt-4o\",\n",
    "    # api_key=\"YOUR_API_KEY\",\n",
    ")\n",
    "\n",
    "\n",
    "# Define a simple function tool that the agent can use.\n",
    "# For this example, we use a fake weather tool for demonstration purposes.\n",
    "async def get_weather(city: str) -> str:\n",
    "    \"\"\"Get the weather for a given city.\"\"\"\n",
    "    return f\"The weather in {city} is 73 degrees and Sunny.\"\n",
    "\n",
    "\n",
    "# Define an AssistantAgent with the model, tool, system message, and reflection enabled.\n",
    "# The system message instructs the agent via natural language.\n",
    "agent = AssistantAgent(\n",
    "    name=\"weather_agent\",\n",
    "    model_client=model_client,\n",
    "    tools=[get_weather],\n",
    "    system_message=\"You are a helpful assistant.\",\n",
    "    reflect_on_tool_use=True,\n",
    "    model_client_stream=True,  # Enable streaming tokens from the model client.\n",
    ")\n",
    "\n",
    "\n",
    "# Run the agent and stream the messages to the console.\n",
    "async def main() -> None:\n",
    "    await Console(agent.run_stream(task=\"What is the weather in New York?\"))\n",
    "    # Close the connection to the model client.\n",
    "    await model_client.close()\n",
    "\n",
    "\n",
    "# NOTE: if running this inside a Python script you'll need to use asyncio.run(main()).\n",
    "await main()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## What's Next?\n",
    "\n",
    "Now that you have a basic understanding of how to use a single agent, consider following the [tutorial](./tutorial/index.md) for a walkthrough on other features of AgentChat."
   ]
  }
 ],
 "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.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐