最简单快速的测试方式,不调用真实 LLM,而是根据工具 schema 生成有效的结构化数据。默认会调用 Agent 中的所有工具,然后返回纯文本或结构化响应。
from pydantic_ai.models.test import TestModel
with agent.override(model=TestModel()):
result = agent.run_sync('Hello')
assert isinstance(result.output, str)用于更复杂的测试场景,允许定义自定义响应逻辑:
from pydantic_ai.models.function import FunctionModel, ModelContext
from pydantic_ai.messages import ModelResponse, TextPart
def custom_model_function(messages: list, info: ModelContext) -> ModelResponse:
return ModelResponse(parts=[TextPart(content='Custom response')])
with agent.override(model=FunctionModel(custom_model_function)):
result = agent.run_sync('Any query')设置 ALLOW_MODEL_REQUESTS=False 全局阻止对非测试模型的请求,防止测试中意外产生 API 费用。