Pydantic 模型
使用PydanticAI从文本输入构造Pydantic模型的简单示例。
演示:
运行示例
安装依赖项并设置环境变量后,运行:
python -m pydantic_ai_examples.pydantic_model
uv run -m pydantic_ai_examples.pydantic_model
这个例子默认使用 openai:gpt-4o,但它与其他模型也能很好地配合,例如,你可以使用以下方式与 Gemini 一起运行它:
PYDANTIC_AI_MODEL=gemini-1.5-pro python -m pydantic_ai_examples.pydantic_model
PYDANTIC_AI_MODEL=gemini-1.5-pro uv run -m pydantic_ai_examples.pydantic_model
(或 PYDANTIC_AI_MODEL=gemini-1.5-flash ...)
示例代码
pydantic_model.py
import os
from typing import cast
import logfire
from pydantic import BaseModel
from pydantic_ai import Agent
from pydantic_ai.models import KnownModelName
# 'if-token-present' means nothing will be sent (and the example will work) if you don't have logfire configured
logfire.configure(send_to_logfire='if-token-present')
class MyModel(BaseModel):
city: str
country: str
model = cast(KnownModelName, os.getenv('PYDANTIC_AI_MODEL', 'openai:gpt-4o'))
print(f'Using model: {model}')
agent = Agent(model, result_type=MyModel)
if __name__ == '__main__':
result = agent.run_sync('The windy city in the US of A.')
print(result.data)
print(result.usage())