Troubleshooting Kimi K3.1 Pro second‑turn tool_call_id and tool results

Kimi

Learn how to stabilize multi-turn tool calls with Kimi K3.1 Pro by correctly persisting tool_call_id, pairing it one-to-one with tool results, distinguishing normal no-tool turns from duplicate ID errors, and debugging empty or missing tool responses through structured tests.

Published
On this page

Stabilise multi‑turn tool calls by pairing tool_call_id with tool results

Keep the complete assistant message as returned, including reasoning_content and tool_calls.[3] Execute each tool, then return one tool message whose tool_call_id matches its call’s id. Send the saved history and all matching results on the next request. Stop if an ID is missing, duplicated or unmatched.

  1. Send the user message with the tool definitions.
  2. Save the assistant message and its tool_calls unchanged.
  3. Execute each tool and create a tool message with the matching tool_call_id.
  4. Send the complete history, including the assistant message and every tool result, for the model to continue.
javascriptcode
// Example conversation state. The API call and tool implementation are omitted.
const messagesTurn1 = [
  { role: "user", content: "What is the temperature in Paris?" }
];

// Illustrative assistant response. In an actual call, preserve the returned message.
const assistantToolCall = {
  role: "assistant",
  content: null,
  tool_calls: [{
    id: "call_123",
    type: "function",
    function: {
      name: "getWeather",
      arguments: JSON.stringify({ city: "Paris" })
    }
  }]
};

// Your application executes the function and serializes its result.
const toolResult = {
  role: "tool",
  tool_call_id: "call_123",
  content: JSON.stringify({ temperatureC: 18, conditions: "Clear" })
};

// Send this history as the next request's messages, with the tool definitions.
const messagesTurn2 = [...messagesTurn1, assistantToolCall, toolResult];
Keep the call and result paired when continuing the conversation.
  1. Save the assistant message

    Keep each tool_calls[].id and the full message as returned.

  2. Return tool results

    Set each tool result’s tool_call_id to the corresponding call id.

  3. Continue the conversation

    Send the saved assistant message followed by all matching tool results.

Distinguish duplicate tool_call_id errors from empty responses and missing tool calls

SymptomTypical causeInitial debugging focus
Server or client reports an error related to conflicting or duplicated tool_call identifiers in a later turnA call ID may be duplicated, missing, or associated with the wrong result when history is rebuilt.Inspect how prior assistant tool calls and tool results are stored and replayed in messages, ensuring each emitted tool_call identifier is treated as a stable link to its own result instead of being reused for new calls
API response appears completely empty for the second turn (no content, no tool calls, and no visible token usage or payload to parse)A transport error, incomplete response, or client parsing issue can be one cause; inspect the response before assigning a cause.Check HTTP status codes, error bodies, raw response logging, and client parsing to confirm that a full response is actually received and decoded before blaming message history or tool_call handling
Assistant returns a normal-looking reply in the second turn but contains no tool_call entries at allModel chooses to answer directly from context instead of invoking tools, or prompt and tool definitions do not strongly require tool usage for that queryReview system instructions, tool descriptions, and the user question to determine whether a tool call is truly required, and adjust prompting or tool configuration if the application needs the model to prefer tools over direct answers

When a call/result error appears, compare the saved assistant message with the exact history sent on the next request. Check that every call ID has one matching tool result and that no result points to an absent call. For an empty response, inspect the HTTP status, response body and client parsing separately; an empty content field alone may accompany a valid tool call.

When missing tool calls are normal Kimi K3.1 Pro behaviour

An assistant reply without a tool call can be normal: the model may answer from the available context. Inspect finish_reason and the full response structure before deciding that a tool call is missing.

  • A direct answer can be appropriate when existing context or prior tool results suffice.
  • If a workflow requires a tool, make that requirement clear in the tool instructions and enforce it in application logic; instructions alone do not guarantee a call.

Inspect finish_reason, content and tool_calls together. A reply without a new call is different from a transport failure or an invalid call/result pair.

Debug empty responses and missing tool results step by step

  1. Confirm that you actually received a response object from the Kimi K3.1 Pro API. In your client code, check that the call returned without raising an exception and that a response (or equivalent) structure is present. If your environment surfaces transport details such as HTTP status or error payloads, include them in this first pass: a non-success status or explicit error body usually means you are dealing with a transport or quota issue rather than a tool-call or message-history problem.
  2. Inspect the raw response payload for assistant content and usage information before any downstream processing. With an OpenAI-compatible client, Kimi K3.1 Pro responses expose the assistant message as response.choices[0].message and the token accounting under response.usage.[1] Log or print both fields directly (for example, print(message.content) and print(response.usage) in Python) to see whether the model produced text, whether any tokens were consumed, and whether your own serialization or filtering code might be dropping a non-empty reply or hiding tool calls.[1]

Keep the returned assistant message unchanged. Follow it with all tool-result messages, each carrying the matching tool_call_id, before asking the model to continue. For parallel calls, match by ID rather than relying on completion order.

If the issue persists, reproduce it with a single deterministic tool and compare the actual request history with the saved response. Record the request ID, error, model and client version, with sensitive content removed. This helps isolate middleware or serialization changes.

For a timed-out write, check the operation’s status before retrying: the action may have succeeded even though the response was lost. Keep the original model call ID for its result and track execution attempts separately; an ID alone does not make the downstream action idempotent.

Validate Kimi K3.1 Pro’s tool_call_id behaviour where documentation is unclear

The public K3 encoder matches tool results to calls by tool_call_id and can reorder a group of results.[2] This does not guarantee identical handling by every serving platform. The model card separately requires the full assistant message to be passed back.[3]

  • Test two parallel calls with results arriving in reverse order; pair them by ID and assemble the history in call order.
  • In a controlled environment, test missing, duplicate and unmatched IDs; verify your client stops before sending an invalid continuation.
  • After an SDK or service change, repeat the tests and record the model, client version and sanitized errors.

A runnable two-turn request example

This Python 3 example uses only the standard library. Set SMTOKEN_API_KEY before running it; it sends two real requests to SmarToken and may incur charges. get_temperature is a local illustrative tool: 18°C is not live weather. The script stops if the model does not return a tool call.

pythoncode
import json
import os
from urllib.request import Request, urlopen
from urllib.error import HTTPError

base = os.environ.get('SMTOKEN_BASE_URL', 'https://thesmartoken.com/v1').rstrip('/')
key = os.environ['SMTOKEN_API_KEY']
model = 'kimi-k3.1-pro'
tools = [{"type": "function", "function": {
    "name": "get_temperature", "description": "Return a demo temperature for a city.",
    "parameters": {"type": "object", "properties": {"city": {"type": "string"}},
                   "required": ["city"]}}}]
messages = [{"role": "user", "content": "Use get_temperature to look up Paris, then answer."}]

def chat():
    body = json.dumps({"model": model, "messages": messages, "tools": tools,
                       "stream": False}).encode()
    request = Request(base + '/chat/completions', data=body,
                      headers={'Authorization': 'Bearer ' + key, 'Content-Type': 'application/json'})
    try:
        with urlopen(request, timeout=60) as response:
            print('HTTP status:', response.status)
            return json.load(response)['choices'][0]['message']
    except HTTPError as error:
        print('HTTP status:', error.code)
        raise

assistant = chat()
calls = assistant.get('tool_calls') or []
if not calls:
    raise RuntimeError('No tool call returned; inspect the first response before continuing.')
messages.append(assistant)  # Preserve the complete response, including reasoning fields.
seen = set()
for call in calls:
    call_id = call.get('id')
    fn = call.get('function') or {}
    if not call_id or call_id in seen or fn.get('name') != 'get_temperature':
        raise ValueError('Missing/duplicate ID or unexpected tool; stop.')
    seen.add(call_id)
    args = json.loads(fn['arguments'])
    if not isinstance(args, dict) or not isinstance(args.get('city'), str):
        raise ValueError('Invalid city argument.')
    result = {'city': args['city'], 'temperature_c': 18, 'source': 'illustrative'}
    messages.append({'role': 'tool', 'tool_call_id': call_id,
                     'content': json.dumps(result, ensure_ascii=False)})

answer = chat()
print(answer.get('content') or '[No final text; inspect the response]')

On December 1, 2026, we ran one actual two-request exchange with kimi-k3.1-pro and max_tokens set to 400. These excerpts redact the ID as <call_id>; the same placeholder represents the same original ID in both places. The second request included the complete assistant message. The 18°C tool result is a local example, not live weather.

StepActual content, excerpted
First user requestUse get_temperature to look up Paris, then answer.
First assistant responseCalls get_temperature with {"city": "Paris"}; id = <call_id>
Tool resulttool_call_id = <call_id>; {"city":"Paris","temperature_c":18,"source":"illustrative"}
Second assistant responseParis is 18°C (illustrative temperature).

We also reran this script with Python 3.9.6 and a local mock HTTP service; it needs no third-party packages. The mock printed HTTP status: 200 twice and Paris: 18°C (illustrative). Actual status, reply and usage depend on the API response.

A recorded two-turn exchange

The following exchange was recorded on December 1, 2026, using POST https://thesmartoken.com/v1/chat/completions. Response IDs are replaced and reasoning_content is redacted; both occurrences of <call_id> stand for the same original tool-call ID. The credential is not part of the request body. This is a process record, not a copy-and-paste second request: when running the example above, use the original assistant message and ID returned by the API. The 18°C result is a local demonstration value.

First request

jsoncode
{
  "model": "kimi-k3.1-pro",
  "messages": [
    {
      "role": "user",
      "content": "Use get_temperature to look up Paris, then answer."
    }
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_temperature",
        "description": "Return a demo temperature for a city.",
        "parameters": {
          "type": "object",
          "properties": {
            "city": {
              "type": "string"
            }
          },
          "required": [
            "city"
          ]
        }
      }
    }
  ],
  "stream": false,
  "max_tokens": 400
}

First response

jsoncode
{
  "id": "<response_1>",
  "object": "chat.completion",
  "created": 1796107750,
  "model": "kimi-k3.1-pro",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "",
        "reasoning_content": "[redacted]",
        "tool_calls": [
          {
            "function": {
              "arguments": "{\"city\": \"Paris\"}",
              "name": "get_temperature"
            },
            "id": "<call_id>",
            "index": 0,
            "type": "function"
          }
        ]
      },
      "finish_reason": "tool_calls"
    }
  ],
  "usage": {
    "prompt_tokens": 175,
    "completion_tokens": 77,
    "total_tokens": 252
  }
}

Second request

jsoncode
{
  "model": "kimi-k3.1-pro",
  "messages": [
    {
      "role": "user",
      "content": "Use get_temperature to look up Paris, then answer."
    },
    {
      "role": "assistant",
      "content": "",
      "reasoning_content": "[redacted]",
      "tool_calls": [
        {
          "function": {
            "arguments": "{\"city\": \"Paris\"}",
            "name": "get_temperature"
          },
          "id": "<call_id>",
          "index": 0,
          "type": "function"
        }
      ]
    },
    {
      "role": "tool",
      "tool_call_id": "<call_id>",
      "content": "{\"city\": \"Paris\", \"temperature_c\": 18, \"source\": \"illustrative\"}"
    }
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_temperature",
        "description": "Return a demo temperature for a city.",
        "parameters": {
          "type": "object",
          "properties": {
            "city": {
              "type": "string"
            }
          },
          "required": [
            "city"
          ]
        }
      }
    }
  ],
  "stream": false,
  "max_tokens": 400
}

Second response

jsoncode
{
  "id": "<response_2>",
  "object": "chat.completion",
  "created": 1796107755,
  "model": "kimi-k3.1-pro",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Paris is **18°C** (illustrative temperature).",
        "reasoning_content": "[redacted]"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 304,
    "completion_tokens": 57,
    "total_tokens": 361
  }
}

The two receipts reported 175 / 77 and 304 / 57 input / output tokens respectively; these figures describe this run only. The original log did not separately record HTTP status codes, so no specific status is asserted here.

A recorded two-call reverse-order replay

On December 1, 2026, we ran a two-request exchange through SmarToken’s playground with kimi-k3.1-pro, asking separately for Paris and Berlin. The first response returned two get_temperature calls; the application supplied illustrative local temperatures and deliberately returned them in reverse order. Both HTTP responses were 200. The original call IDs are redacted as A and B consistently below.

StageRedacted record
First call Aget_temperature({"city":"Paris"})
First call Bget_temperature({"city":"Berlin"})
First result Btool_call_id=B, Berlin, 22°C (illustrative)
Second result Atool_call_id=A, Paris, 18°C (illustrative)
Second responseParis 18°C; Berlin 22°C, both illustrative

The second response correctly paired Paris with 18°C and Berlin with 22°C and identified the values as illustrative. Input/output usage was 184/230 tokens in the first request and 497/70 in the second; both used max_tokens 400. This is one reverse-order replay, not a test of concurrent tool execution or proof that other providers accept the same ordering.

Sources

  1. SmarToken · Kimi K3.1 Pro
  2. Moonshot · Kimi K3 message encoding
  3. Moonshot · Kimi K3.1 Pro model card