ag2-quickstart
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseQuickstart: 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). Run the install:tracingbashpip install "ag2[openai]" # swap in the provider/extra you usedIf you cannot run commands, state the exactcommand. This is part of finishing the task, not an optional note.pip installFor a multi-file project (more than a throwaway script), also drop apinningrequirements.txtwith the extras you used (e.g.ag2) so the environment is reproducible.ag2[openai]>=0.14.0
Install the right provider extra and have a key for it. Each requires its provider SDK — without the matching extra you'll see .
*ConfigImportError: ... requires optional dependencies. Install with pip install "ag2[<provider>]"| Provider | Install | Env var | Config class |
|---|---|---|---|
| OpenAI | | | |
| Anthropic | | | |
| Gemini (API key) | | | |
| Vertex AI (Gemini) | | service-account / ADC | |
| Ollama (local) | | — | |
| DashScope (Qwen) | | | |
Load env vars from a project-root with so scripts pick up keys without exporting them in your shell:
.envpython-dotenvpython
from dotenv import load_dotenv
load_dotenv() # reads .env at project rootQuick 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)。运行以下安装命令:tracingbashpip install "ag2[openai]" # 替换为你使用的提供商/扩展包如果你无法执行命令,请明确说明具体的命令。这是完成任务的一部分,而非可选提示。pip install对于多文件项目(不仅仅是一次性脚本),还需创建文件,固定你使用的带扩展包的requirements.txt版本(例如ag2),以确保环境可复现。ag2[openai]>=0.14.0
安装对应提供商的扩展包并获取其密钥。每个都需要对应的提供商SDK——如果没有安装匹配的扩展包,你会看到错误。
*ConfigImportError: ... requires optional dependencies. Install with pip install "ag2[<provider>]"| 提供商 | 安装命令 | 环境变量 | 配置类 |
|---|---|---|---|
| OpenAI | | | |
| Anthropic | | | |
| Gemini(API密钥) | | | |
| Vertex AI(Gemini) | | 服务账号/ADC | |
| Ollama(本地) | | — | |
| DashScope(通义千问) | | | |
使用从项目根目录的文件加载环境变量,这样脚本无需在shell中导出密钥即可读取:
python-dotenv.envpython
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(...)AgentReplyAgentReply.ask(...)reply.bodyag2-structured-outputreply.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(...)AgentReplyAgentReply.ask(...)reply.bodyag2-structured-outputreply.content()Picking a provider
选择提供商
Each provider has its own config class in . All accept , optional , and (where supported) . Streaming is recommended — AG2 is async- and streaming-first.
ag2.configmodel=api_key=streaming=Truepython
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 is omitted, the config reads the standard env var — , , (or ), etc.
api_key=OPENAI_API_KEYANTHROPIC_API_KEYGEMINI_API_KEYGOOGLE_API_KEYFor OpenAI-compatible endpoints (vLLM, LM Studio, Together, NVIDIA NIM, etc.) use with set:
OpenAIConfigbase_url=python
config = OpenAIConfig(
model="qwen-3",
base_url="http://localhost:8000/v1",
api_key="NotRequired", # pragma: allowlist secret
)每个提供商在中都有自己的配置类。所有配置类都接受参数,可选的参数,以及(支持的情况下)参数。推荐启用流式传输——AG2以异步和流式传输为核心设计。
ag2.configmodel=api_key=streaming=Truepython
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_KEYANTHROPIC_API_KEYGEMINI_API_KEYGOOGLE_API_KEY对于兼容OpenAI的端点(vLLM、LM Studio、Together、NVIDIA NIM等),使用并设置:
OpenAIConfigbase_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()多轮交互——链式调用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()agent.ask(...)assets/multi_turn.pypython
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.pyReusing model configs
复用模型配置
Configs are immutable. Use to fork one with overrides:
.copy(...)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 secretThe 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")你还可以在每次调用时覆盖模型配置——当用户按请求提供自己的API密钥时非常有用:
askpython
agent = Agent("assistant", prompt="提供帮助。")
reply = await agent.ask("你好!", config=OpenAIConfig(model="gpt-5", api_key="sk-...")) # pragma: allowlist secret每次调用时的配置会完全替换该轮次中Agent的原有配置。
askGoing deeper
深入学习
- Working starter (single-turn): (mirrors
assets/hello_agent.py).code_examples/01 - Multi-turn starter: (mirrors
assets/multi_turn.py).code_examples/03 - Full provider reference, including auth,
VertexAIConfig, customextra_bodyclient, env-var fallback table:httpx.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 — every method on
await/Agentis async. Wrap inAgentReplyfor scripts.asyncio.run(main()) - Calling twice expecting context to carry — it doesn't; use
agent.ask()instead.reply.ask() - Hardcoding API keys — prefer env-var fallback (, etc.) so configs commit cleanly.
OPENAI_API_KEY - Skipping — AG2 is streaming-first; you'll get a worse user experience without it on supported providers.
streaming=True - Per-ask is total override, not a partial merge — be deliberate about which knobs you set.
config=
- 忘记使用——
await/Agent上的所有方法都是异步的。脚本中需用AgentReply包裹。asyncio.run(main()) - 两次调用并期望上下文延续——这不会生效;请改用
agent.ask()。reply.ask() - 硬编码API密钥——优先使用环境变量回退机制(等),确保配置可以干净地提交到版本控制系统。
OPENAI_API_KEY - 跳过——AG2以流式传输为核心设计;在支持的提供商上不启用流式传输会导致更差的用户体验。
streaming=True - 每次调用时的
ask是完全覆盖,而非部分合并——设置参数时请谨慎考虑。config=