Pydantic 模型
一个使用 Pydantic AI 从文本输入构建 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
"""Simple example of using Pydantic AI to construct a Pydantic model from a text input.
Run with:
uv run -m pydantic_ai_examples.pydantic_model
"""
import os
import logfire
from pydantic import BaseModel
from pydantic_ai import Agent
# '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')
logfire.instrument_pydantic_ai()
class MyModel(BaseModel):
city: str
country: str
model = os.getenv('PYDANTIC_AI_MODEL', 'openai:gpt-4o')
print(f'Using model: {model}')
agent = Agent(model, output_type=MyModel)
if __name__ == '__main__':
result = agent.run_sync('The windy city in the US of A.')
print(result.output)
print(result.usage())