快速入门#

通过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?"))


# 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.

接下来是什么?#

既然你已经对如何使用单个代理有了基本的了解,考虑跟随教程来了解AgentChat的其他功能。