Pydantic AI 接入 Cohere安装配置、Provider 定制与 Model Settings 实战指南【免费下载链接】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本指南讲解在 Pydantic AI 中如何接入 Cohere 模型Command R 系列等覆盖安装方式、API Key 配置、环境变量、两种模型初始化方式、自定义Provider与 HTTP 客户端以及CohereModelSettings的参数用法并结合仓库源码剖析请求转发、工具调用与用量统计等底层实现。读完本文你将能够在自己的 Agent 应用中完整接入 Cohere并掌握调试与优化其运行行为的具体手段。本文以仓库内 docs/models/cohere.md 为骨架底层细节均对照 pydantic_ai_slim/pydantic_ai/models/cohere.py、pydantic_ai_slim/pydantic_ai/providers/cohere.py 与对应测试 tests/models/test_cohere.py 展开。安装cohere可选依赖组Pydantic AI 的核心包pydantic-ai已内置 Cohere 支持如果你使用的是精简包pydantic-ai-slim则需要通过cohere可选依赖组补装 Cohere 官方 SDKpip/uv-add pydantic-ai-slim[cohere]在源码层面pydantic_ai_slim/pydantic_ai/models/cohere.py 与 pydantic_ai_slim/pydantic_ai/providers/cohere.py 均在try/except ImportError中导入cohereSDKAsyncClientV2等符号未安装时会抛出明确的提示请安装cohere包或使用pip install pydantic-ai-slim[cohere]。这也意味着 Cohere 相关类型只有在安装该依赖后才会真正可用。获取 API Key要使用 Cohere 官方 API需要先到 Cohere 开发者控制台dashboard.cohere.com/api-keys页面生成一个 API Key。说明由于仓库为只读镜像这里仅介绍操作流程不提供外部链接跳转请按上述页面路径自行完成注册与密钥创建。CohereModelName类型见 pydantic_ai_slim/pydantic_ai/models/cohere.py收录了当前最流行的 Cohere 模型名下文会单独展开说明。配置环境变量拿到 API Key 后将其导出为环境变量CO_API_KEYexport CO_API_KEYyour-api-key从源码看CO_API_KEY是CohereProvider的默认凭据来源pydantic_ai_slim/pydantic_ai/providers/cohere.py 中会先读取api_key参数未提供时回退到os.getenv(CO_API_KEY)两者都缺失时抛出UserError提示「设置CO_API_KEY环境变量或通过CohereProvider(api_key...)传入」。此外还支持CO_BASE_URL环境变量覆盖 API 端点地址同文件第 80 行。方式一按模型名直接使用设置好环境变量后最简单的方式是直接在Agent中按名称引用 Cohere 模型格式为cohere:模型名from pydantic_ai import Agent agent Agent(cohere:command-r7b-12-2024) ...Pydantic AI 会根据cohere:前缀自动推断出对应的模型与 Provider源码中CohereModel.__init__的provider参数默认值即为字符串cohere随后通过infer_provider解析见 pydantic_ai_slim/pydantic_ai/models/cohere.py。方式二直接初始化CohereModel当需要对模型做更精细的控制时可以直接实例化CohereModel并传入Agentfrom pydantic_ai import Agent from pydantic_ai.models.cohere import CohereModel model CohereModel(command-r7b-12-2024) agent Agent(model) ...CohereModel.__init__的完整签名见 pydantic_ai_slim/pydantic_ai/models/cohere.py为CohereModel( model_name: CohereModelName, *, provider: Literal[cohere] | Provider[AsyncClientV2] cohere, profile: ModelProfileSpec | None None, settings: ModelSettings | None None, )其中settings参数可在模型层面预设默认的ModelSettingsprofile用于指定模型画像默认由 Provider 根据模型名挑选。模型名除了下面列出的最新模型外任意字符串都可以传入——CohereModelName被定义为str | LatestCohereModelNames这是为了兼容 Cohere 大量带日期戳的历史模型命名。支持的模型名CohereModelName源码中LatestCohereModelNamespydantic_ai_slim/pydantic_ai/models/cohere.py明确列出了最新一批模型模型名说明command-r7b-12-2024Command R 系列 7B 参数模型文档示例默认模型command-r-08-2024Command R 系列command-r-plus-08-2024Command R 高端型号command-nightlyCommand 每日构建版c4ai-aya-expanse-32bAya Expanse 32Bc4ai-aya-expanse-8bAya Expanse 8B由于 Cohere 持续发布带日期戳的模型类型注解允许任何字符串完整的可用模型清单以 Cohere 官方模型文档为准。此外模型画像逻辑pydantic_ai_slim/pydantic_ai/profiles/cohere.py会检测模型名中是否包含reasoning子串——例如command-a-reasoning-08-2025——命中时自动启用supports_thinkingTrue与thinking_always_enabledTrue即推理类模型默认开启思维链输出对应测试见 tests/models/test_cohere.py。自定义provider参数默认情况下 Pydantic AI 会根据环境变量自动构建 Cohere Provider。当需要显式控制认证信息时可以手动构造CohereProvider并传入provider参数from pydantic_ai import Agent from pydantic_ai.models.cohere import CohereModel from pydantic_ai.providers.cohere import CohereProvider model CohereModel(command-r7b-12-2024, providerCohereProvider(api_keyyour-api-key)) agent Agent(model) ...CohereProvider.__init__pydantic_ai_slim/pydantic_ai/providers/cohere.py支持三个互斥/可选的参数api_key显式 API Key缺省时回退CO_API_KEY环境变量cohere_client直接复用已有的AsyncClientV2实例一旦传入api_key与http_client必须为None有断言保护http_client自定义httpx.AsyncClient。CohereProvider同时持有 v2 与 v1 两个客户端AsyncClientV2与AsyncClient其name属性固定返回coherebase_url默认指向https://api.cohere.com该默认值被测试 tests/models/test_cohere.py 断言锁定。自定义 HTTP 客户端CohereProvider还支持注入自定义http_client这在需要设置超时、代理或连接池时非常有用from httpx import AsyncClient from pydantic_ai import Agent from pydantic_ai.models.cohere import CohereModel from pydantic_ai.providers.cohere import CohereProvider custom_http_client AsyncClient(timeout30) model CohereModel( command-r7b-12-2024, providerCohereProvider(api_keyyour-api-key, http_clientcustom_http_client), ) agent Agent(model) ...从源码看http_client会被同时用于构造 v2 与 v1 两个 Cohere 客户端若不传则使用create_async_http_client()创建的默认客户端pydantic_ai_slim/pydantic_ai/providers/cohere.py。关于 SDK 重试重要注意事项与 OpenAI、Anthropic、Groq 的客户端不同Cohere 官方客户端不暴露max_retries之类的重试开关它的内置客户端会在你传入的 transport 之上对服务端错误和限流rate limit自动重试两次且无法关闭。因此在设计 HTTP 传输层transport的重试策略时务必把这个因素考虑进去——否则会出现「传输层重试 × SDK 内置重试」叠加放大的效果。Pydantic AI 将重试分为多个层级其中 Provider SDK 内置重试与传输层重试相互叠加而不是互相替代详见 docs/retries.md 中「Provider SDK retries」一节的说明。Cohere 的 SDK 重试说明也收录在该文档的 Provider 专属设置列表中。模型设置CohereModelSettings可以通过CohereModelSettings定制模型行为。它继承自ModelSettings在源码中目前是一个占位类所有字段必须带cohere_前缀以便与其他模型设置合并见 pydantic_ai_slim/pydantic_ai/models/cohere.py实际生效的字段来自ModelSettings的公共字段。from pydantic_ai import Agent from pydantic_ai.models.cohere import CohereModel, CohereModelSettings model CohereModel(command-r7b-12-2024) settings CohereModelSettings( temperature0.2, top_k40, ) agent Agent(model, model_settingssettings) ...支持的设置字段对照 pydantic_ai_slim/pydantic_ai/settings.py 中的ModelSettings定义以及 pydantic_ai_slim/pydantic_ai/models/cohere.py 中_chat方法的转发逻辑Cohere 模型实际会发送到 API 的字段如下ModelSettings字段Cohere API 参数说明max_tokensmax_tokens生成的最大 token 数temperaturetemperature采样随机性0.0附近偏向确定/分析型输出top_pp核采样只考虑累积概率质量达top_p的 tokentop_kk仅从概率最高的前 K 个 token 中采样用于去除「长尾」低概率响应seedseed随机种子理论上可获得更确定的结果presence_penaltypresence_penalty对已出现过的新 token 施加惩罚frequency_penaltyfrequency_penalty按 token 出现频率施加惩罚stop_sequencesstop_sequences命中即停止生成的序列列表每个设置项在源码中都是「取到才传、缺省不传」model_settings.get(top_k, OMIT)之类的写法pydantic_ai_slim/pydantic_ai/models/cohere.py保证未配置的字段以 Cohere SDK 的OMIT占位符跳过从而让 Cohere 服务端使用其默认值。测试 tests/models/test_cohere.py 验证了top_k会原样转发为 API 请求中的k参数。源码级原理请求是如何被转发到 Cohere 的消息与工具的映射CohereModel._map_messagespydantic_ai_slim/pydantic_ai/models/cohere.py把 Pydantic AI 内部的ModelRequest/ModelResponse消息结构转换为 Cohere v2 的ChatMessageV2系列系统提示SystemPromptPart→SystemChatMessageV2用户消息UserPromptPart→UserChatMessageV2支持纯文本与多段TextContentCachePoint会被静默跳过有专门测试test_cache_point_silently_skipped_user_prompt_part固定该行为工具结果ToolReturnPart与工具重试RetryPromptPart→ToolChatMessageV2助手消息会同时聚合文本、思考ThinkingPart与工具调用ToolCallV2。值得注意的限制Cohere 目前不支持多模态输入。当用户消息中出现文本以外的内容如ImageUrl时会抛出RuntimeError(Cohere does not yet support multi-modal inputs.)pydantic_ai_slim/pydantic_ai/models/cohere.py对应测试 tests/models/test_cohere.py。此外空的助手响应既无文本也无工具调用会被从历史中剔除避免 Cohere 返回 400见test_cohere_empty_response_skipped_in_history。工具选择tool_choice的适配Cohere v2 API 的tool_choice只接受REQUIRED/NONE或省略让模型自行决定且不支持按工具名定向。因此_get_tool_choicepydantic_ai_slim/pydantic_ai/models/cohere.py采用了与 Mistral 适配器类似的策略tool_choicenone→ 发送tool_choiceNONE工具列表保留tool_choicerequired→ 发送tool_choiceREQUIREDtool_choiceauto→ 省略该参数由模型决定当解析结果限定到某个命名子集list[str]时由于 Cohere 无法按名定向实现会过滤工具列表只保留子集内的工具再通过REQUIRED/省略来控制是否强制调用。这与ModelSettings.tool_choice文档中「Cohere命名子集通过过滤工具列表实现而非作为参数发送」的描述一致pydantic_ai_slim/pydantic_ai/settings.py。结束原因与错误的映射响应处理_process_responsepydantic_ai_slim/pydantic_ai/models/cohere.py会把 Cohere 的ChatFinishReason映射为 Pydantic AI 统一的FinishReasonCohere 结束原因Pydantic AI 结束原因COMPLETEstopSTOP_SEQUENCEstopMAX_TOKENSlengthTOOL_CALLtool_callERRORerror错误处理方面pydantic_ai_slim/pydantic_ai/models/cohere.pyCohere SDK 抛出的ApiError若带status_code 400会被转换为ModelHTTPError保留状态码、响应体与响应头测试test_model_status_error验证了retry-after、x-request-id等头部会原样透传其他情况转换为ModelAPIError。用量统计Usage_map_usagepydantic_ai_slim/pydantic_ai/models/cohere.py将 Cohere 响应中的billed_units计费单位、tokens与cached_tokens归一化到RequestUsagebilled_units.input_tokens/output_tokens/search_units/classifications进入details顶层tokens字段Cohere SDK 中为 float 类型会被转成 int 后作为一等字段input_tokens/output_tokenscached_tokens归一化为cache_read_tokens用于提示词缓存命中统计——相关测试test_request_usage_with_cached_tokens验证了缓存命中的提取路径VCR 测试则验证了真实 API 返回tests/models/test_cohere.py、tests/models/test_cohere.py。推理模型与思考输出当使用名称含reasoning的模型如command-a-reasoning-08-2025时模型画像会自动开启 thinking 支持见上文「支持的模型名」小节。测试 tests/models/test_cohere.py 展示了跨模型接力场景先用 OpenAI 模型产出ThinkingPart历史再切换为 Cohere 推理模型继续对话Cohere 适配器会把响应中的thinking内容映射为ThinkingPartpydantic_ai_slim/pydantic_ai/models/cohere.py说明 Pydantic AI 的思考链路对 Cohere 推理模型是完整打通的。常见问题速查提示缺少 API KeyUserError提示「Set theCO_API_KEYenvironment variable or pass it viaCohereProvider(api_key...)」——按上文配置环境变量或显式传参即可。未安装cohere包ImportError会明确提示使用pip install pydantic-ai-slim[cohere]。多模态输入Cohere 适配器不支持图片等多模态内容会抛RuntimeError请改用纯文本输入或选择其他支持多模态的模型如 OpenAI、Google。传输层重试叠加Cohere SDK 内置的两次重试不可关闭配置自定义http_client的重试策略时应参考 docs/retries.md 中关于重试层级与相乘效应的说明避免重试次数被意外放大。相关参考文档模型配置总览、Cohere API 参考、Provider SDK 重试说明。【免费下载链接】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),仅供参考
