Python 快速开始Python quick start
本页对应 agentscope 2.0.11。目标是让你在十分钟内跑通一个带工具调用、流式输出和结构化返回的智能体。所有类名都可以在左侧 Python 手册中查到完整签名。
1. 环境准备
要求 Python 3.11+:
python --version
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install "agentscope==2.0.11"
设置模型密钥。下面的例子使用 OpenAI 兼容端点,也可以换成 DashScope、DeepSeek、Anthropic、Gemini、Ollama 等适配器:
export OPENAI_API_KEY="sk-..." # Windows PowerShell: $env:OPENAI_API_KEY="sk-..."
2. 创建模型
模型由 凭据 + 模型名 + 参数 构成。凭据是独立对象,便于在多个模型间复用:
from agentscope.credential import OpenAICredential
from agentscope.model import OpenAIChatModel
model = OpenAIChatModel(
credential=OpenAICredential(api_key="sk-..."),
model="gpt-4o-mini",
stream=True,
context_size=128_000,
)
agentscope.credential 还提供 DashScopeCredential、DeepSeekCredential、AnthropicCredential、GeminiCredential、OllamaCredential 等。模型适配器会自动选择对应的格式化器;需要定制协议时,可以显式传入 formatter=。
3. 定义工具
工具就是普通 Python 函数。框架从 函数签名 和 Google 风格 docstring 生成 JSON Schema:
from agentscope.tool import FunctionTool, Toolkit
def get_weather(city: str) -> str:
"""Return the current weather for a city.
Args:
city: The city name, for example "Hangzhou".
"""
# 真实项目里应调用天气 API
return f"{city}: sunny, 24C"
toolkit = Toolkit(tools=[FunctionTool(get_weather)])
工具在调用前会经过参数校验与权限检查。需要人工确认时,在事件流中会收到确认请求;需要并行执行时,把 FunctionTool(is_concurrency_safe=True) 交给框架调度。
4. 构建智能体并对话
import asyncio
from agentscope.agent import Agent, ReActConfig
from agentscope.message import UserMsg
async def main() -> None:
agent = Agent(
name="assistant",
system_prompt="You are a concise assistant. Use tools when needed.",
model=model,
toolkit=toolkit,
react_config=ReActConfig(max_iters=10),
)
reply = await agent.reply(UserMsg("user", "What's the weather in Hangzhou?"))
print(reply.get_text_content())
asyncio.run(main())
reply 内部完成整个 ReAct 循环:模型决定调用 get_weather,工具执行结果被写回上下文,模型再生成最终答复。返回的 Msg 里包含 content、usage、finished_reason 等元数据。
5. 流式输出
需要逐字渲染时,用 reply_stream。它产生的事件覆盖回复开始、模型调用、文本增量、思考增量、工具调用、工具结果和回复结束:
from agentscope.event import TextBlockDeltaEvent
async for event in agent.reply_stream(UserMsg("user", "Explain ReAct in two sentences.")):
if isinstance(event, TextBlockDeltaEvent):
print(event.delta, end="", flush=True)
如果还需要最终消息,传入 yield_final_msg=True;流末尾会额外产出一个 Msg。
6. 结构化输出
传入 Pydantic 模型即可约束返回结构:
from pydantic import BaseModel
class WeatherReport(BaseModel):
city: str
temperature_c: float
condition: str
reply = await agent.reply(
UserMsg("user", "Report the weather in Hangzhou as structured data."),
structured_schema=WeatherReport,
)
print(reply.structured_output) # dict,符合 WeatherReport
结构化输出通过循环内的一个专用工具实现,因此仍会遵循工具权限与迭代上限。若模型未能生成合法结构,finished_reason 会反映失败原因。
7. 多轮对话与状态
把同一个 AgentState 传给智能体,就能跨多次 reply 保留上下文:
from agentscope.state import AgentState
state = AgentState(session_id="demo-session")
agent = Agent(
name="assistant",
system_prompt="You are a helpful assistant.",
model=model,
state=state,
)
await agent.reply(UserMsg("user", "My name is Ada."))
reply = await agent.reply(UserMsg("user", "What is my name?"))
需要持久化时,序列化状态并由你的数据库/Redis/S3 保存:
payload = state.model_dump_json()
# save(payload)
# state = AgentState.model_validate_json(payload)
上下文过长时,ContextConfig 会触发压缩。压缩会生成结构化摘要并保留近期消息、工具调用与任务状态;压缩过程也会出现在事件流中。
8. 加入 RAG
RAG 的四个可替换部件是:解析器、切块器、嵌入模型、向量库。下面用本地 Milvus Lite 演示:
from agentscope.embedding import OpenAIEmbeddingModel
from agentscope.rag import KnowledgeBase, MilvusLiteStore
embedding = OpenAIEmbeddingModel(
credential=OpenAICredential(api_key="sk-..."),
model="text-embedding-3-small",
dimensions=1536,
)
store = MilvusLiteStore(uri="./knowledge.db")
kb = KnowledgeBase(
name="handbook",
description="Internal engineering handbook",
embedding_model=embedding,
vector_store=store,
collection="handbook",
)
# 先解析文档(PDFParser / WordParser / TextParser 等),再 insert_document(chunks)
results = await kb.search(["deployment checklist"], top_k=5)
for item in results:
print(item)
把检索封装成工具,或使用 RAGMiddleware 在模型调用前自动注入结果。生产环境通常把 MilvusLiteStore 换成 QdrantStore、MongoDBStore 或 ElasticsearchStore。
9. 下一步
- 在
Agent页面查看完整构造参数与reply_stream的输入类型; - 在
Toolkit页面查看工具分组、MCP 与技能注册; - 在
KnowledgeBase页面查看文档管理与检索细节; - 需要多智能体时,阅读
TeamPipeline; - 需要服务化时,阅读
agentscope.app下的存储、频道与消息总线 API。
This page targets agentscope 2.0.11. The goal is a working agent with tool calls, streaming and structured output in ten minutes. Every class name links to its full signature in the Python reference.
1. Setup
Python 3.11+ is required:
python --version
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install "agentscope==2.0.11"
Export a model key. The examples use an OpenAI-compatible endpoint; DashScope, DeepSeek, Anthropic, Gemini and Ollama adapters work the same way:
export OPENAI_API_KEY="sk-..." # Windows PowerShell: $env:OPENAI_API_KEY="sk-..."
2. Create a model
A model is credential + model name + parameters. Credentials are separate objects so they can be reused across models:
from agentscope.credential import OpenAICredential
from agentscope.model import OpenAIChatModel
model = OpenAIChatModel(
credential=OpenAICredential(api_key="sk-..."),
model="gpt-4o-mini",
stream=True,
context_size=128_000,
)
agentscope.credential also provides DashScopeCredential, DeepSeekCredential, AnthropicCredential, GeminiCredential, OllamaCredential and others. The adapter picks the matching formatter; pass formatter= explicitly to customize the protocol.
3. Define a tool
A tool is a plain Python function. The framework derives a JSON Schema from the signature and the Google-style docstring:
from agentscope.tool import FunctionTool, Toolkit
def get_weather(city: str) -> str:
"""Return the current weather for a city.
Args:
city: The city name, for example "Hangzhou".
"""
# Call a real weather API in production
return f"{city}: sunny, 24C"
toolkit = Toolkit(tools=[FunctionTool(get_weather)])
Calls are validated and permission-checked before execution. When human confirmation is required, the event stream carries a confirmation request. For parallel execution, construct the tool with FunctionTool(is_concurrency_safe=True).
4. Build the agent and chat
import asyncio
from agentscope.agent import Agent, ReActConfig
from agentscope.message import UserMsg
async def main() -> None:
agent = Agent(
name="assistant",
system_prompt="You are a concise assistant. Use tools when needed.",
model=model,
toolkit=toolkit,
react_config=ReActConfig(max_iters=10),
)
reply = await agent.reply(UserMsg("user", "What's the weather in Hangzhou?"))
print(reply.get_text_content())
asyncio.run(main())
reply runs the whole ReAct loop: the model decides to call get_weather, the result is written back to the context, and the model produces the final answer. The returned Msg carries content, usage, finished_reason and other metadata.
5. Streaming
Use reply_stream for incremental rendering. Events cover reply start, model calls, text deltas, thinking deltas, tool calls, tool results and reply end:
from agentscope.event import TextBlockDeltaEvent
async for event in agent.reply_stream(UserMsg("user", "Explain ReAct in two sentences.")):
if isinstance(event, TextBlockDeltaEvent):
print(event.delta, end="", flush=True)
Pass yield_final_msg=True to receive the final Msg at the end of the stream.
6. Structured output
Pass a Pydantic model to constrain the result:
from pydantic import BaseModel
class WeatherReport(BaseModel):
city: str
temperature_c: float
condition: str
reply = await agent.reply(
UserMsg("user", "Report the weather in Hangzhou as structured data."),
structured_schema=WeatherReport,
)
print(reply.structured_output) # dict matching WeatherReport
Structured output is implemented as a dedicated tool inside the loop, so it still obeys tool permissions and the iteration limit. If the model cannot produce a valid value, finished_reason records the failure.
7. Multi-turn state
Pass the same AgentState to keep context across reply calls:
from agentscope.state import AgentState
state = AgentState(session_id="demo-session")
agent = Agent(
name="assistant",
system_prompt="You are a helpful assistant.",
model=model,
state=state,
)
await agent.reply(UserMsg("user", "My name is Ada."))
reply = await agent.reply(UserMsg("user", "What is my name?"))
To persist, serialize the state and store it in your database, Redis or object storage:
payload = state.model_dump_json()
# save(payload)
# state = AgentState.model_validate_json(payload)
When the context grows too long, ContextConfig triggers compression. Compression produces a structured summary and preserves recent messages, tool calls and task state; it is visible in the event stream.
8. Add RAG
RAG has four replaceable parts: parsers, chunkers, embedding models and vector stores. A local Milvus Lite setup:
from agentscope.embedding import OpenAIEmbeddingModel
from agentscope.rag import KnowledgeBase, MilvusLiteStore
embedding = OpenAIEmbeddingModel(
credential=OpenAICredential(api_key="sk-..."),
model="text-embedding-3-small",
dimensions=1536,
)
store = MilvusLiteStore(uri="./knowledge.db")
kb = KnowledgeBase(
name="handbook",
description="Internal engineering handbook",
embedding_model=embedding,
vector_store=store,
collection="handbook",
)
# Parse documents first (PDFParser / WordParser / TextParser, ...), then insert_document(chunks)
results = await kb.search(["deployment checklist"], top_k=5)
for item in results:
print(item)
Wrap retrieval as a tool, or use RAGMiddleware to inject results before the model call. In production, swap MilvusLiteStore for QdrantStore, MongoDBStore or ElasticsearchStore.
9. Next steps
- See
Agentfor the full constructor and the input variants ofreply_stream. - See
Toolkitfor tool groups, MCP and skill registration. - See
KnowledgeBasefor document management and retrieval. - For multiple agents, read
TeamPipeline. - For service deployment, browse the storage, channel and message-bus APIs under
agentscope.app.