进阶 pydantic.dev 2026-11-20 05:57:40 · 5 阅读

第24章 在 Pydantic AI Gateway 中集成 TypeSafe 分类模型 Jev

现在,你可以通过 Pydantic AI Gateway 调用 TypeSafe 的分类模型 Jev 了。你的应用只需保留一个 gateway key,Jev 的请求会和你的语言模型一起出现在同一个费用视图、限额和护栏体系中。

Jev 不是聊天模型。它接收一段文本和一组带类型的问题,为每个问题返回一个答案和概率。David Montague 已经演示过如何将它作为 judge 用在 Pydantic Evals 中,价格为每百万输入 token $0.042。

设置

TypeSafe 是一个自带 key 的提供商。在 Pydantic Logfire 中,进入 Gateway,然后进入 Providers,添加一个 provider。选择 TypeSafe AI:

粘贴你的 TypeSafe API key 并点击 Test & continue。Gateway 会用这个 key 向 TypeSafe 请求其模型列表,所以如果 key 无效,会在这一步失败,而不是在你的第一次请求时:

给 provider 命名,就完成了。Connect 对话框默认使用 jev-latest,并生成一段已填入你的 gateway key 的代码片段。

Jev 使用的是 TypeSafe 的 System One API,而非 OpenAI chat 格式,所以 Gateway 会原生转发请求。以下是 curl 请求示例:

curl https://gateway-us.pydantic.dev/proxy/typesafe/v1/systemone \ -H "Authorization: Bearer $PYDANTIC_AI_GATEWAY_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "jev-latest", "state": "Help! My payouts have been failing for 3 days.", "questions": { "is_urgent": { "type": "noul", "instructions": "Does this convey urgency?" } } }'

URL 中的 typesafe 是你给该 provider 设置的路由名称。state 是待评估的内容,questions 中的每一项都是关于它的一条问题。

TypeSafe Python SDK 也可以使用。先安装:

uv add typesafe-sdk

然后把 base_url 指向 Gateway:

from typesafe_sdk import Noul, TypeSafeClient

with TypeSafeClient( api_key='', base_url='https://gateway-us.pydantic.dev/proxy/typesafe', model='jev-latest', ) as client: response = client.system_one( state='Help! My payouts have been failing for 3 days.', questions={'is_urgent': Noul(instructions='Does this convey urgency?')}, )

print(response.answers['is_urgent'].noul)

通过 Gateway 你能得到什么

Gateway 不会改变 Jev 的成本或响应速度,它提供的是你从其他所有提供商那里已经获得的收益:

费用与用量。每个请求都会被计量,Jev 会和你的语言模型一起出现在同一个费用视图和限额体系中。 护栏。在请求发送到上游之前,输入护栏会先检查 state、instructions 和 criteria。 一个 key。你的应用持有的是 gateway key,而不是 TypeSafe key。

在 Pydantic AI 中使用

Pydantic AI 可以通过 TypeSafeModel 在 Jev 上运行 agent:输出类型的每个字段都会变成一条问题。安装时带上 typesafe extra:

uv add "pydantic-ai-slim[typesafe]"

要通过 Gateway 发送请求,给 provider 提供你的 gateway key 和 URL 即可:

from typing import Literal

from pydantic import BaseModel, Field

from pydantic_ai import Agent from pydantic_ai.models.typesafe import TypeSafeModel from pydantic_ai.providers.typesafe import TypeSafeProvider

class Ticket(BaseModel): """Triage a support ticket."""

urgent: bool = Field(description='Does this need a reply within the hour?') area: Literal['billing', 'bug', 'account', 'other'] = Field(description='Which team owns it?')

provider = TypeSafeProvider( api_key='', base_url='https://gateway-us.pydantic.dev/proxy/typesafe', ) agent = Agent(TypeSafeModel('jev-latest', provider=provider), output_type=Ticket) result = agent.run_sync('You have charged me twice and my account is now overdrawn.') print(result.output) #> urgent=True area='billing'

如果你在使用中遇到问题,欢迎提交 issue 或到 Slack 告诉我们。

评论 (0)