
Agent-Skills-for-Context-Engineering 实战MiniMax-M2.1 Interleaved Thinking 与工具调用最佳实践【免费下载链接】Agent-Skills-for-Context-EngineeringA comprehensive collection of Agent Skills for context engineering, multi-agent architectures, and production agent systems. Use when building, optimizing, or debugging agent systems that require effective context management.项目地址: https://gitcode.com/GitHub_Trending/ag/Agent-Skills-for-Context-Engineering本指南围绕examples/interleaved-thinking/docs/interleavedthinking.md展开系统讲解 MiniMax-M2.1 的 Interleaved Thinking交错思考机制在工具调用Tool Use场景下的正确用法如何通过 Anthropic SDK 与 OpenAI SDK 接入、如何解析 thinking / tool_calls / reasoning_details 等关键字段以及为什么“完整保留模型响应到历史消息”是维持推理链连续性的生命线。读完本文你将能够正确搭建多轮工具调用循环避免因丢弃思考内容导致的性能退化并了解本仓库 Reasoning Trace Optimizer 如何利用该机制进行 Agent 调试与提示词优化。一、Interleaved Thinking 是什么Agent 能力的核心差异MiniMax-M2.1 是一个具备卓越工具调用能力的 Agentic Model其原生支持Interleaved Thinking交错思考模型可以在每一轮工具交互之间进行推理在每次 Tool Use 之前模型都会先反思当前环境与工具输出再决定下一步动作。这一点与传统推理模型有本质区别examples/interleaved-thinking/README.md 中给出了直观对比Traditional: Think → Act → Act → Act → Done ↑ (reasoning only at start) M2.1: Think → Act → Think → Act → Think → Act → Done ↑ ↑ ↑ (continuous reasoning between each tool call)这一设计之所以关键根据配套文档 examples/interleaved-thinking/docs/agentthinking.md 的阐述主要有两点原因长程任务Long-Horizon Tasks中维持专注复杂 Agent 任务的上下文极长仅在开始时思考一次不足以维持指令遵循与连贯性。适应外部扰动External PerturbationsAgent 任务会不断引入来自外部世界的不可预测扰动即工具输出模型必须足够健壮能够诊断错误、提取有用信息并持续重新评估环境。思考过程让模型能够实时适应新信息。正因如此M2.1 在 SWE、BrowseCamp、xBench 等同时考验编码与 Agentic 推理能力的基准上表现出色。核心要点是每次都要返回模型的完整响应尤其是内部推理字段thinking 或 reasoning_details——这是本篇文章贯穿始终的第一原则。二、工具调用核心机制请求与响应参数请求参数tools定义可调用函数的列表包含函数名、描述与参数 schemaJSON Schema 格式。响应参数工具调用响应中的关键字段字段说明thinking/reasoning_details模型的思考/推理过程text/content模型输出的文本内容tool_calls模型决定调用的函数信息function.name被调用函数的名称function.arguments函数调用参数JSON 字符串格式id工具调用的唯一标识符注意字段的呈现方式会因 SDK 与调用格式而异通过 Anthropic SDK 调用时思考内容以thinkingblock 形式返回通过 OpenAI SDK 调用且设置reasoning_splitTrue时思考内容被分离到独立的reasoning_details字段使用 OpenAI 原生格式reasoning_splitFalse时思考内容被包裹在content字段的think.../think标签内。三种格式的差异与取舍将在后文逐一展开。三、多轮调用中最关键的一条原则完整保留模型响应在多轮函数调用会话中必须将模型的完整响应assistant message追加到会话历史中以维持推理链的连续性。这是最容易出错、也最影响性能的环节——很多社区反馈的“性能下降”问题根源正是沿用简单推理模型的使用习惯、意外丢弃了这部分关键上下文。针对两种 SDK规则分别如下OpenAI SDK将完整的response_message对象包含tool_calls字段追加到消息历史。使用 MiniMax-M2.1 时content字段包含think标签会被自动保留在 Interleaved Thinking 兼容格式下通过额外参数reasoning_splitTrue将思考内容分离到reasoning_details字段该内容同样需要加入历史消息。Anthropic SDK将完整的response.content列表追加到消息历史包含 thinking / text / tool_use 等全部内容块。这一原则在本仓库源码中有直接印证。examples/interleaved-thinking/reasoning_trace_optimizer/capture.py 中的TraceCapture.run()在多轮循环里正是这样做的# Append assistant response to history (CRITICAL for M2.1) messages.append({role: assistant, content: response.content}) ... # Add tool results to messages messages.append({role: user, content: tool_results})代码注释中的CRITICAL for M2.1与文档中的警告如出一辙——完整保留 assistant 响应含全部 thinking block是 M2.1 发挥最佳性能的前提。四、Anthropic SDK 实战完整示例配置环境变量国际用户使用https://api.minimax.io/anthropic中国用户使用https://api.minimaxi.com/anthropicexport ANTHROPIC_BASE_URLhttps://api.minimax.io/anthropic export ANTHROPIC_API_KEY${YOUR_API_KEY}完整代码以下示例定义一个天气查询工具并通过 Anthropic SDK 完成「用户提问 → 模型思考并调用工具 → 执行工具 → 返回结果 → 模型最终回复」的完整链路import anthropic import json # Initialize client client anthropic.Anthropic() # Define tool: weather query tools [ { name: get_weather, description: Get weather of a location, the user should supply a location first., input_schema: { type: object, properties: { location: { type: string, description: The city and state, e.g. San Francisco, US, } }, required: [location] } } ] def send_messages(messages): params { model: MiniMax-M2.1, max_tokens: 4096, messages: messages, tools: tools, } response client.messages.create(**params) return response def process_response(response): thinking_blocks [] text_blocks [] tool_use_blocks [] # Iterate through all content blocks for block in response.content: if block.type thinking: thinking_blocks.append(block) print(f Thinking\n{block.thinking}\n) elif block.type text: text_blocks.append(block) print(f Model\t{block.text}) elif block.type tool_use: tool_use_blocks.append(block) print(f Tool\t{block.name}({json.dumps(block.input, ensure_asciiFalse)})) return thinking_blocks, text_blocks, tool_use_blocks # 1. User query messages [{role: user, content: Hows the weather in San Francisco?}] print(f\n User\t {messages[0][content]}) # 2. Model returns first response (may include tool calls) response send_messages(messages) thinking_blocks, text_blocks, tool_use_blocks process_response(response) # 3. If tool calls exist, execute tools and continue conversation if tool_use_blocks: # ⚠️ Critical: Append the assistants complete response to message history # response.content contains a list of all blocks: [thinking block, text block, tool_use block] # Must be fully preserved, otherwise subsequent conversation will lose context messages.append({ role: assistant, content: response.content }) # Execute tool and return result (simulating weather API call) print(f\n Executing tool: {tool_use_blocks[0].name}) tool_result 24℃, sunny print(f Tool result: {tool_result}) # Add tool execution result messages.append({ role: user, content: [ { type: tool_result, tool_use_id: tool_use_blocks[0].id, content: tool_result } ] }) # 4. Get final response final_response send_messages(messages) process_response(final_response)运行输出展示了完整思考链路——模型先分析用户需求、评估工具是否适用、确定参数然后才发起调用拿到工具结果后又对结果进行解读最终组织语言回复 User Hows the weather in San Francisco? Thinking Okay, so the user is asking about the weather in San Francisco. This is a straightforward request that requires me to get current weather information for a specific location. ... Tool get_weather({location: San Francisco}) Executing tool: get_weather Tool result: 24℃, sunny Thinking Ive just called the get_weather tool to check the current conditions in San Francisco as the user requested... ... Model The current weather in San Francisco is 24℃ and sunny.响应体关键字段解读{ id: 05566b15ee32962663694a2772193ac7, type: message, role: assistant, model: MiniMax-M2.1, content: [ { thinking: Let me think about this request. The user is asking about the weather in San Francisco..., signature: cfa12f9d651953943c7a33278051b61f586e2eae016258ad6b824836778406bd, type: thinking }, { type: tool_use, id: call_function_3679004591_1, name: get_weather, input: { location: San Francisco, US } } ], usage: { input_tokens: 222, output_tokens: 321 }, stop_reason: tool_use, base_resp: { status_code: 0, status_msg: } }值得注意的细节响应由多个content block组成thinkingblock含模型思考全文与signature签名与tool_useblock含id、name、input。这正是第三节所说“必须把response.content完整列表追加回历史”的原因——历史中需要同时包含思考块与工具调用块。stop_reason为tool_use表示模型本轮输出以工具调用结尾等待执行工具后继续对话。usage中的input_tokens/output_tokens可用于监控每次调用的 token 消耗在 examples/interleaved-thinking/reasoning_trace_optimizer/capture.py 中这些数字被累加到 trace 的total_tokens用于成本与效率分析。五、OpenAI SDK 实战Interleaved Thinking 兼容格式推荐配置环境变量国际用户使用https://api.minimax.io/v1中国用户使用https://api.minimaxi.com/v1export OPENAI_BASE_URLhttps://api.minimax.io/v1 export OPENAI_API_KEY${YOUR_API_KEY}Interleaved Thinking Compatible Format通过 OpenAI SDK 调用 MiniMax-M2.1 时可传递额外参数reasoning_splitTrue获得对开发者更友好的输出格式思考内容被分离到独立的reasoning_details字段而不是混在content里。重要提示为确保 Interleaved Thinking 正常运作、模型的思维链不被中断整个response_message包括reasoning_details字段必须完整保留在消息历史中并在下一轮交互时回传给模型。这是达成模型最佳性能的必要条件。实现时请务必检查你的 API 请求与响应处理函数例如send_messages是如何实现的以及如何用messages.append(response_message)追加历史消息。import json from openai import OpenAI client OpenAI() # Define tool: weather query tools [ { type: function, function: { name: get_weather, description: Get weather of a location, the user should supply a location first., parameters: { type: object, properties: { location: { type: string, description: The city and state, e.g. San Francisco, US, } }, required: [location], }, }, }, ] def send_messages(messages): Send messages and return response response client.chat.completions.create( modelMiniMax-M2.1, messagesmessages, toolstools, # Set reasoning_splitTrue to separate thinking content into reasoning_details field extra_body{reasoning_split: True}, ) return response.choices[0].message # 1. User query messages [{role: user, content: Hows the weather in San Francisco?}] print(f User\t {messages[0][content]}) # 2. Model returns tool call response_message send_messages(messages) if response_message.tool_calls: tool_call response_message.tool_calls[0] function_args json.loads(tool_call.function.arguments) print(f Thinking\t {response_message.reasoning_details[0][text]}) print(f Model\t {response_message.content}) print(f Tool\t {tool_call.function.name}({function_args[location]})) # 3. Execute tool and return result messages.append(response_message) messages.append( { role: tool, tool_call_id: tool_call.id, content: 24℃, sunny, # In real applications, call actual weather API here } ) # 4. Get final response final_message send_messages(messages) print( f Thinking\t {final_message.model_dump()[reasoning_details][0][text]} ) print(f Model\t {final_message.content}) else: print(f Model\t {response_message.content})运行输出节选 User Hows the weather in San Francisco? Thinking Alright, the user is asking about the weather in San Francisco... Tool get_weather(San Francisco, US) Thinking Okay, Ive received the users question about the weather in San Francisco, and Ive used the get_weather tool to retrieve the current conditions... Model The weather in San Francisco is currently sunny with a temperature of 24℃.兼容格式响应体解读{ id: 05566b8d51ded3a3016d6cc100685cad, choices: [ { finish_reason: tool_calls, index: 0, message: { content: \n, role: assistant, name: MiniMax AI, tool_calls: [ { id: call_function_2831178524_1, type: function, function: { name: get_weather, arguments: {\location\: \San Francisco, US\} }, index: 0 } ], audio_content: , reasoning_details: [ { type: reasoning.text, id: reasoning-text-1, format: MiniMax-response-v1, index: 0, text: Let me think about this request. The user is asking about the weather in San Francisco... } ] } } ], created: 1762080909, model: MiniMax-M2.1, object: chat.completion, usage: { total_tokens: 560, total_characters: 0, prompt_tokens: 203, completion_tokens: 357 }, input_sensitive: false, output_sensitive: false, base_resp: { status_code: 0, status_msg: } }对比 Anthropic 格式可见reasoning_splitTrue时思考全文从content中剥离进入message.reasoning_details[0].text而tool_calls[0].function.arguments仍是 JSON 字符串需要json.loads解析。finish_reason为tool_calls时表示需要执行工具并继续。六、OpenAI 原生格式reasoning_splitFalse由于 OpenAI ChatCompletion API 原生格式不原生支持思考内容的返回与回传模型的思考会被以thinkreasoning_content/think的形式注入content字段。开发者可以手动解析以便展示但官方强烈推荐使用 Interleaved Thinking 兼容格式。extra_body{reasoning_split: False}的作用将思考嵌入 content模型推理被包裹在content字段的think标签内需要手动解析如需单独展示推理内容需自行解析think标签。重要提醒如果选择原生格式请注意不要修改消息历史中的content字段。必须完整保留模型的思考内容即thinkreasoning_content/think。这是确保 Interleaved Thinking 生效、达到最佳模型性能的关键原生格式代码如下send_messages中改为extra_body{reasoning_split: False}并在打印时直接输出含think标签的contentfrom openai import OpenAI import json # Initialize client client OpenAI( api_keyapi-key, base_urlhttps://api.minimax.io/v1, ) # Define tool: weather query tools [ { type: function, function: { name: get_weather, description: Get weather of a location, the user should supply a location first., parameters: { type: object, properties: { location: { type: string, description: The city and state, e.g. San Francisco, US, } }, required: [location] }, } }, ] def send_messages(messages): Send messages and return response response client.chat.completions.create( modelMiniMax-M2.1, messagesmessages, toolstools, # Set reasoning_splitFalse to keep thinking content in think tags within content field extra_body{reasoning_split: False}, ) return response.choices[0].message # 1. User query messages [{role: user, content: Hows the weather in San Francisco?}] print(f User\t {messages[0][content]}) # 2. Model returns tool call response_message send_messages(messages) if response_message.tool_calls: tool_call response_message.tool_calls[0] function_args json.loads(tool_call.function.arguments) print(f Model\t {response_message.content}) print(f Tool\t {tool_call.function.name}({function_args[location]})) # 3. Execute tool and return result messages.append(response_message) messages.append({ role: tool, tool_call_id: tool_call.id, content: 24℃, sunny # In production, call actual weather API here }) # 4. Get final response final_message send_messages(messages) print(f Model\t {final_message.content}) else: print(f Model\t {response_message.content})运行输出中可以看到思考内容以think.../think标签包裹在content内且前后两轮思考都完整保留 User Hows the weather in San Francisco? Model think Alright, the user is asking about the weather in San Francisco. This is a straightforward request that I can handle using the tools provided to me. ... /think Tool get_weather(San Francisco, US) Model think Let me analyze whats happening in this conversation... /think The weather in San Francisco is currently sunny with a temperature of 24℃.对应响应体中message.content字段即为包含think.../think的完整文本tool_calls结构与兼容格式一致。若需单独展示思考内容需要自行对think标签做解析剥离——这正是官方推荐兼容格式的原因。七、仓库实践Reasoning Trace Optimizer 如何利用 Interleaved Thinking本文档所在的examples/interleaved-thinking目录进一步把 Interleaved Thinking 落地为一个完整的 Agent 调试与提示词优化工具链。其核心思路在 examples/interleaved-thinking/README.md 中概括为TraceCapture包裹 M2.1 API 捕获全部思考块→TraceAnalyzer检测上下文退化、工具混淆、指令漂移等失败模式→PromptOptimizer基于分析生成改进提示词→OptimizationLoop自动化的捕获→分析→改进→重跑循环→SkillGenerator把学习成果转化为可分享的 Agent Skills。这些组件的实现与本文档的要点一一对应完整保留响应如第三节所述capture.py 的run()在每轮都把response.content原样追加进messages并且_process_response会按block.type把thinking、text、tool_use三种块分类记录到ReasoningTrace——这正是本文档“Anthropic SDK 返回三种内容块”的工程化封装。它还额外提供了run_streaming()方法支持通过on_thinking、on_text、on_tool_call回调实时流式展示思考与工具调用。模式检测TraceAnalyzer会依据 analyzer.py 中定义的 10 种失败模式context_degradation、tool_confusion、instruction_drift、hallucination、incomplete_reasoning、tool_misuse、goal_abandonment、circular_reasoning、premature_conclusion、missing_validation对推理轨迹打分并给出建议每个模式包含证据片段、严重级别、改进建议与置信度。自动化优化循环OptimizationLooploop.py以LoopConfig控制迭代次数max_iterations、收敛阈值convergence_threshold、分数达标线min_score_threshold、回归回退阈值regression_threshold、提示词膨胀上限max_prompt_growth等实现“执行 Agent → 捕获轨迹 → 分析模式 → 优化提示词 → 重跑”的闭环并支持最佳提示词追踪与连续回归自动停止。CLI 接入安装后可通过 cli.py 提供的rto命令直接使用例如rto capture 任务描述 -s 系统提示词、rto analyze 任务 -o analysis.txt、rto optimize 任务 --max-iterations 5 --generate-skill、rto generate-skill my-skill-name --artifacts-dir ./optimization_artifacts。真实示例examples/02_tool_usage.py 展示了带get_weather/get_forecast双工具的定义与 mock 执行器写法可直接观察模型在工具输出如旧金山大雾、纽约多云之间如何逐轮调整推理。该工具链本身也作为可复用的 Agent Skill 发布在 examples/interleaved-thinking/SKILL.md可在 Claude Code 中通过/reasoning-trace-optimizer触发会话级推理分析或在工具报错后自动分析失败原因。八、最佳实践清单与常见误区基于本文档与仓库源码归纳出以下可直接落地的实践要点每次请求都返回完整响应无论使用哪种 SDKassistant 消息都必须完整回传——Anthropic 端保留整个response.content块列表thinking/text/tool_useOpenAI 端保留整个response_message含tool_calls与reasoning_details或think标签。优先使用 Interleaved Thinking 兼容格式reasoning_splitTrue让思考内容独立成字段开发、调试、日志记录都更友好原生格式虽可用但需要手动解析think标签且严禁改动content中的思考内容。工具定义要清晰name、description、参数 schema 与required要无歧义description中给出参数格式示例如The city and state, e.g. San Francisco, US能显著降低tool_confusion风险。执行工具后正确回填结果Anthropic 端用{type: tool_result, tool_use_id: ..., content: ...}且角色为userOpenAI 端用{role: tool, tool_call_id: ..., content: ...}其中tool_call_id必须与模型返回的tool_calls[].id一致。监控 token 与轮次多轮工具调用会累积上下文建议关注usage字段并设置合理的max_tokens本文示例为 4096与最大轮次如max_turns10避免无限循环。善用失败模式检测遇到 Agent 行为异常时优先检查是否出现context_degradation长上下文信息丢失、tool_confusion误用工具或instruction_drift偏离原始指令——这些正是 Interleaved Thinking 思考轨迹最擅长暴露的问题。总结MiniMax-M2.1 的 Interleaved Thinking 将 Agent 的推理从“任务开头的一次性思考”扩展为“每轮工具交互之间的持续反思”这使得长程任务中的目标保持与外部扰动适应成为可能。但要真正发挥其能力工程侧必须做到一件事把模型每一轮返回的思考内容与工具调用完整地写回对话历史。无论是 Anthropic SDK 的response.content块列表还是 OpenAI SDK 兼容格式下的reasoning_details字段、原生格式下的think标签都承载着思维链的连续性。本文档与examples/interleaved-thinking中的 Reasoning Trace Optimizer 一起构成了「正确接入 → 完整保留 → 深度分析 → 自动优化」的完整闭环可作为 Agent 系统上下文工程实践的直接参考。【免费下载链接】Agent-Skills-for-Context-EngineeringA comprehensive collection of Agent Skills for context engineering, multi-agent architectures, and production agent systems. Use when building, optimizing, or debugging agent systems that require effective context management.项目地址: https://gitcode.com/GitHub_Trending/ag/Agent-Skills-for-Context-Engineering创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考