跳过内容

模型

PydanticAI 是与模型无关的,并内置支持以下模型提供者:

请参阅 OpenAI兼容模型 以获取有关如何使用支持OpenAI SDK的模型,例如 OpenRouterGrok (xAI) 的更多示例。

您还可以 添加对其他模型的支持

PydanticAI 还提供了 TestModelFunctionModel 用于测试和开发。

要使用每个模型提供者,您需要配置本地环境并确保安装了正确的软件包。

开放AI

安装

要使用OpenAI模型,您需要安装pydantic-ai,或者安装pydantic-ai-slim,并带上openai可选组:

pip install 'pydantic-ai-slim[openai]'
uv add 'pydantic-ai-slim[openai]'

配置

要通过他们的主要API使用 OpenAIModel,请访问 platform.openai.com 并按照指示操作,直到找到生成API密钥的地方。

环境变量

一旦你拥有了API密钥,你可以将其设置为环境变量:

export OPENAI_API_KEY='your-api-key'

你可以通过名称使用 OpenAIModel:

openai_model_by_name.py
from pydantic_ai import Agent

agent = Agent('openai:gpt-4o')
...

或者直接用模型名称初始化模型:

openai_model_init.py
from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIModel

model = OpenAIModel('gpt-4o')
agent = Agent(model)
...

api_key 参数

如果您不想或无法设置环境变量,您可以通过 api_key 参数 在运行时传递它:

openai_model_api_key.py
from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIModel

model = OpenAIModel('gpt-4o', api_key='your-api-key')
agent = Agent(model)
...

自定义 OpenAI 客户端

OpenAIModel 还接受通过 openai_client 参数 自定义的 AsyncOpenAI 客户端,您可以根据 OpenAI API 文档 自定义 organizationprojectbase_url 等等。

您还可以使用AsyncAzureOpenAI客户端来使用Azure OpenAI API。

openai_azure.py
from openai import AsyncAzureOpenAI

from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIModel

client = AsyncAzureOpenAI(
    azure_endpoint='...',
    api_version='2024-07-01-preview',
    api_key='your-api-key',
)

model = OpenAIModel('gpt-4o', openai_client=client)
agent = Agent(model)
...

人类情感

安装

要使用 AnthropicModel 模型,您需要安装 pydantic-ai,或者安装带有 anthropic 可选组的 pydantic-ai-slim

pip install 'pydantic-ai-slim[anthropic]'
uv add 'pydantic-ai-slim[anthropic]'

配置

要通过 Anthropic 使用他们的 API,请访问 console.anthropic.com/settings/keys 以生成 API 密钥。

AnthropicModelName 包含可用的Anthropic模型列表。

环境变量

一旦你拥有了API密钥,你可以将其设置为环境变量:

export ANTHROPIC_API_KEY='your-api-key'

然后您可以通过名称使用 AnthropicModel:

anthropic_model_by_name.py
from pydantic_ai import Agent

agent = Agent('anthropic:claude-3-5-sonnet-latest')
...

或者直接用模型名称初始化模型:

anthropic_model_init.py
from pydantic_ai import Agent
from pydantic_ai.models.anthropic import AnthropicModel

model = AnthropicModel('claude-3-5-sonnet-latest')
agent = Agent(model)
...

api_key 参数

如果您不想或无法设置环境变量,您可以通过 api_key 参数 在运行时传递它:

anthropic_model_api_key.py
from pydantic_ai import Agent
from pydantic_ai.models.anthropic import AnthropicModel

model = AnthropicModel('claude-3-5-sonnet-latest', api_key='your-api-key')
agent = Agent(model)
...

双子

仅用于原型设计

谷歌自己称这个API为“爱好者”API,我多次从它那里收到503响应。 这个API易于使用,适合原型开发和简单演示,但我不会在生产环境中依赖它。

如果您想在生产中运行Gemini模型,您应该使用下面描述的 VertexAI API

安装

要使用 GeminiModel 模型,您只需安装 pydantic-aipydantic-ai-slim,不需要额外的依赖。

配置

GeminiModel 让你通过他们的 生成语言API 使用谷歌的 Gemini 模型, generativelanguage.googleapis.com

GeminiModelName 包含可以通过此接口使用的可用 Gemini 模型的列表。

要使用 GeminiModel,请访问 aistudio.google.com 并按照提示找到生成API密钥的地方。

环境变量

一旦你拥有了API密钥,你可以将其设置为环境变量:

export GEMINI_API_KEY=your-api-key

然后你可以通过名称使用 GeminiModel:

gemini_model_by_name.py
from pydantic_ai import Agent

agent = Agent('google-gla:gemini-1.5-flash')
...

注意

google-gla 提供程序前缀表示 Google Generative Language API 用于 GeminiModelgoogle-vertex 用于 Vertex AIVertexAIModel

或者直接用模型名称初始化模型:

gemini_model_init.py
from pydantic_ai import Agent
from pydantic_ai.models.gemini import GeminiModel

model = GeminiModel('gemini-1.5-flash')
agent = Agent(model)
...

api_key 参数

如果您不想或无法设置环境变量,您可以通过 api_key 参数 在运行时传递它:

gemini_model_api_key.py
from pydantic_ai import Agent
from pydantic_ai.models.gemini import GeminiModel

model = GeminiModel('gemini-1.5-flash', api_key='your-api-key')
agent = Agent(model)
...

通过VertexAI的Gemini

要在生产中运行谷歌的Gemini模型,您应该使用 VertexAIModel,它使用 *-aiplatform.googleapis.com API。

GeminiModelName 包含可以通过此接口使用的可用 Gemini 模型列表。

安装

要使用 VertexAIModel,您需要安装 pydantic-ai,或者安装 pydantic-ai-slim 以及 vertexai 可选组:

pip install 'pydantic-ai-slim[vertexai]'
uv add 'pydantic-ai-slim[vertexai]'

配置

这个接口相对于上面文档中的 generativelanguage.googleapis.com 有许多优点:

  1. 根据我们的经验,VertexAI API 更可靠且延迟略低。
  2. 您可以 购买预配置的吞吐量 来与 VertexAI 保证容量。
  3. 如果您在GCP中运行PydanticAI,则不需要设置身份验证,它应该“自动工作”。
  4. 您可以决定使用哪个区域,这可能从监管的角度来看很重要,并且可能改善延迟。

一个大缺点是,对于本地开发,您可能需要创建和配置一个“服务账号”,我过去发现这非常麻烦。

无论你使用哪种方式认证,你都需要在你的GCP账户中启用VertexAI。

应用程序默认凭据

幸运的是,如果您在 GCP 内运行 PydanticAI,或者您已经安装并配置了 gcloud CLI,您应该能够无须任何额外设置使用 VertexAIModel

要使用 VertexAIModel,需要配置应用程序默认凭证(例如使用 gcloud),您可以简单地使用:

vertexai_application_default_credentials.py
from pydantic_ai import Agent
from pydantic_ai.models.vertexai import VertexAIModel

model = VertexAIModel('gemini-1.5-flash')
agent = Agent(model)
...

内部使用 google.auth.default()google-auth 包获取凭证。

不会失败直到 agent.run()

因为 google.auth.default() 需要网络请求并且可能很慢,所以在你调用 agent.run() 之前不会执行。这意味着任何配置或权限错误只有在你尝试使用模型时才会被抛出。要初始化模型以执行此检查,请调用 await model.ainit()

如果应用程序默认凭据没有设置项目,您可能还需要将 project_id 参数传递给 VertexAIModel,如果您传递了 project_id 且它与应用程序默认凭据设置的项目冲突,将会引发错误。

服务账户

如果您希望使用服务账户进行身份验证而不是应用程序默认凭据,您需要创建一个服务账户,将其添加到您的GCP项目中(注意:据我所知,即使您在项目内创建了服务账户,这一步也是必要的),给予该服务账户“Vertex AI 服务代理”角色,并下载服务账户的JSON文件。

一旦你拥有了JSON文件,你可以这样使用它:

vertexai_service_account.py
from pydantic_ai import Agent
from pydantic_ai.models.vertexai import VertexAIModel

model = VertexAIModel(
    'gemini-1.5-flash',
    service_account_file='path/to/service-account.json',
)
agent = Agent(model)
...

自定义区域

无论您使用哪种方式进行身份验证,都可以通过region参数指定请求将发送到哪个区域。

使用离您的应用程序较近的区域可以提高延迟,并且从监管的角度来看可能很重要。

vertexai_region.py
from pydantic_ai import Agent
from pydantic_ai.models.vertexai import VertexAIModel

model = VertexAIModel('gemini-1.5-flash', region='asia-east1')
agent = Agent(model)
...

VertexAiRegion 包含可用区域的列表。

Groq

安装

要使用 GroqModel,您需要安装 pydantic-ai,或者安装带有 groq 可选组的 pydantic-ai-slim

pip install 'pydantic-ai-slim[groq]'
uv add 'pydantic-ai-slim[groq]'

配置

要通过Groq使用他们的API,请访问console.groq.com/keys,然后根据提示找到生成API密钥的地方。

GroqModelName 包含可用的 Groq 模型列表。

环境变量

一旦你拥有了API密钥,你可以将其设置为环境变量:

export GROQ_API_KEY='your-api-key'

然后你可以按名称使用 GroqModel

groq_model_by_name.py
from pydantic_ai import Agent

agent = Agent('groq:llama-3.3-70b-versatile')
...

或者直接用模型名称初始化模型:

groq_model_init.py
from pydantic_ai import Agent
from pydantic_ai.models.groq import GroqModel

model = GroqModel('llama-3.3-70b-versatile')
agent = Agent(model)
...

api_key 参数

如果您不想或无法设置环境变量,您可以通过 api_key 参数 在运行时传递它:

groq_model_api_key.py
from pydantic_ai import Agent
from pydantic_ai.models.groq import GroqModel

model = GroqModel('llama-3.3-70b-versatile', api_key='your-api-key')
agent = Agent(model)
...

米斯特拉尔

安装

要使用 MistralModel,您需要安装 pydantic-ai,或者安装 pydantic-ai-slim,并将 mistral 作为可选组:

pip install 'pydantic-ai-slim[mistral]'
uv add 'pydantic-ai-slim[mistral]'

配置

要通过Mistral使用他们的API,请访问console.mistral.ai/api-keys/,然后根据提示找到生成API密钥的地方。

MistralModelName 包含了最受欢迎的 Mistral 模型的列表。

环境变量

一旦你拥有了API密钥,你可以将其设置为环境变量:

export MISTRAL_API_KEY='your-api-key'

然后你可以通过名称使用 MistralModel

mistral_model_by_name.py
from pydantic_ai import Agent

agent = Agent('mistral:mistral-large-latest')
...

或者直接用模型名称初始化模型:

mistral_model_init.py
from pydantic_ai import Agent
from pydantic_ai.models.mistral import MistralModel

model = MistralModel('mistral-small-latest')
agent = Agent(model)
...

api_key 参数

如果您不想或无法设置环境变量,您可以通过 api_key 参数 在运行时传递它:

mistral_model_api_key.py
from pydantic_ai import Agent
from pydantic_ai.models.mistral import MistralModel

model = MistralModel('mistral-small-latest', api_key='your-api-key')
agent = Agent(model)
...

Cohere

安装

要使用 CohereModel,您需要安装 pydantic-ai,或者安装带有 cohere 可选组的 pydantic-ai-slim

pip install 'pydantic-ai-slim[cohere]'
uv add 'pydantic-ai-slim[cohere]'

配置

要通过他们的API使用 Cohere,请访问 dashboard.cohere.com/api-keys 并按照说明找到生成API密钥的地方。

CohereModelName 包含了最受欢迎的 Cohere 模型的列表。

环境变量

一旦你拥有了API密钥,你可以将其设置为环境变量:

export CO_API_KEY='your-api-key'

然后你可以按名称使用 CohereModel

cohere_model_by_name.py
from pydantic_ai import Agent

agent = Agent('cohere:command')
...

或者直接用模型名称初始化模型:

cohere_model_init.py
from pydantic_ai import Agent
from pydantic_ai.models.cohere import CohereModel

model = CohereModel('command', api_key='your-api-key')
agent = Agent(model)
...

api_key 参数

如果您不想或无法设置环境变量,您可以通过 api_key 参数 在运行时传递它:

cohere_model_api_key.py
from pydantic_ai import Agent
from pydantic_ai.models.cohere import CohereModel

model = CohereModel('command', api_key='your-api-key')
agent = Agent(model)
...

与OpenAI兼容的模型

许多模型与OpenAI API兼容,因此可以在PydanticAI中与 OpenAIModel 一起使用。 在开始之前,请查看OpenAI部分以获取安装和配置说明。

要使用其他兼容OpenAI的API,您可以使用 base_urlapi_key 参数:

openai_model_base_url.py
from pydantic_ai.models.openai import OpenAIModel

model = OpenAIModel(
    'model_name',
    base_url='https://<openai-compatible-api-endpoint>.com',
    api_key='your-api-key',
)
...

Ollama

要使用 Ollama,您必须首先下载 Ollama 客户端,然后使用 Ollama model library 下载一个模型。

您还必须确保Ollama服务器正在运行,以便尝试向其发送请求。有关更多信息,请参阅Ollama文档

示例本地使用

安装了 ollama 后,您可以使用您想要的模型运行服务器:

terminal-run-ollama
ollama run llama3.2
(如果您尚未下载,该命令将拉取 llama3.2 模型)

然后运行你的代码,这里是一个最小的示例:

ollama_example.py
from pydantic import BaseModel

from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIModel


class CityLocation(BaseModel):
    city: str
    country: str


ollama_model = OpenAIModel(model_name='llama3.2', base_url='http://localhost:11434/v1')
agent = Agent(ollama_model, result_type=CityLocation)

result = agent.run_sync('Where were the olympics held in 2012?')
print(result.data)
#> city='London' country='United Kingdom'
print(result.usage())
"""
Usage(requests=1, request_tokens=57, response_tokens=8, total_tokens=65, details=None)
"""

使用远程服务器的示例

ollama_example_with_remote_server.py
from pydantic import BaseModel

from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIModel

ollama_model = OpenAIModel(
    model_name='qwen2.5-coder:7b',  # (1)!
    base_url='http://192.168.1.74:11434/v1',  # (2)!
)


class CityLocation(BaseModel):
    city: str
    country: str


agent = Agent(model=ollama_model, result_type=CityLocation)

result = agent.run_sync('Where were the olympics held in 2012?')
print(result.data)
#> city='London' country='United Kingdom'
print(result.usage())
"""
Usage(requests=1, request_tokens=57, response_tokens=8, total_tokens=65, details=None)
"""
  1. 在远程服务器上运行的模型名称
  2. 远程服务器的URL

开放路由器

要使用 OpenRouter,首先在 openrouter.ai/keys 创建一个 API 密钥。

一旦你拥有API密钥,你可以将其作为 api_key 参数传递给 OpenAIModel

openrouter_model_init.py
from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIModel

model = OpenAIModel(
    'anthropic/claude-3.5-sonnet',
    base_url='https://openrouter.ai/api/v1',
    api_key='your-openrouter-api-key',
)
agent = Agent(model)
...

领悟 (xAI)

前往 xAI API Console 并创建一个 API 密钥。 一旦您拥有 API 密钥,请按照 xAI API Documentation 的说明,适当地设置 base_urlapi_key 参数:

grok_model_init.py
from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIModel

model = OpenAIModel(
    'grok-2-1212',
    base_url='https://api.x.ai/v1',
    api_key='your-xai-api-key',
)
agent = Agent(model)
...

深度搜索

访问 DeepSeek API Platform 并创建一个API密钥。 一旦您拥有API密钥,请按照 DeepSeek API Documentation,并适当地设置 base_urlapi_key 参数:

deepseek_model_init.py
from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIModel

model = OpenAIModel(
    'deepseek-chat',
    base_url='https://api.deepseek.com',
    api_key='your-deepseek-api-key',
)
agent = Agent(model)
...

困惑度

按照 Perplexity 入门 指南创建一个 API 密钥。然后,您可以使用以下内容查询 Perplexity API:

perplexity_model_init.py
from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIModel

model = OpenAIModel(
    'sonar-pro',
    base_url='https://api.perplexity.ai',
    api_key='your-perplexity-api-key',
)
agent = Agent(model)
...

实现自定义模型

要实现对尚不支持的模型的支持,您需要对子类化Model抽象基类。

对于流式传输,您还需要实现以下抽象基类:

开始的最佳地点是查看现有实现的源代码,例如 OpenAIModel

有关我们何时接受向PydanticAI添加新模型的贡献的详细信息,请参见贡献指南