CAMEL 框架中 AnthropicConfig 配置类完全指南:从采样参数到扩展思考与提示缓存 📅 发布时间:2026/9/14 6:26:59 👁 浏览次数: CAMEL 框架中 AnthropicConfig 配置类完全指南从采样参数到扩展思考与提示缓存【免费下载链接】camel CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org项目地址: https://gitcode.com/GitHub_Trending/ca/camel导读本文以 CAMEL 开源框架的 API 参考文档 camel.configs.anthropic_config 为主体系统讲解AnthropicConfig配置类的全部字段语义、默认行为与底层实现机制并结合 AnthropicModel 源码、官方示例与单元测试说明如何在 CAMEL 的 Agent 体系中接入 Claude 系列模型、开启扩展思考Extended Thinking、提示缓存Prompt Caching与结构化输出。读完本文你将掌握AnthropicConfig的完整参数面能直接写出可运行、可调优的 Claude 模型接入代码。一、AnthropicConfig 是什么AnthropicConfig是 CAMEL 框架中用于定义 Anthropic Messages API 聊天补全请求参数的配置类定义于 camel/configs/anthropic_config.py继承自BaseConfigclass AnthropicConfig(BaseConfig): rDefines the parameters for generating chat completions using the Anthropic API. 它本质上是一个基于 Pydantic 的配置容器所有字段默认值为None未显式设置的参数不会被发送到 Anthropic API。框架设计上CAMEL 各模型平台均提供同名*Config类如 OpenAIConfig、GeminiConfig 等AnthropicConfig是 Claude 系列模型在 CAMEL 中的统一配置入口。1.1 继承自 BaseConfig 的公共能力在深入各参数之前需要理解 BaseConfig 带来的三条公共约束它们直接影响AnthropicConfig的使用方式extraforbid传入配置类中不存在的字段会直接报错防止拼写错误被静默忽略frozenTrue配置对象一旦创建即不可变保证同一份配置在多次请求中行为一致as_dict()将配置对象序列化为字典并剔除所有None值因为部分 API如 OpenAI Beta 工具接口不接受None同时把tools列表统一转换为 OpenAI 工具 Schema。def as_dict(self) - dict[str, Any]: config_dict self.model_dump() # Convert tools to OpenAI tool schema config_dict[tools] ( [tool.get_openai_tool_schema() for tool in self.tools] if self.tools else None ) # Remove None values return {k: v for k, v in config_dict.items() if v is not None}此外BaseConfig定义了tools字段最多支持 128 个函数并带有字段校验器fields_type_checking工具必须是camel.toolkits.FunctionTool实例否则抛出ValueError。二、参数全解逐字段深入AnthropicConfig共定义 13 个请求相关字段不含继承自基类的tools与 API 参考文档逐一对应。以下按功能分组说明。2.1 生成控制参数字段类型默认值说明max_tokensOptional[int]None停止前最多生成的 token 数。Anthropic 模型可能提前停止该值只表示绝对上限。Anthropic API 的必填参数实际使用时建议显式设置temperatureOptional[float]None注入响应的随机程度范围 0~1默认 1。接近 0 适合分析/选择题接近 1 适合创意生成。注意即使为 0.0 结果也非完全确定top_pOptional[float]None核采样nucleus sampling按概率降序累积分布截断到指定概率阈值。官方建议temperature与top_p只改其一top_kOptional[int]None每个后续 token 只从概率最高的 K 个候选中采样用于去除长尾低概率响应stop_sequencesOptional[List[str]]None自定义停止序列列表。模型正常回合结束即停止若命中自定义序列则终止生成且stop_reason为stop_sequencestreamOptional[bool]None是否通过 Server-Sent Events 增量流式返回响应在源码中_run方法只把这五个生成控制参数透传给 Anthropic SDKfor key in [ temperature, top_p, top_k, stop_sequences, metadata, ]: if key in self.model_config_dict: request_params[key] self.model_config_dict[key]而max_tokens始终作为必填项进入请求体max_tokens: self.model_config_dict.get(max_tokens, None)见 anthropic_model.py。2.2 请求元数据与工具控制参数metadataOptional[dict]描述请求的元数据对象典型用途是携带user_id作为与请求关联的外部用户标识便于调用侧做审计与配额管理。tool_choiceOptional[dict]控制模型如何使用已提供的工具可取使用指定工具使用任意可用工具模型自行决定或完全不使用工具。示例见下文实战部分。extra_headersOptional[dict]附加到请求的 HTTP 头。extra_bodyOptional[dict]透传给 Anthropic API 的额外请求体参数用于覆盖 SDK 未显式封装的字段。其中extra_headers在 AnthropicModel._run 中被直接取出并放入request_paramsextra_body则经深拷贝后参与output_config合并见 2.4。2.3 提示缓存参数 cache_controlcache_controlOptional[Literal[5m, 1h]]提示缓存Prompt Caching的 TTL 控制5m表示 5 分钟缓存1h表示 1 小时缓存。默认None表示不启用。该参数在 AnthropicModel 构造函数 中被严格校验并转换为 Anthropic 的ephemeral缓存块格式if cache_control is not None and cache_control not in (5m, 1h): raise ValueError( fInvalid cache_control value: {cache_control!r}. fMust be either 5m or 1h. ) self._cache_control_config None if cache_control: self._cache_control_config { type: ephemeral, ttl: cache_control, }启用后请求构建阶段会将该缓存块分别附加到system 消息和最后一条用户消息上见 anthropic_model.py使得长对话上下文的后续轮次请求可以命中缓存从而降低延迟与成本。对应的单元测试 test/models/test_anthropic_model.py 覆盖了合法值5m、1h与非法值如10m抛ValueError两种路径。2.4 扩展思考与输出配置参数thinkingOptional[Dict[str, Any]]Claude 模型扩展思考Extended Thinking配置。文档给出的合法形态包括{type: enabled, budget_tokens: 1024}启用思考并设定预算 token 数{type: enabled, budget_tokens: 1024, display: omitted}启用思考但不向用户展示思考内容{type: adaptive}自适应思考模式由模型根据任务复杂度动态决定思考强度。thinking在请求中被整体透传request_params[thinking] copy.deepcopy(thinking)。同时thinking 与工具调用的组合存在限制当思考启用时tool_choice只支持{type: auto}或{type: none}否则抛出ValueErrorAnthropic 扩展思考 工具的限制。值得注意的是test_anthropic_model.py 的测试 验证了thinking{type: adaptive}与output_config{effort: medium}可以组合使用。output_configOptional[Dict[str, Any]]Anthropic 输出配置有两个典型用途与自适应思考adaptive thinking配合设置思考强度effort配合结构化输出Structured Outputs指定输出 JSON Schema。AnthropicModel._build_request_output_config 展示了它的合并逻辑先取extra_body中遗留的output_config再合并model_config_dict中配置的output_config最后如果调用侧传入了response_formatPydantic 模型则通过_build_output_config用transform_schema把 Pydantic JSON Schema 转成 Anthropic 的json_schema格式并合并进去最终作为output_config.format发送。这意味着结构化输出可以完全由 CAMEL 的response_format参数驱动无需手写 Schema。2.5 模块级常量 ANTHROPIC_API_PARAMS源码末尾还定义了一个模块级集合ANTHROPIC_API_PARAMS {param for param in AnthropicConfig.model_fields.keys()}它动态收集配置类的全部字段名供上层代码如模型工厂、参数透传逻辑判断哪些参数属于 Anthropic API 原生参数避免把无关配置误传给 SDK。三、与 AnthropicModel 的配合方式AnthropicConfig本身不发起任何网络请求它需要配合AnthropicModel定义于 camel/models/anthropic_model.py使用。AnthropicModel把 Anthropic SDK 封装进 CAMEL 统一的BaseModelBackend接口并自动完成以下工作默认配置未传model_config_dict时使用AnthropicConfig().as_dict()环境变量读取api_key未传时读取ANTHROPIC_API_KEYurl未传时读取ANTHROPIC_API_BASE_URL超时未传时读取MODEL_TIMEOUT默认 180 秒客户端初始化内部创建anthropic.Anthropic与anthropic.AsyncAnthropic同步/异步双客户端max_retries默认 3 次也支持注入自定义client/async_client消息格式转换将 OpenAI 风格的messages转换为 Anthropic 格式——system 消息抽离为独立system参数、工具结果转换为tool_result内容块、assistant 工具调用转换为tool_use内容块并自动去除消息末尾空白Anthropic API 不允许消息内容以空白结尾响应归一化把 Anthropic 的stop_reasonend_turn/max_tokens/stop_sequence/tool_use/refusal映射为 OpenAI 风格的finish_reasonstop/length/stop/tool_calls/content_filter并把 token 用量统一为prompt_tokens/completion_tokens/total_tokens同时保留缓存命中的cache_read_input_tokens、cache_creation_input_tokens字段流式转换把 Anthropic SSE 流中的message_start、content_block_delta、message_delta等事件转换为 OpenAI 风格的ChatCompletionChunk其中思考增量thinking_delta映射为reasoning_content并处理了finish_reason的防重复发送逻辑。从源码结构看AnthropicModel还内置了严格工具strict tools的降级保护当请求的工具数量、可选参数数量或联合类型参数数量超过 Anthropic 结构化输出上限20 个严格工具、24 个可选参数、16 个联合参数时会自动把工具的strict降为False并发出 warning避免请求被 API 拒绝见 anthropic_model.py。四、实战完整可运行的配置示例4.1 环境准备运行前需要安装 Anthropic 依赖并设置环境变量pip install camel-ai[all] # 或按需安装 anthropic 依赖 export ANTHROPIC_API_KEYsk-ant-... # 可选第三方 Anthropic 兼容服务 export ANTHROPIC_API_BASE_URLhttps://your-endpoint # 可选请求超时秒默认 180 export MODEL_TIMEOUT3004.2 基础配置创建 Claude 模型并驱动 ChatAgent下面的代码取自官方示例 examples/models/anthropic_model_example.py演示了AnthropicConfig与ModelFactory、ChatAgent的组合from camel.agents import ChatAgent from camel.configs import AnthropicConfig from camel.models import ModelFactory from camel.toolkits import MathToolkit from camel.types import ModelPlatformType, ModelType def create_anthropic_model(stream: bool False): rCreate a Claude Opus 4.7 model with adaptive thinking enabled. model_config AnthropicConfig( max_tokens16000, streamstream, thinking{type: adaptive}, output_config{effort: medium}, tool_choice{type: auto}, ).as_dict() return ModelFactory.create( model_platformModelPlatformType.ANTHROPIC, model_typeModelType.CLAUDE_OPUS_4_7, model_config_dictmodel_config, ) math_tools MathToolkit().get_tools() camel_agent ChatAgent( system_messageYou are a helpful assistant., modelcreate_anthropic_model(), toolsmath_tools, ) user_msg ( Use the math_multiply tool to calculate 3 * 7 * 11, then use the result to explain why the Euclid-style number 4 * (3 * 7 * 11) - 1 is congruent to 3 modulo 4. ) response camel_agent.step(user_msg) answer response.msgs[0] print(Answer:) print(answer.content) if response.info and response.info.get(tool_calls): print(\nTool calls:) print(response.info[tool_calls]) if answer.reasoning_content: print(\nThinking summary:) print(answer.reasoning_content)该示例同时演示了流式模式AnthropicConfig(streamTrue)创建的模型配合stream_accumulateFalse的ChatAgent逐块打印reasoning_content与content。注意示例中thinking{type: adaptive}与output_config{effort: medium}搭配使用——这正是 2.4 节提到的自适应思考 effort组合而tool_choice{type: auto}也符合思考模式下工具选择的限制。4.3 提示缓存实战长对话上下文复用官方示例 examples/models/prompt_caching_anthropic_example.py 展示了cache_control5m的典型应用——让 Agent 抓取网页后连续追问同一篇文章的多个问题from camel.agents import ChatAgent from camel.configs import AnthropicConfig from camel.models import ModelFactory from camel.toolkits import FunctionTool from camel.types import ModelPlatformType, ModelType model ModelFactory.create( model_platformModelPlatformType.ANTHROPIC, model_typeModelType.CLAUDE_SONNET_4_5, model_config_dictAnthropicConfig( max_tokens64000, cache_control5m, ).as_dict(), ) agent ChatAgent( system_messageYou are a helpful assistant., modelmodel, tools[FunctionTool(fetch_url)], ) # 第一轮Agent 自行抓取博客并总结 response agent.step(fPlease read this blog post and summarise it...: {BLOG_URL}) print(f Usage: {response.info.get(usage, {})}) # 后续轮次复用已缓存的长上下文更快更省 for question in follow_ups: response agent.step(question) print(f Usage: {response.info.get(usage, {})})使用效果可以从response.info[usage]中的cache_read_input_tokens字段观察——该字段由 2.3 节提到的_extract_usage逻辑从 Anthropic 响应中提取当后续轮次命中缓存时会显著大于 0。4.4 结构化输出实战Pydantic 模型驱动示例 examples/models/anthropic_structured_output_example.py 演示了response_format与工具结合的完整链路——模型先调用工具查证再按 Pydantic 模型输出结构化 JSONclass TripDecision(BaseModel): recommended_area: str Field(descriptionBest Kyoto area for a first-time weekend visitor) estimated_total_budget_rmb: int Field(descriptionEstimated total budget in RMB) must_visit_spot: str Field(descriptionOne attraction selected using tool-backed context) transport_tip: str Field(descriptionShort practical transport advice) # 注意这里直接使用 AnthropicModelmodel_config_dict 仅显式设置 max_tokens return AnthropicModel( model_typemodel_type, api_keyapi_key, urlbase_url, token_counterOpenAITokenCounter(ModelType.GPT_4O_MINI), # 第三方兼容平台可改用本地计数 model_config_dict{max_tokens: 800}, ) response agent.step( Plan a first-time 2-day Kyoto weekend ... Return only the structured result., response_formatTripDecision, ) print(response.msgs[0].parsed.model_dump())该示例还提示了一个兼容性细节第三方 Anthropic 兼容平台若无法访问 Anthropic 官方的count_tokensAPI可以像示例中那样注入OpenAITokenCounter作为本地兜底 token 计数器。4.5 通过 YAML 文件配置AnthropicConfig同样支持从 YAML 配置驱动。仓库测试中提供了示例配置文件 test/models/test_config_file/yaml_configs/claude_haiku_4_5_config.yamlmodel_platform: ANTHROPIC model_type: CLAUDE_HAIKU_4_5 model_config_dict: temperature: 0.7 top_p: 0.9 max_tokens: 1024 token_counter: null api_key: test_key url: null可以看到model_config_dict中的键与AnthropicConfig字段一一对应temperature、top_p、max_tokens等生成控制参数可直接在配置文件中声明实现配置与代码分离。五、设计要点与最佳实践综合 anthropic_config.py 与 anthropic_model.py 的源码总结以下几点实用经验max_tokens务必显式设置它是 Anthropic API 的必填参数虽然配置类默认值为None不会报错但框架会把它原样传给 SDK最终由 SDK 端处理。为稳定计所有示例都显式赋值。temperature与top_p只改其一两者都作用于采样分布同时调整会互相干扰这也是官方文档的明确建议。思考模式下工具选择的限制启用thinking后tool_choice仅支持{type: auto}或{type: none}违反会抛出ValueError。若需要强制调用某工具需关闭思考或改用其他方式编排。缓存 TTL 取值严格受限cache_control只接受字面量5m或1h其它字符串会在模型构造阶段直接报错而不是等到请求时失败——这是 CAMEL 将参数校验前置到构造期的一个体现。结构化输出无需手写 Schema传入 Pydanticresponse_format后框架会自动完成 JSON Schema 转换transform_schema 类型列表归一化并合并进output_config。调试手段metadata可携带user_id用于请求关联extra_headers与extra_body可透传平台扩展能力响应中的stop_reason语义end_turn/max_tokens/stop_sequence/tool_use/refusal经归一化后可从finish_reason直接判断生成结束原因。六、验证与测试仓库对AnthropicConfig及其与AnthropicModel的联动有完整的单元测试覆盖见 test/models/test_anthropic_model.py默认配置断言未传配置时model.model_config_dict AnthropicConfig().as_dict()第 77 行缓存合法性cache_control5m正确生成_cache_control_config非法值如10m抛出ValueError第 116-150 行思考字段thinking{type: adaptive}与output_config{effort: medium}被正确保留在配置字典中第 152-160 行思考块透传带思考块的响应会被转换为 OpenAI 格式并缓存到_tool_call_thinking_blocks供工具调用续轮复用第 444-545 行流式思考增量thinking_delta块被正确累积为thinking_blocks状态第 805-865 行。这些测试既是行为契约也是排查接入问题的参考手册例如当发现缓存未生效时可对照缓存相关用例检查cache_control取值当思考内容丢失时可对照思考块用例检查消息转换路径。结语AnthropicConfig虽然只是一个配置类却是 CAMEL 接入 Claude 系列模型的总开关采样参数控制生成质量thinking与output_config解锁扩展思考与结构化输出cache_control优化长上下文成本tool_choice与tools字段则让 Claude 无缝融入 CAMEL 的 Agent 工具调用体系。结合AnthropicModel的自动消息转换、响应归一化与流式封装开发者只需关注配置本身即可让 Claude 与 CAMEL 生态中的ChatAgent、ModelFactory、FunctionTool等组件协同工作。【免费下载链接】camel CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org项目地址: https://gitcode.com/GitHub_Trending/ca/camel创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考