SDK 集成
PydanticAI
通过 PydanticAI 的 OpenAI 兼容 provider,让 agent 跑在 OhMyGPT 的模型上。
PydanticAI 的 agent 通过内置的 OpenAICompatibleProvider 接入 OhMyGPT。一个 provider 对象,就能让你的 agent 使用模型列表里的所有对话模型,结构化输出和工具照常可用。示例使用 pydantic-ai-slim 2.64。
安装
pip install "pydantic-ai-slim[openai]"创建模型
import os
from pydantic_ai.models.openai import OpenAIChatModel
from pydantic_ai.providers.openai_compatible import OpenAICompatibleProvider
provider = OpenAICompatibleProvider(
"ohmygpt",
base_url="https://api.ohmygpt.com/v1",
api_key=os.environ["OHMYGPT_API_KEY"],
)
model = OpenAIChatModel("zhipu/glm-5.3-flash", provider=provider)第一个参数可以是 GET /v1/models 中的任意模型 ID。免费测试时用 "ohmygpt/mock":它会应答每一次调用,包括工具调用,所以下面每个 agent 都能免费完整跑通。
运行 agent
from pydantic_ai import Agent
from ohmygpt import model
agent = Agent(model, instructions="Answer in one sentence.")
result = agent.run_sync("What is the capital of France?")
print(result.output)
print(result.usage)The capital of France is Paris.
RunUsage(input_tokens=25, output_tokens=38, requests=1)结构化输出
from pydantic import BaseModel
from pydantic_ai import Agent
from ohmygpt import model
class City(BaseModel):
name: str
country: str
agent = Agent(model, output_type=City)
print(agent.run_sync("Tell me about Tokyo.").output)name='Tokyo' country='Japan'PydanticAI 通过工具调用拿到这个对象,所以模型必须支持工具调用。
工具
from pydantic_ai import Agent
from ohmygpt import model
agent = Agent(model)
@agent.tool_plain
def get_weather(city: str) -> str:
"""Get the current weather for a city."""
return f"18°C and cloudy in {city}"
print(agent.run_sync("What is the weather in Paris?").output)The weather in Paris is currently **18°C and cloudy**.agent 会把工具结果发回模型,并返回模型的最终回答。在 ohmygpt/mock 上,工具会以 city="" 运行一次。