PydanticAI 采用 Graph 执行模型——Agent 运行被建模为有向图遍历,每个节点是一个处理步骤。这是所有框架中唯一的图执行架构。
Agent.run()
→ 构建 Graph:
UserPromptNode → ModelRequestNode → CallToolsNode → (loop back to ModelRequestNode)
→ Graph 执行(pydantic_graph 引擎)
→ 输出验证(result_type 强类型)
核心依赖 pydantic_graph 库——一个通用有向图执行引擎,节点通过 BaseNode 定义,GraphBuilder 构建。
PydanticAI 采用装饰器驱动的提示词系统,极简但类型安全:
# 静态 system prompt
agent = Agent('openai:gpt-4', system_prompt='You are a helpful assistant.')
# 动态 system prompt(带依赖注入)
@agent.system_prompt
async def get_prompt(ctx: RunContext[MyDeps]) -> str:
return f"User's language: {ctx.deps.language}"
# 动态 + 可刷新(每轮重新评估)
@agent.system_prompt(dynamic=True)
async def get_time_prompt(ctx: RunContext[MyDeps]) -> str:
return f"Current time: {datetime.now()}"
# _system_prompt.py 源码:
class SystemPromptRunner:
function: SystemPromptFunc[AgentDepsT]
dynamic: bool = False # 标记是否每轮刷新
async def run(self, run_context) -> str | None:
# 自动检测函数是否接受 ctx 参数
if self._takes_ctx:
args = (run_context,)
else:
args = ()
# resolve_system_prompts():
# 1. 先添加静态字符串 prompts
# 2. 逐个执行 runners
# 3. dynamic=True 的 runner 设置 dynamic_ref=函数名
# 4. 非 dynamic 且返回空的跳过
标记 dynamic=True 的 system prompt 在每轮对话中重新求值,生成的 SystemPromptPart 携带 dynamic_ref(函数限定名),Agent Graph 在后续轮次中用此标记匹配并替换旧值。
基于 pydantic_graph 的图执行:
UserPromptNode ↓ ModelRequestNode ←──────┐ ↓ │ CallToolsNode │ ├── 有 tool_call ───────┘ └── 无 tool_call → End
early — 首个匹配 result_type 的结果即停止graceful — 允许 LLM 补充说明后停止exhaustive — 消耗所有 tool calls 后再停止@agent.tool
async def my_tool(ctx: RunContext[MyDeps], query: str) -> str:
return ctx.deps.search(query)
# 工具参数自动从函数签名提取 Pydantic schema
# 返回值自动序列化
ToolManager 管理工具注册和验证,ValidatedToolCall 确保参数类型正确。
支持 DeferredToolResult — 异步延迟返回的工具结果。
Native Tools — 支持模型原生工具调用(不经过 PydanticAI 包装),包括 ToolSearchTool(工具搜索)。
RunContext[DepsT] 提供类型化访问'new' 强制新对话没有内置向量记忆或 RAG——依赖开发者通过 Dependencies 注入实现。
通过 Agent 作为 Tool 模式:
# 将一个 Agent 注册为另一个 Agent 的工具
agent_a = Agent('openai:gpt-4', ...)
agent_b = Agent('openai:gpt-4', tools=[agent_a.as_tool(...)])
没有框架级的多 Agent 路由或转移机制——由开发者自行编排。
pydantic_ai_slim/pydantic_ai/agent.py — Agent 主类pydantic_ai_slim/pydantic_ai/_agent_graph.py — Graph 执行引擎pydantic_ai_slim/pydantic_ai/_system_prompt.py — System prompt 解析pydantic_ai_slim/pydantic_ai/_instructions.py — 指令处理pydantic_ai_slim/pydantic_ai/tool_manager.py — 工具管理pydantic_ai_slim/pydantic_ai/tools.py — 工具定义pydantic_ai_slim/pydantic_ai/messages.py — 消息类型