ag2-quickstart

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Quickstart: build your first AG2 Agent

快速入门:构建你的第一个AG2 Agent

When to use

适用场景

  • The user is starting from a blank file and wants a working AG2 agent.
  • The user is unsure which provider config to use.
  • The user wants to chain follow-up turns without losing conversation context.
  • A larger task needs the basic Agent setup as its skeleton — start here, then layer the relevant feature skill on top.
  • 用户从零开始编写代码,想要一个可运行的AG2 Agent。
  • 用户不确定该使用哪种提供商配置。
  • 用户希望在不丢失对话上下文的情况下进行多轮后续交互。
  • 大型任务需要以基础Agent设置为框架——从这里开始,再添加相关的功能模块。

Prerequisites

前置条件

Required step: install dependencies before finishing. After writing AG2 code, install the matching provider extra (plus any feature extra the task needs, e.g.
ag-ui
,
tracing
). Run the install:
bash
pip install "ag2[openai]"   # swap in the provider/extra you used
If you cannot run commands, state the exact
pip install
command. This is part of finishing the task, not an optional note.
For a multi-file project (more than a throwaway script), also drop a
requirements.txt
pinning
ag2
with the extras you used (e.g.
ag2[openai]>=0.14.0
) so the environment is reproducible.
Install the right provider extra and have a key for it. Each
*Config
requires its provider SDK — without the matching extra you'll see
ImportError: ... requires optional dependencies. Install with pip install "ag2[<provider>]"
.
ProviderInstallEnv varConfig class
OpenAI
pip install "ag2[openai]"
OPENAI_API_KEY
OpenAIConfig
,
OpenAIResponsesConfig
Anthropic
pip install "ag2[anthropic]"
ANTHROPIC_API_KEY
AnthropicConfig
Gemini (API key)
pip install "ag2[gemini]"
GEMINI_API_KEY
(or
GOOGLE_API_KEY
)
GeminiConfig
Vertex AI (Gemini)
pip install "ag2[gemini]"
service-account / ADC
VertexAIConfig
Ollama (local)
pip install "ag2[ollama]"
OllamaConfig
DashScope (Qwen)
pip install "ag2[dashscope]"
DASHSCOPE_API_KEY
DashScopeConfig
Load env vars from a project-root
.env
with
python-dotenv
so scripts pick up keys without exporting them in your shell:
python
from dotenv import load_dotenv
load_dotenv()  # reads .env at project root
Quick sanity-check before debugging weird import errors — make sure you're running against the ag2 you think:
bash
python -c "import sys, ag2; from importlib.metadata import version; print(sys.executable); print('ag2', version('ag2'))"
必填步骤:完成前先安装依赖。 编写AG2代码后,安装匹配的提供商扩展包(以及任务所需的任何功能扩展包,例如
ag-ui
tracing
)。运行以下安装命令:
bash
pip install "ag2[openai]"   # 替换为你使用的提供商/扩展包
如果你无法执行命令,请明确说明具体的
pip install
命令。这是完成任务的一部分,而非可选提示。
对于多文件项目(不仅仅是一次性脚本),还需创建
requirements.txt
文件,固定你使用的带扩展包的
ag2
版本(例如
ag2[openai]>=0.14.0
),以确保环境可复现。
安装对应提供商的扩展包并获取其密钥。每个
*Config
都需要对应的提供商SDK——如果没有安装匹配的扩展包,你会看到
ImportError: ... requires optional dependencies. Install with pip install "ag2[<provider>]"
错误。
提供商安装命令环境变量配置类
OpenAI
pip install "ag2[openai]"
OPENAI_API_KEY
OpenAIConfig
,
OpenAIResponsesConfig
Anthropic
pip install "ag2[anthropic]"
ANTHROPIC_API_KEY
AnthropicConfig
Gemini(API密钥)
pip install "ag2[gemini]"
GEMINI_API_KEY
(或
GOOGLE_API_KEY
GeminiConfig
Vertex AI(Gemini)
pip install "ag2[gemini]"
服务账号/ADC
VertexAIConfig
Ollama(本地)
pip install "ag2[ollama]"
OllamaConfig
DashScope(通义千问)
pip install "ag2[dashscope]"
DASHSCOPE_API_KEY
DashScopeConfig
使用
python-dotenv
从项目根目录的
.env
文件加载环境变量,这样脚本无需在shell中导出密钥即可读取:
python
from dotenv import load_dotenv
load_dotenv()  # 读取项目根目录的.env文件
在调试奇怪的导入错误前,先快速检查——确保你运行的是预期版本的ag2:
bash
python -c "import sys, ag2; from importlib.metadata import version; print(sys.executable); print('ag2', version('ag2'))"

60-second recipe

60秒快速实现

python
import asyncio
from ag2 import Agent
from ag2.config import OpenAIConfig

async def main() -> None:
    agent = Agent(
        "assistant",
        prompt="You are a helpful assistant. Reply in one sentence.",
        config=OpenAIConfig(model="gpt-4o-mini"),
    )

    # First turn
    reply = await agent.ask("What is the capital of France?")
    print(reply.body)

    # Continue the same conversation — context is preserved
    reply = await reply.ask("And of Germany?")
    print(reply.body)

asyncio.run(main())
Agent.ask(...)
starts a new turn and returns an
AgentReply
.
AgentReply.ask(...)
continues the same conversation, preserving its context and history. The reply text is in
reply.body
; for typed output see the
ag2-structured-output
skill (
reply.content()
).
python
import asyncio
from ag2 import Agent
from ag2.config import OpenAIConfig

async def main() -> None:
    agent = Agent(
        "assistant",
        prompt="你是一个乐于助人的助手。用一句话回复。",
        config=OpenAIConfig(model="gpt-4o-mini"),
    )

    # 第一轮对话
    reply = await agent.ask("法国的首都是什么?")
    print(reply.body)

    # 继续同一场对话——上下文会被保留
    reply = await reply.ask("那德国的呢?")
    print(reply.body)

asyncio.run(main())
Agent.ask(...)
启动新的对话轮次并返回
AgentReply
AgentReply.ask(...)
继续同一场对话,保留其上下文和历史记录。回复文本位于
reply.body
中;如需结构化输出,请查看
ag2-structured-output
模块(
reply.content()
)。

Picking a provider

选择提供商

Each provider has its own config class in
ag2.config
. All accept
model=
, optional
api_key=
, and (where supported)
streaming=True
. Streaming is recommended — AG2 is async- and streaming-first.
python
from ag2.config import OpenAIConfig          # gpt-4o, gpt-5-*, o-series, etc.
from ag2.config import OpenAIResponsesConfig # OpenAI Responses API (image gen, file_id support)
from ag2.config import AnthropicConfig       # claude-sonnet-4-6, claude-opus-4-7, etc.
from ag2.config import GeminiConfig          # Gemini Developer API (api_key)
from ag2.config import VertexAIConfig        # Gemini on Google Vertex AI (project + location)
from ag2.config import OllamaConfig          # local Ollama
from ag2.config import DashScopeConfig       # Alibaba Qwen

config = AnthropicConfig(model="claude-sonnet-4-6", streaming=True)
If
api_key=
is omitted, the config reads the standard env var —
OPENAI_API_KEY
,
ANTHROPIC_API_KEY
,
GEMINI_API_KEY
(or
GOOGLE_API_KEY
), etc.
For OpenAI-compatible endpoints (vLLM, LM Studio, Together, NVIDIA NIM, etc.) use
OpenAIConfig
with
base_url=
set:
python
config = OpenAIConfig(
    model="qwen-3",
    base_url="http://localhost:8000/v1",
    api_key="NotRequired",  # pragma: allowlist secret
)
每个提供商在
ag2.config
中都有自己的配置类。所有配置类都接受
model=
参数,可选的
api_key=
参数,以及(支持的情况下)
streaming=True
参数。推荐启用流式传输——AG2以异步和流式传输为核心设计。
python
from ag2.config import OpenAIConfig          # gpt-4o, gpt-5-*, o-series等
from ag2.config import OpenAIResponsesConfig # OpenAI Responses API(支持图像生成、file_id)
from ag2.config import AnthropicConfig       # claude-sonnet-4-6, claude-opus-4-7等
from ag2.config import GeminiConfig          # Gemini开发者API(需api_key)
from ag2.config import VertexAIConfig        # Google Vertex AI上的Gemini(需项目+区域)
from ag2.config import OllamaConfig          # 本地Ollama
from ag2.config import DashScopeConfig       # 阿里云通义千问

config = AnthropicConfig(model="claude-sonnet-4-6", streaming=True)
如果省略
api_key=
参数,配置会读取标准环境变量——
OPENAI_API_KEY
ANTHROPIC_API_KEY
GEMINI_API_KEY
(或
GOOGLE_API_KEY
)等。
对于兼容OpenAI的端点(vLLM、LM Studio、Together、NVIDIA NIM等),使用
OpenAIConfig
并设置
base_url=
python
config = OpenAIConfig(
    model="qwen-3",
    base_url="http://localhost:8000/v1",
    api_key="NotRequired",  # pragma: allowlist secret
)

Multi-turn — chain
reply.ask()

多轮交互——链式调用
reply.ask()

python
agent = Agent("planner", prompt="...", config=config)
reply = await agent.ask("Plan a 5-day Japan trip in late April.")
reply = await reply.ask("Budget is $2500 per person, two travellers.")
reply = await reply.ask("Prefer trains. Day-by-day itinerary.")
print(reply.body)
reply.ask()
keeps the prior turns in scope so the LLM remembers the constraints. Calling
agent.ask(...)
again instead would start a fresh conversation. See
assets/multi_turn.py
for the full travel-planner example.
python
agent = Agent("planner", prompt="...", config=config)
reply = await agent.ask("规划一个4月底的5天日本行程。")
reply = await reply.ask("每人预算2500美元,共两位旅行者。")
reply = await reply.ask("偏好乘坐火车。请提供每日行程安排。")
print(reply.body)
reply.ask()
会保留之前的对话轮次,让大语言模型记住约束条件。如果再次调用
agent.ask(...)
,会启动一场全新的对话。完整的旅行规划示例请查看
assets/multi_turn.py

Reusing model configs

复用模型配置

Configs are immutable. Use
.copy(...)
to fork one with overrides:
python
base = OpenAIConfig(model="gpt-5")
hot = base.copy(temperature=0.8)
cheap = base.copy(model="gpt-5-mini")
You can also override the model per ask — useful when the user brings their own API key per request:
python
agent = Agent("assistant", prompt="Help.")
reply = await agent.ask("Hello!", config=OpenAIConfig(model="gpt-5", api_key="sk-..."))  # pragma: allowlist secret
The per-ask config completely replaces the agent's config for that turn.
配置是不可变的。使用
.copy(...)
方法创建带有覆盖参数的副本:
python
base = OpenAIConfig(model="gpt-5")
hot = base.copy(temperature=0.8)
cheap = base.copy(model="gpt-5-mini")
你还可以在每次调用
ask
时覆盖模型配置
——当用户按请求提供自己的API密钥时非常有用:
python
agent = Agent("assistant", prompt="提供帮助。")
reply = await agent.ask("你好!", config=OpenAIConfig(model="gpt-5", api_key="sk-..."))  # pragma: allowlist secret
每次调用
ask
时的配置会完全替换该轮次中Agent的原有配置。

Going deeper

深入学习

  • Working starter (single-turn):
    assets/hello_agent.py
    (mirrors
    code_examples/01
    ).
  • Multi-turn starter:
    assets/multi_turn.py
    (mirrors
    code_examples/03
    ).
  • Full provider reference, including
    VertexAIConfig
    auth,
    extra_body
    , custom
    httpx
    client, env-var fallback table:
    website/docs/user-guide/model_configuration.mdx
    .
  • Agent communication API surface (events, observing, HITL):
    website/docs/user-guide/agents.mdx
    .
  • Static, dynamic, per-turn prompts:
    website/docs/user-guide/system_prompts.mdx
    .
  • 单轮交互入门示例:
    assets/hello_agent.py
    (与
    code_examples/01
    一致)。
  • 多轮交互入门示例:
    assets/multi_turn.py
    (与
    code_examples/03
    一致)。
  • 完整的提供商参考,包括
    VertexAIConfig
    认证、
    extra_body
    、自定义
    httpx
    客户端、环境变量回退表:
    website/docs/user-guide/model_configuration.mdx
  • Agent通信API接口(事件、观测、人机协同):
    website/docs/user-guide/agents.mdx
  • 静态、动态、每轮提示词:
    website/docs/user-guide/system_prompts.mdx

Common pitfalls

常见误区

  • Forgetting to
    await
    — every method on
    Agent
    /
    AgentReply
    is async. Wrap in
    asyncio.run(main())
    for scripts.
  • Calling
    agent.ask()
    twice expecting context to carry
    — it doesn't; use
    reply.ask()
    instead.
  • Hardcoding API keys — prefer env-var fallback (
    OPENAI_API_KEY
    , etc.) so configs commit cleanly.
  • Skipping
    streaming=True
    — AG2 is streaming-first; you'll get a worse user experience without it on supported providers.
  • Per-ask
    config=
    is total override
    , not a partial merge — be deliberate about which knobs you set.
  • 忘记使用
    await
    ——
    Agent
    /
    AgentReply
    上的所有方法都是异步的。脚本中需用
    asyncio.run(main())
    包裹。
  • 两次调用
    agent.ask()
    并期望上下文延续
    ——这不会生效;请改用
    reply.ask()
  • 硬编码API密钥——优先使用环境变量回退机制(
    OPENAI_API_KEY
    等),确保配置可以干净地提交到版本控制系统。
  • 跳过
    streaming=True
    ——AG2以流式传输为核心设计;在支持的提供商上不启用流式传输会导致更差的用户体验。
  • 每次调用
    ask
    时的
    config=
    是完全覆盖,而非部分合并
    ——设置参数时请谨慎考虑。