跳转到主要内容

参数说明

更多参数说明参考 文本合成 API

请求参数说明

  • tools: 定义可调用的函数列表,包含函数名、描述和参数规范

响应参数说明

函数调用响应中的关键字段:
  • tool_calls: 包含模型决定调用的函数信息
  • function.name: 被调用的函数名称
  • function.arguments: 函数调用参数(JSON 格式字符串)
  • id: 工具调用的唯一标识符

特别注意

在多轮 Function Call 对话中,必须将完整的模型返回(即 assistant 消息)添加到对话历史,以保持思维链的连续性: OpenAI SDK:
  • 将完整的 response_message 对象(包含 tool_calls 字段)添加到消息历史
  • OpenAI API 的 MiniMax-M2 模型 content 字段会包含 <think> 标签内容,需要完整保留
Anthropic SDK:
  • 将完整的 response.content(包含 thinking/text/tool_use 等所有块)添加到消息历史
  • response.content 是一个列表,包含多种类型的内容块,必须完整回传

请求示例

OpenAI SDK

from openai import OpenAI
import json

# 初始化客户端
client = OpenAI(
    api_key="<api-key>",
    base_url="https://api.minimaxi.com/v1",
)

# 定义工具:天气查询
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):
    """发送消息并返回响应"""
    response = client.chat.completions.create(
        model="MiniMax-M2",
        messages=messages,
        tools=tools
    )
    return response.choices[0].message

# 1. 用户提问
messages = [{"role": "user", "content": "How's the weather in San Francisco?"}]
print(f"👤 User>\t {messages[0]['content']}")

# 2. 模型返回工具调用
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. 执行工具并返回结果
    messages.append(response_message)
    messages.append({
        "role": "tool",
        "tool_call_id": tool_call.id,
        "content": "24℃, sunny"  # 实际应用中这里应该调用真实的天气API
    })

    # 4. 获取最终回复
    final_message = send_messages(messages)
    print(f"💬 Model>\t {final_message.content}")
else:
    print(f"💬 Model>\t {response_message.content}")
代码输出结果如下:
👤 User>         How's the weather in San Francisco?
💬 Model>        <think>
Alright, the user is asking about the weather in San Francisco. This is a straightforward request that requires me to provide weather information.

Looking at the tools available to me, I see I have access to a "get_weather" tool that can retrieve weather information for a specific location. This is exactly what I need for this query.

The tool requires a "location" parameter, which should be the city and state (or in this case, city and country). The user has asked about "San Francisco" which is a major city in US. To use the tool properly, I should format the location as "San Francisco, US" to be specific and ensure I get the correct weather data.

I could try to guess or provide general information about San Francisco's climate, but that would be unreliable and potentially inaccurate. The best approach is to use the provided tool to get the current, accurate weather information.

So I'll need to make a tool call to "get_weather" with the argument "location" set to "San Francisco, US". This will retrieve the current weather conditions for San Francisco, which is exactly what the user is asking for.

Once I get the weather data back from the tool, I'll be able to provide the user with accurate information about the current weather conditions in San Francisco. But first, I need to make the tool call.
</think>

🔧 Tool>         get_weather(San Francisco, US)
💬 Model>        <think>
I've just called the get_weather tool to check the current weather conditions in San Francisco, and I've received the response. Let me analyze what I got back.

The tool returned "24℃, sunny" which is a simple but clear weather description. It tells me two important pieces of information:
1. The temperature is 24 degrees Celsius (which is a comfortable temperature, about 75°F)
2. The weather condition is sunny, which means clear skies and good visibility

This is exactly the information the user was asking for when they inquired "How's the weather in San Francisco?" They wanted to know the current conditions, and now I have that data.

I should format this information in a clear, concise way for the user. Since the data is straightforward, I don't need to elaborate with additional details about humidity, wind, or other metrics. A simple, direct response that answers their question is best.

I'll mention both the temperature and the sunny conditions to give them a complete picture of the weather. I don't need to add any caveats or additional information since the data is clear and specific.

My response should be brief but informative, giving them exactly what they asked for in a friendly manner. I'll just state the temperature and weather condition clearly.
</think>
The weather in San Francisco is currently 24 and sunny.

Anthropic SDK

import anthropic
import json

# 初始化客户端
client = anthropic.Anthropic(
    base_url="https://api.minimaxi.com/anthropic",
    api_key="<your api key>"  # 替换为你的 MiniMax API Key
)

# 定义工具:天气查询
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",
        "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 = []

    # 遍历所有内容块
    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_ascii=False)})")

    return thinking_blocks, text_blocks, tool_use_blocks

# 1. 用户提问
messages = [{"role": "user", "content": "How's the weather in San Francisco?"}]
print(f"\n👤 User>\t {messages[0]['content']}")

# 2. 模型返回第一轮响应(可能包含工具调用)
response = send_messages(messages)
thinking_blocks, text_blocks, tool_use_blocks = process_response(response)

# 3. 如果有工具调用,执行工具并继续对话
if tool_use_blocks:
    # ⚠️ 关键:将助手的完整响应回传到消息历史
    # response.content 包含所有块的列表:[thinking块, text块, tool_use块]
    # 必须完整回传,否则后续对话会丢失上下文信息
    messages.append({
        "role": "assistant",
        "content": response.content
    })

    # 执行工具并返回结果(这里模拟天气API调用)
    print(f"\n🔨 执行工具: {tool_use_blocks[0].name}")
    tool_result = "24℃, sunny"
    print(f"📊 工具返回: {tool_result}")

    # 添加工具执行结果
    messages.append({
        "role": "user",
        "content": [
            {
                "type": "tool_result",
                "tool_use_id": tool_use_blocks[0].id,
                "content": tool_result
            }
        ]
    })

    # 4. 获取最终回复
    final_response = send_messages(messages)
    process_response(final_response)
代码输出结果如下:
👤 User>         How's 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.

Looking at my available tools, I see I have a `get_weather` function that can provide weather information for a location. This is exactly what I need to answer the user's question. The function requires a "location" parameter, which should be a string containing the city and potentially the state/country.

In this case, the user has clearly specified San Francisco as the location. San Francisco is a major city in US, so I don't need to include the country code - just "San Francisco" should be sufficient for the weather service to identify the correct location.

The required parameters for the get_weather tool are:
- location: "San Francisco"

I should call this tool to retrieve the current weather information for San Francisco before I can provide a meaningful answer to the user. Once I get the weather data back from the tool, I'll be able to share details like temperature, conditions (sunny, cloudy, rainy, etc.), and possibly other relevant information like humidity or wind speed.

So I'll make a tool call to get_weather with the location parameter set to "San Francisco". After I receive the response from this tool call, I'll be able to provide the user with the current weather information they requested.

🔧 Tool>        get_weather({"location": "San Francisco"})

🔨 执行工具: get_weather
📊 工具返回: 24, sunny
💭 Thinking>
I've just called the get_weather tool to check the current conditions in San Francisco as the user requested. Let me analyze what information I received back.

The tool returned a simple response: "24℃, sunny". This is quite straightforward - it tells me the current temperature is 24 degrees Celsius and the weather conditions are sunny. This is exactly the basic weather information the user was asking about.

The temperature is given in Celsius (24℃), which is appropriate since US uses the metric system. I could convert this to Fahrenheit for users who might be more familiar with that scale, but since the user didn't specify a preference, I'll stick with the metric measurement as provided by the tool.

For the weather condition, I received "sunny" which indicates clear skies and good visibility. This is useful information that tells the user they can expect good weather if they're planning to be outside.

I don't have additional details like humidity, wind speed, or UV index from the tool response. If the user wants more detailed information, they could ask a follow-up question, and I might need to provide general advice about sunny weather conditions or suggest checking a more detailed weather service.

Now I need to formulate a clear, concise response to the user that directly answers their question about the weather in San Francisco. I'll keep it simple and factual, stating the temperature and conditions clearly. I should also add a friendly closing to invite further questions if needed.

The most straightforward way to present this information is to state the temperature first, followed by the conditions, and then add a friendly note inviting the user to ask for more information if they want it.

💬 Model>       The current weather in San Francisco is 24 and sunny.

推荐阅读

I