资讯动态

pydantic-ai 集成指南:使用 CrusoeModel 接入 Crusoe Serverless Inference

发布时间:2026/9/13 7:25:54 来源:尧图企业网站定制
pydantic-ai 集成指南使用 CrusoeModel 接入 Crusoe Serverless Inference【免费下载链接】pydantic-aiHow Python does AI. Agents, realtime voice, image generation, embeddings. Every model, every interface, typed end to end.项目地址: https://gitcode.com/GitHub_Trending/py/pydantic-aiCrusoe 以单一 OpenAI 兼容端点同时托管多家人工智能实验室的开源权重模型如zai/GLM-5.2、deepseek-ai/DeepSeek-V4-Pro、meta-llama/Llama-3.3-70B-Instruct并在服务端为每个模型启用 guided decoding。本文面向 pydantic-ai 用户讲解pydantic_ai.models.crusoe的安装、认证、模型命名规范、结构化输出与 Provider 定制并结合仓库源码剖析CrusoeModel/CrusoeProvider的底层实现读完即可在项目中直接接入 Crusoe 全家桶模型。安装与认证配置CrusoeModel是pydantic-ai的模型适配器其内部依赖openai包来构建 OpenAI 兼容客户端。安装pydantic-ai完整版后即可直接使用若使用精简版需要显式安装crusoe可选组。该可选组的依赖定义位于 pydantic_ai_slim/pyproject.tomlcrusoe [openai3.8.0]对应命令行安装方式pip install pydantic-ai-slim[crusoe] # 或使用 uv uv add pydantic-ai-slim[crusoe]若未安装openai包源码 pydantic_ai_slim/pydantic_ai/models/crusoe.py 会抛出带提示的ImportError指引用户通过crusoe可选组安装。获取 API Key 与环境变量使用 Crusoe Serverless Inference 前需要在 Crusoe Cloud 控制台选择 Models 并点击Get API Key生成密钥然后将其设置为环境变量export CRUSOE_API_KEYyour-api-key从源码 pydantic_ai_slim/pydantic_ai/providers/crusoe.py 可以看到CrusoeProvider初始化时优先使用显式传入的api_key否则回退到CRUSOE_API_KEY环境变量两者皆无且未传入openai_client时会抛出UserErrorapi_key api_key or os.getenv(CRUSOE_API_KEY) if not api_key and openai_client is None: raise UserError( Set the CRUSOE_API_KEY environment variable or pass it via CrusoeProvider(api_key...) to use the Crusoe provider. )对应的失败路径由 tests/providers/test_crusoe.py 的test_crusoe_provider_need_api_key覆盖验证。CrusoeProvider的默认端点base_url为https://api.inference.crusoecloud.com/v1其 name 为crusoe底层封装openai.AsyncOpenAI客户端。快速开始两种初始化方式方式一按名称使用推荐设置好环境变量后可以直接用crusoe:前缀的模型字符串创建 Agentfrom pydantic_ai import Agent agent Agent(crusoe:zai/GLM-5.2) result agent.run_sync(What is 2 2?) print(result.output)crusoe:前缀会让模型解析器infer_model解析出CrusoeModel而非裸的OpenAIChatModel这一点由 tests/providers/test_crusoe.py 的test_infer_crusoe_model验证infer_model(crusoe:zai/GLM-5.2)返回CrusoeModel实例且model_name为zai/GLM-5.2。方式二直接初始化模型from pydantic_ai import Agent from pydantic_ai.models.crusoe import CrusoeModel model CrusoeModel(zai/GLM-5.2) agent Agent(model)CrusoeModel的构造函数签名见 pydantic_ai_slim/pydantic_ai/models/crusoe.py为def __init__( self, model_name: CrusoeModelName, *, provider: Literal[crusoe] | Provider[AsyncOpenAI] crusoe, profile: ModelProfileSpec | None None, settings: ModelSettings | None None, ):其中provider默认值为crusoe会解析为CrusoeProviderprofile默认由 Provider 根据模型名推导settings作为该模型的默认 ModelSettings。除__init__外其余方法全部继承自OpenAIChatModel基类因此CrusoeModel是一个类型化别名下的轻量子类核心逻辑复用 OpenAI 兼容实现。模型命名规范实验室前缀决定模型 ProfileCrusoe 用一个端点服务多家实验室的开源权重模型因此模型名必须携带实验室前缀例如zai/GLM-5.2、deepseek-ai/DeepSeek-V4-Pro、meta-llama/Llama-3.3-70B-Instruct、openai/gpt-oss-120b。这个前缀正是选择 model profile 的关键——务必保留前缀不要只传裸模型 id。CrusoeProvider.model_profile()实现了前缀到 profile 的映射见 pydantic_ai_slim/pydantic_ai/providers/crusoe.pyvendor_to_profile { meta-llama: meta_model_profile, deepseek-ai: deepseek_model_profile, qwen: qwen_model_profile, google: google_model_profile, openai: harmony_model_profile, # used for gpt-oss models on Crusoe moonshotai: moonshotai_model_profile, zai: zai_model_profile, }解析逻辑为将模型名小写化后按/分割取出 vendor 前缀并调用对应实验室的 profile 工厂函数未知前缀则回退到OpenAIModelProfile(json_schema_transformerOpenAIJsonSchemaTransformer)。随后用merge_profile合并三层配置厂商 profile、OpenAI JSON Schema 转换器回退、以及强制开启的结构化输出标志supports_json_schema_outputTrue、supports_json_object_outputTrue。这一映射行为由 tests/providers/test_crusoe.py 的test_crusoe_provider_model_profile全面验证meta-llama/...使用InlineDefsJsonSchemaTransformerdeepseek-ai/...使用OpenAIJsonSchemaTransformergoogle/gemma-4-31b-it使用GoogleJsonSchemaTransformeropenai/gpt-oss-120b走 harmony profilezai/GLM-5.2走 zai profile而unknown-vendor/unknown-model也能得到带OpenAIJsonSchemaTransformer的可用 profile。已收录的模型名源码 pydantic_ai_slim/pydantic_ai/models/crusoe.py 通过LatestCrusoeModelNames类型收录了一批已知模型列表会随仓库更新变化包括Qwen/Qwen3-235B-A22B-Instruct-2507deepseek-ai/DeepSeek-V3-0324、deepseek-ai/DeepSeek-V4-Pro、deepseek-ai/Deepseek-V4-Flashgoogle/gemma-4-31b-itmeta-llama/Llama-3.3-70B-Instructmoonshotai/Kimi-K2.6nvidia/NVIDIA-Nemotron-3-*、nvidia/Nemotron-3.5-Lightning-30B-A3B等系列openai/gpt-oss-120byutori/n1.5zai/GLM-5.1、zai/GLM-5.2CrusoeModelName str | LatestCrusoeModelNames的类型注解允许任意字符串因为 Crusoe 模型列表变动频繁类型层面仅对已知模型给出静态提示最新列表以官方 Serverless Inference 文档为准。结构化输出guided decoding 加持下的 NativeOutputCrusoe 对目录内每个模型都启用了 guided decoding因此NativeOutput在所有模型上都能工作——包括那些通过自家厂商接入时不支持原生结构化输出的模型家族。其底层原理在 pydantic_ai_slim/pydantic_ai/providers/crusoe.py 的model_profile()中有明确体现return merge_profile( OpenAIModelProfile(json_schema_transformerOpenAIJsonSchemaTransformer), profile, ModelProfile(supports_json_schema_outputTrue, supports_json_object_outputTrue), )无论厂商 profile 是否声明支持CrusoeProvider都会在最终 profile 上强制叠加supports_json_schema_output与supports_json_object_output两个标志。代码注释说明response_format即 guided decoding对所有模型生效结构化输出标志优先覆盖厂商 profile 的缺失声明。对应的测试用例 tests/providers/test_crusoe.py 的test_crusoe_provider_supports_structured_output对zai/GLM-5.2zai profile 不声明原生结构化输出支持、meta-llama/...、unknown-vendor/unknown-model、裸模型名四类输入断言两个标志均为True。端到端验证见 tests/models/test_crusoe.py 的test_crusoe_native_outputzai_model_profile不声称支持原生结构化输出若无CrusoeProvider的强制标志NativeOutput(City)会抛出UserError: Native structured output is not supported by this model而实际运行中Agent(model, output_typeNativeOutput(City))成功返回City(cityParis, countryFrance)。使用示例from pydantic import BaseModel from pydantic_ai import Agent, NativeOutput class City(BaseModel): city: str country: str agent Agent(crusoe:zai/GLM-5.2, output_typeNativeOutput(City)) result agent.run_sync(Where is the Eiffel Tower?) print(result.output) # cityParis countryFrance思考reasoning内容解析Crusoe 将思考内容放在非标准字段中返回大多数模型使用reasoningDeepSeek 模型使用reasoning_content。OpenAIChatModel基类会读取这两个字段并还原为ThinkingPart因此CrusoeProvider无需也无法为单一字段做配置——这正是测试文件 tests/models/test_crusoe.py 开头注释所强调的行为。该文件中的test_crusoe_model_simple展示了真实返回结构agent.run(What is 2 2?)的响应包含一个ThinkingPartidreasoning、provider_namecrusoe、内含逐步思考内容与一个TextPart2 2 4.usage 中还记录了reasoning_tokens与output_reasoning_tokens等思考 token 统计。test_crusoe_model_streaming则验证流式场景下agent.run_stream(...).stream_text(deltaTrue)可以正常逐段输出文本。自定义 Provider 与 HTTP 客户端传入自定义 ProviderCrusoeModel的provider参数接受crusoe字符串或任意Provider[AsyncOpenAI]实例。显式传入CrusoeProvider(api_key...)时可以不依赖环境变量from pydantic_ai import Agent from pydantic_ai.models.crusoe import CrusoeModel from pydantic_ai.providers.crusoe import CrusoeProvider model CrusoeModel(zai/GLM-5.2, providerCrusoeProvider(api_keyyour-api-key)) agent Agent(model)CrusoeProvider构造函数支持三种互斥的配置路径见 pydantic_ai_slim/pydantic_ai/providers/crusoe.pyapi_key显式 API Key优先级高于环境变量openai_client传入现成的AsyncOpenAI客户端此时api_key与http_client必须为Nonehttp_client传入自定义的httpx2.AsyncClient或旧版httpx.AsyncClient由 Provider 内部基于base_url与api_key构建AsyncOpenAI客户端。其中test_crusoe_pass_openai_client验证了传入openai.AsyncOpenAI时 Provider 直接复用该实例。自定义 HTTP 客户端通过httpx2.AsyncClient可以精细控制超时、代理、连接池等传输层行为from httpx2 import AsyncClient from pydantic_ai import Agent from pydantic_ai.models.crusoe import CrusoeModel from pydantic_ai.providers.crusoe import CrusoeProvider custom_http_client AsyncClient(timeout30) model CrusoeModel( zai/GLM-5.2, providerCrusoeProvider(api_keyyour-api-key, http_clientcustom_http_client), ) agent Agent(model)工具调用与多轮对话Crusoe 的 OpenAI 兼容端点同样支持函数调用pydantic-ai 的agent.tool_plain装饰器可直接使用。测试 tests/models/test_crusoe.py 的test_crusoe_tool_calling展示了一次完整往返第一轮响应包含ThinkingPart与ToolCallPart(tool_nameget_weather, args{city: Paris})finish_reasontool_callAgent 执行工具后把ToolReturnPart发回第二轮响应再次携带新的思考内容并最终返回TextPart结果。值得注意的是第二轮请求的 usage 中还包含cache_read_tokens64说明 Crusoe 服务端支持 prompt 缓存多轮工具调用时可节省输入 token。小结pydantic_ai.models.crusoe是 pydantic-ai 接入 Crusoe Serverless Inference 的官方适配层核心要点可归纳为安装pip install pydantic-ai-slim[crusoe]依赖openai3.8.0认证设置CRUSOE_API_KEY环境变量或在CrusoeProvider(api_key...)中显式传入命名模型名必须携带实验室前缀如zai/、deepseek-ai/前缀决定 model profile 的解析结构化输出guided decoding 使NativeOutput对目录内所有模型生效无需关心厂商原生支持思考解析非标准字段reasoning/reasoning_content由OpenAIChatModel基类自动读取为ThinkingPart扩展性provider参数支持传入自定义CrusoeProvider并可注入httpx2.AsyncClient或现成的AsyncOpenAI客户端以定制传输层。相关参考资料模型 API 文档见 docs/api/models/crusoe.md 与 docs/models/crusoe.md底层实现位于 pydantic_ai_slim/pydantic_ai/models/crusoe.py 和 pydantic_ai_slim/pydantic_ai/providers/crusoe.py测试用例见 tests/models/test_crusoe.py 与 tests/providers/test_crusoe.py。【免费下载链接】pydantic-aiHow Python does AI. Agents, realtime voice, image generation, embeddings. Every model, every interface, typed end to end.项目地址: https://gitcode.com/GitHub_Trending/py/pydantic-ai创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价