> ## Documentation Index
> Fetch the complete documentation index at: https://docs.siflow.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# Pydantic AI

> 了解如何在 Pydantic AI 中配置 OpenAI provider，接入 siflow endpoint，并使用算秩模型实现类型化 structured outputs 和 tool calling。

[Pydantic AI](https://github.com/pydantic/pydantic-ai) 是 Pydantic 团队提供的 Python 智能体框架，支持类型化 structured outputs 和 tool calling。它的 OpenAI model 类支持自定义 provider，因此可以接入 siflow endpoint。

本文默认模型为 `glm-5.2`；完整模型列表和价格请查看 [模型广场](https://console.siflow.cn/model-inference/models)。

## 配置

在 [API 密钥](https://console.siflow.cn/model-inference/api_keys) 页面创建 API Key，并将其导出为环境变量：

```bash theme={null}
export SIFLOW_API_KEY="<Your API Key>"
```

创建一个 `OpenAIChatModel`，并通过 `OpenAIProvider` 将 `base_url` 设置为 siflow endpoint：

```python theme={null}
import os
from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIChatModel
from pydantic_ai.providers.openai import OpenAIProvider

model = OpenAIChatModel(
    "glm-5.2",
    provider=OpenAIProvider(
        base_url="https://api.siflow.cn/model-api/v1",
        api_key=os.environ["SIFLOW_API_KEY"],
    ),
)
agent = Agent(model)
```

| 字段                           | 说明                                                                                                             |
| ---------------------------- | -------------------------------------------------------------------------------------------------------------- |
| `OpenAIChatModel("<id>")`    | 模型 ID，例如 `glm-5.2`。Pydantic AI 2.x 的类名是 `OpenAIChatModel`；较早的 1.x 版本使用 `OpenAIModel`                           |
| `OpenAIProvider(base_url=…)` | siflow OpenAI-compatible endpoint：`https://api.siflow.cn/model-api/v1`。OpenAI provider 会追加 `/chat/completions` |
| `OpenAIProvider(api_key=…)`  | 从环境变量读取的 API Key                                                                                               |

类名与版本相关。请根据已安装的 Pydantic AI 版本导入对应类。

如果要使用 Pydantic AI 的 tool/structured-output 功能，请选择原生支持 tool calling 的模型。

## 验证

运行一个 prompt。如果返回正常回复，即表示连接成功：

```python theme={null}
result = agent.run_sync("In one short sentence, which model are you?")
print(result.output)
# → a normal completion from siflow, e.g. "I am GLM, a large language model…"
```

模型的自我介绍不一定可靠，可能会说出不同的模型族。实际路由由您传入的 model ID 决定。
