Pydantic AI
Hello Pydantic AI
Pydantic AI 快速入门
2025-08-12 更新:突然发现新版的 PydanticAI 0.6.2 的 API 发生了重大变化
准备工作
到 Google AI Studio 注册一个账号,获取 Gemini 的 API Key。 Google 提供的免费 Gemini API 的配额还是非常多的,而且 Gemini 的模型能力也不错,还有多模可以选。比较麻烦的是国内无法直接访问,国内使用需要配置代理,不过大多数框架的配置还比较容易。
Python 项目使用 uv 管理,这个确实太舒服了,速度确实快,功能也够多。大家一定要掌握。
Hello World
初始化项目
uv init
uv add pydantic-ai然后参考 PydanticAI 项目的 README.md 编辑 hello.py 为:
from pydantic_ai import Agent
# Define a very simple agent including the model to use, you can also set the model when running the agent.
agent = Agent(
'google-gla:gemini-1.5-flash',
# Register a static system prompt using a keyword argument to the agent.
# For more complex dynamically-generated system prompts, see the example below.
system_prompt='Be concise, reply with one sentence.',
)
# Run the agent synchronously, conducting a conversation with the LLM.
# Here the exchange should be very short: PydanticAI will send the system prompt and the user query to the LLM,
# the model will return a text response. See below for a more complex run.
result = agent.run_sync('Where does "hello world" come from?')
print(result.output)
"""
The first known use of "hello, world" was in a 1974 textbook about the C programming language.
"""然后运行 uv run hello.py 即可?不行,还需要设置环境变量:
HTTP_PROXY=http://127.0.0.1:10808
HTTPS_PROXY=http://127.0.0.1:10808
GEMINI_API_KEY=your-gemini-api-key
# 0.6.2 使用这个环境变量,不过 GEMINI_API_KEY 还支持
GOOGLE_API_KEY=your-gemini-api-key还是不行,在国内访问不了 Gemini 的 API。和其他框架有点区别,PydanticAI 默认不会读取环境变量的代理配置,所以代码需要修改为:
import os
import logging
from pydantic_ai import Agent
from pydantic_ai.models.google import GoogleModel
from pydantic_ai.providers.google import GoogleProvider
from google.genai.types import HttpOptions, HttpRetryOptions
from google import genai
def get_model():
# 1. 定义代理和重试设置
# httpx(底层库)默认会读取 HTTP_PROXY 和 HTTPS_PROXY 环境变量。
proxy_url = os.environ.get("HTTPS_PROXY")
retry_attempts = 2 # 例如,设置5次重试
# 2. 准备 HttpOptions 的参数
http_options_kwargs = {}
if proxy_url:
logging.info(f"正在使用代理: {proxy_url}")
proxies = {
"http://": proxy_url,
"https://": proxy_url,
}
http_options_kwargs["client_args"] = {"proxies": proxies}
http_options_kwargs["async_client_args"] = {"proxies": proxies}
# 3. 添加重试配置
logging.info(f"设置 API 请求重试次数为: {retry_attempts}")
http_options_kwargs["retry_options"] = HttpRetryOptions(attempts=retry_attempts)
# 4. 创建并传递配置
http_options = HttpOptions(**http_options_kwargs)
google_client = genai.Client(http_options=http_options)
provider = GoogleProvider(client=google_client)
model = GoogleModel(model_name='gemini-2.0-flash', provider=provider)
return model
agent = Agent(
model=get_model(),
system_prompt='Be concise, reply with one sentence.' # Read system prompt from .env or use default
)
result = agent.run_sync('Where does "hello world" come from?')
print(result.output)对应的 pyproject.toml:
[project]
name = "hello-pydanticai"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"markdownify>=1.1.1",
"pydantic-ai>=0.6.2",
"pydantic-ai-slim[google]>=0.6.2",
]很无奈,多了不少代码,但是总算可以运行了。
似乎,还没有体现出 Agent 的作用,大家可以参考无需框架构建AI Agent:分步指南,感受下 Agent 的价值。