tencent cloud

Kimi API Guide

Download
フォーカスモード
フォントサイズ
最終更新日: 2026-07-20 21:51:55
AI翻訳
The Kimi series of models are compatible with the OpenAI / Anthropic protocols and can be called directly via the OpenAI SDK or standard HTTP APIs. This document provides invocation examples in five programming languages (cURL, Python, Node.js, Java, Go) for common scenarios and explains Kimi's special features, such as its reasoning mode and multimodal capabilities.
Note:
This document uses the TokenHub gateway as an example. All calls are routed through https://tokenhub-intl.tencentcloudmaas.com/v1 and authenticated using a TokenHub-owned API Key.

Supported Models

TokenHub currently supports the following Kimi models (for specifics, refer to the model list):
Model ID
Type
Reasoning Capability
Visual Capability
Video Capability
kimi-k3
General Conversation Model
Thinking only (Cannot be disabled)
Supported
Supported
kimi-k2.7-code-highSpeed
Coding model
Thinking only (Cannot be disabled)
Supported
Supported
kimi-k2.7-code
Coding model
Thinking only (Cannot be disabled)
Supported
Supported
kimi-k2.6
General Conversation Model
Configurable (Enabled by default)
Supported
Supported
kimi-k2.5
General Conversation Model
Configurable (Enabled by default)
Supported
Not supported.
Note:
Kimi K2.6 / K2.5 are both conversation and reasoning models. Unlike other vendors, you do not need to switch model IDs between a standard model and a reasoning model. You can simply control whether to enable the reasoning capability using the thinking parameter. The reasoning mode for kimi-k2.7-code cannot be disabled.

Model Selection Overview

The invocation protocols for different Kimi models are generally compatible with OpenAI Chat Completions. However, parameters for reasoning, output tokens, and multimodal input restrictions are not entirely consistent. It is recommended to first select a model based on your scenario and then apply the corresponding parameter template.
Model
Recommended Scenario
Key Points to Confirm Before Invocation
kimi-k3
Flagship general-purpose capabilities, long-context knowledge work, comprehensive reasoning, and multimodal understanding
Use reasoning_effort. Do not pass the thinking parameter from K2.x. For output parameters, use max_completion_tokens. Public network image URLs are not currently supported.
kimi-k2.7-code / kimi-k2.7-code-highspeed
Long-range code tasks, codebase comprehension, and engineering Agent scenarios; HighSpeed is suitable for interactive Coding scenarios that prioritize response speed.
Only thinking is supported. The sampling parameter is a fixed value. For tool calls, only auto / none is supported. Only Base64 is supported for images.
kimi-k2.6
General conversation, thinking, and multimodal image/video scenarios
Use thinking to control thinking. Retain reasoning_content across multiple rounds. Image URLs and Base64 can be used as supported by the platform.
kimi-k2.5
General conversation, thinking, and image comprehension scenarios
Use thinking to control thinking. Video is not supported. Retain reasoning_content across multiple rounds.

Kimi Model API Differences

The Kimi series of models are generally compatible with the OpenAI Chat Completions protocol, but parameter constraints vary across different models. When integrating, maintain parameter templates according to the specific model ID. Do not reuse a single set of request parameters for all Kimi models.
Writing back
kimi-k3
kimi-k2.7-code / kimi-k2.7-code-highspeed
kimi-k2.6
kimi-k2.5
Model positioning
A flagship general-purpose model, suitable for long-context, knowledge work, comprehensive reasoning, and multimodal understanding
Coding model, suitable for long-range code tasks and engineering Agent; HighSpeed edition is more oriented towards low-latency interaction.
General conversation/thinking model, suitable for general reasoning, dialogue, and multimodal tasks
General conversation/thinking model, suitable for general reasoning, dialogue, and image understanding
Thinking parameters
Use the top-level reasoning_effort parameter. Currently, only "max" is supported, which is also the default value "max".
Only supports thinking. thinking.type defaults to "enabled". Disabling it will cause an error.
Use thinking.type to switch between enabled / disabled.
Use thinking.type to switch between enabled / disabled.
Whether to use thinking
Do not pass the thinking parameter from K2.x.
Use thinking. It is enabled by default and cannot be disabled.
Pass as needed
Pass as needed
Output token parameters
Use the max_completion_tokens parameter. The default value is 131072, and the maximum value is 1048576.
Use max_tokens. The default value is 32768 (32k). Adjust it as needed.
Use max_tokens. A value greater than or equal to 16000 is recommended (shared quota for reasoning + response).
Use max_tokens. A value greater than or equal to 16000 is recommended (shared quota for reasoning + response).
Sampling parameters
temperature=1.0, top_p=0.95, n=1, presence_penalty=0, and frequency_penalty=0 are fixed values. It is recommended not to explicitly pass them.
temperature=1.0, top_p=0.95, n=1, presence_penalty=0, and frequency_penalty=0 are fixed values. Passing other values will cause an error. It is recommended not to pass any of them.
In thinking mode, temperature=1.0; in non-thinking mode, temperature=0.6. top_p / n / penalty terms can be adjusted within a reasonable range.
In thinking mode, temperature=1.0; in non-thinking mode, temperature=0.6. top_p / n / penalty terms can be adjusted within a reasonable range.
Streaming output
Process reasoning_content and content separately.
Process reasoning_content and content separately.
Process reasoning_content and content separately when thinking is enabled.
Process reasoning_content and content separately when thinking is enabled.
Multi-turn rewriting
Add the complete assistant message returned by the API as-is to the next request. Do not retain only the content.
Retain the complete assistant message, especially the reasoning_content and tool call information.
Retain reasoning_content when thinking is enabled; use thinking.keep when long-term retention is required.
Retain reasoning_content when thinking is enabled; use thinking.keep when long-term retention is required.
tool_choice
Supports tool_choice="required" to enforce at least one tool call in the first round. Tool results must be written back according to tool_call_id.
Only supports "auto" (default) / "none". For multi-step tool calls, the assistant's reasoning_content must be retained.
Supports the standard OpenAI Function Calling protocol. Specific capabilities are subject to platform support.
Supports the standard OpenAI Function Calling protocol. Specific capabilities are subject to platform support.
Image input
The content must be an object array. Public network image URLs are not supported. Use Base64 or ms://<file-id>.
Only supports Base64 and does not support direct URL links. The request body for a single request must be less than or equal to 100 MB.
Supports two methods: Base64 and public network direct URL links.
Supports two methods: Base64 and public network direct URL links.
Video Input
Supports video understanding. It is recommended to use ms://<file-id> after file upload or other platform-supported formats.
Supported, subject to platform restrictions.
Supported
Not supported.
Context length
1M tokens. Context caching is automatically enabled for regular requests, requiring no cache ID / TTL.
256K
256K
256K

Key API Usage Scenarios

The following examples cover scenarios that are prone to pitfalls, such as multi-turn writebacks, image inputs, and video inputs. The kimi-k2.6 in the examples has been confirmed as a valid invocation parameter in the TokenHub model list. The current environment is not configured with a TokenHub model invocation API Key, so no real inference request was initiated locally. Actual availability is still determined by account permissions and the console model list.

Multi-Turn Conversation Write-Back reasoning_content

When thinking is enabled, you must write back the reasoning_content and content returned by the previous API call together to the messages; otherwise, the model will lose the reasoning thread in subsequent turns.
cURL
Python
Node.js
Java
Go
curl -X POST 'https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions' \\
-H 'Authorization: Bearer YOUR_API_KEY' \\
-H 'Content-Type: application/json' \\
-d '{
"model": "kimi-k2.6",
"stream": true,
"thinking": {"type": "enabled", "keep": "all"},
"messages": [
{"role": "system", "content": "You are Kimi."},
{"role": "user", "content": "The first question..."},
{
"role": "assistant",
"reasoning_content": "<reasoning_content returned by the previous API call>",
"content": "<content returned by the previous API call>"
},
{"role": "user", "content": "Please continue the deduction based on the previous analysis."}
]
}'
from openai import OpenAI

client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://tokenhub-intl.tencentcloudmaas.com/v1",
)

messages = [
{"role": "system", "content": "You are Kimi."},
{"role": "user", "content": "The first question..."},
{
"role": "assistant",
"reasoning_content": "<reasoning_content returned by the previous API call>",
"content": "<content returned by the previous API call>",
},
{"role": "user", "content": "Please continue the deduction based on the previous analysis."},
]

response = client.chat.completions.create(
model="kimi-k2.6",
messages=messages,
stream=True,
extra_body={"thinking": {"type": "enabled", "keep": "all"}},
)

for chunk in response:
delta = chunk.choices[0].delta
if getattr(delta, "reasoning_content", None):
print(delta.reasoning_content, end="", flush=True)
if delta.content:
print(delta.content, end="", flush=True)
print()
import OpenAI from 'openai';

const client = new OpenAI({
apiKey: 'YOUR_API_KEY',
baseURL: 'https://tokenhub-intl.tencentcloudmaas.com/v1',
});

const messages = [
{ role: 'system', content: 'You are Kimi.' },
{ role: 'user', content: 'The first question...' },
{
role: 'assistant',
reasoning_content: '<reasoning_content returned by the previous API call>',
content: '<content returned by the previous API call>',
},
{ role: 'user', content: 'Please continue the deduction based on the previous analysis.' },
];

const stream = await client.chat.completions.create({
model: 'kimi-k2.6',
messages,
stream: true,
thinking: { type: 'enabled', keep: 'all' },
});

for await (const chunk of stream) {
const delta = chunk.choices?.[0]?.delta;
if (!delta) continue;
if (delta.reasoning_content) process.stdout.write(delta.reasoning_content);
if (delta.content) process.stdout.write(delta.content);
}
console.log();
import okhttp3.*;
import com.google.gson.Gson;
import java.util.*;

public class MultiTurnWithThinking {
public static void main(String[] args) {
Map<String, Object> body = new HashMap<>();
body.put("model", "kimi-k2.6");
body.put("stream", true);
body.put("thinking", Map.of("type", "enabled", "keep", "all"));
body.put("messages", List.of(
Map.of("role", "system", "content", "You are Kimi."),
Map.of("role", "user", "content", "The first question..."),
Map.of(
"role", "assistant",
"reasoning_content", "<reasoning_content returned by the previous API call>",
"content", "<content returned by the previous API call>"
),
Map.of("role", "user", "content", "Please continue the deduction based on the previous analysis.")
));

Request request = new Request.Builder()
.url("https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions")
.header("Authorization", "Bearer YOUR_API_KEY")
.post(RequestBody.create(new Gson().toJson(body), MediaType.parse("application/json")))
.build();

try (Response response = new OkHttpClient().newCall(request).execute();
java.io.BufferedReader r = new java.io.BufferedReader(
new java.io.InputStreamReader(response.body().byteStream()))) {
String line;
while ((line = r.readLine()) != null) {
if (line.startsWith("data: ")) System.out.println(line.substring(6));
}
}
}
}
package main

import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"net/http"
"strings"
)

func main() {
body, _ := json.Marshal(map[string]interface{}{
"model": "kimi-k2.6",
"stream": true,
"thinking": map[string]string{"type": "enabled", "keep": "all"},
"messages": []map[string]interface{}{
{"role": "system", "content": "You are Kimi."},
{"role": "user", "content": "The first question..."},
{
"role": "assistant",
"reasoning_content": "<reasoning_content returned by the previous API call>",
"content": "<content returned by the previous API call>",
},
{"role": "user", "content": "Please continue the deduction based on the previous analysis."},
},
})

req, _ := http.NewRequest("POST",
"https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions",
bytes.NewBuffer(body))
req.Header.Set("Authorization", "Bearer YOUR_API_KEY")
req.Header.Set("Content-Type", "application/json")

resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()

scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "data: ") {
fmt.Println(strings.TrimPrefix(line, "data: "))
}
}
}

Multimodal API Calls

1. Image Input: Base64 Encoding

Suitable for local files / private network image scenarios:
cURL
Python
Node.js
Java
Go
# First, read the image as base64
IMAGE_B64=$(base64 -i image.jpg | tr -d '\\n')

# Use a temporary file to pass the body, avoiding the "Argument list too long" error triggered by an excessively large base64 string.
cat > /tmp/req.json <<EOF
{
"model": "kimi-k2.6",
"messages": [{
"role": "user",
"content": [
{"type": "text", "text": "Please describe this picture."},
{"type": "image_url", "image_url": {"url": "data:image/jpeg;base64,${IMAGE_B64}"}}
]
}]
}
EOF

curl -X POST 'https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions' \\
-H 'Authorization: Bearer YOUR_API_KEY' \\
-H 'Content-Type: application/json' \\
-d @/tmp/req.json
import base64
from openai import OpenAI

client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://tokenhub-intl.tencentcloudmaas.com/v1",
)

with open("image.jpg", "rb") as f:
image_b64 = base64.b64encode(f.read()).decode()

response = client.chat.completions.create(
model="kimi-k2.6",
messages=[{
"role": "user",
"content": [
{"type": "text", "text": "Please describe this picture"},
{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{image_b64}"}},
],
}],
)
print(response.choices[0].message.content)
import fs from 'node:fs';
import OpenAI from 'openai';

const client = new OpenAI({
apiKey: 'YOUR_API_KEY',
baseURL: 'https://tokenhub-intl.tencentcloudmaas.com/v1',
});

const imageB64 = fs.readFileSync('image.jpg').toString('base64');

const response = await client.chat.completions.create({
model: 'kimi-k2.6',
messages: [{
role: 'user',
content: [
{ type: 'text', text: 'Please describe this picture' },
{ type: 'image_url', image_url: { url: `data:image/jpeg;base64,${imageB64}` } },
],
}],
});
console.log(response.choices[0].message.content);
import okhttp3.*;
import com.google.gson.Gson;
import java.nio.file.*;
import java.util.*;

public class ImageBase64Chat {
public static void main(String[] args) throws Exception {
byte[] bytes = Files.readAllBytes(Paths.get("image.jpg"));
String imageB64 = Base64.getEncoder().encodeToString(bytes);

Map<String, Object> body = new HashMap<>();
body.put("model", "kimi-k2.6");
body.put("messages", List.of(Map.of(
"role", "user",
"content", List.of(
Map.of("type", "text", "text", "Please describe this picture"),
Map.of("type", "image_url", "image_url", Map.of(
"url", "data:image/jpeg;base64," + imageB64
))
)
)));

Request request = new Request.Builder()
.url("https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions")
.header("Authorization", "Bearer YOUR_API_KEY")
.post(RequestBody.create(new Gson().toJson(body), MediaType.parse("application/json")))
.build();

try (Response response = new OkHttpClient().newCall(request).execute()) {
System.out.println(response.body().string());
}
}
}
package main

import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)

func main() {
img, _ := os.ReadFile("image.jpg")
imageB64 := base64.StdEncoding.EncodeToString(img)

body, _ := json.Marshal(map[string]interface{}{
"model": "kimi-k2.6",
"messages": []map[string]interface{}{
{
"role": "user",
"content": []map[string]interface{}{
{"type": "text", "text": "Please describe this picture"},
{
"type": "image_url",
"image_url": map[string]string{
"url": "data:image/jpeg;base64," + imageB64,
},
},
},
},
},
})

req, _ := http.NewRequest("POST",
"https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions",
bytes.NewBuffer(body))
req.Header.Set("Authorization", "Bearer YOUR_API_KEY")
req.Header.Set("Content-Type", "application/json")

resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()

data, _ := io.ReadAll(resp.Body)
fmt.Println(string(data))
}

2. Image Input: Public Network Direct URL Link (Only for Models Supporting URLs)

This method is suitable for images already hosted on a CDN / COS, significantly reducing the request size. However, public network URLs are not supported by all Kimi models. For example, the K3 model officially restricts the use of public network image URLs, requiring you to use Base64 or ms://<file-id> instead.
cURL
Python
Node.js
Java
Go
curl -X POST 'https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions' \\
-H 'Authorization: Bearer YOUR_API_KEY' \\
-H 'Content-Type: application/json' \\
-d '{
"model": "kimi-k2.6",
"messages": [{
"role": "user",
"content": [
{"type": "text", "text": "Please describe this picture"},
{"type": "image_url", "image_url": {"url": "https://www.gstatic.com/webp/gallery/1.jpg"}}
]
}]
}'
from openai import OpenAI

client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://tokenhub-intl.tencentcloudmaas.com/v1",
)

response = client.chat.completions.create(
model="kimi-k2.6",
messages=[{
"role": "user",
"content": [
{"type": "text", "text": "Please describe this picture"},
{"type": "image_url", "image_url": {"url": "https://www.gstatic.com/webp/gallery/1.jpg"}},
],
}],
)
print(response.choices[0].message.content)
import OpenAI from 'openai';

const client = new OpenAI({
apiKey: 'YOUR_API_KEY',
baseURL: 'https://tokenhub-intl.tencentcloudmaas.com/v1',
});

const response = await client.chat.completions.create({
model: 'kimi-k2.6',
messages: [{
role: 'user',
content: [
{ type: 'text', text: 'Please describe this picture' },
{ type: 'image_url', image_url: { url: 'https://www.gstatic.com/webp/gallery/1.jpg' } },
],
}],
});
console.log(response.choices[0].message.content);
import okhttp3.*;
import com.google.gson.Gson;
import java.util.*;

public class ImageUrlChat {
public static void main(String[] args) throws Exception {
Map<String, Object> body = new HashMap<>();
body.put("model", "kimi-k2.6");
body.put("messages", List.of(Map.of(
"role", "user",
"content", List.of(
Map.of("type", "text", "text", "Please describe this picture"),
Map.of("type", "image_url", "image_url", Map.of("url", "https://www.gstatic.com/webp/gallery/1.jpg"))
)
)));

Request request = new Request.Builder()
.url("https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions")
.header("Authorization", "Bearer YOUR_API_KEY")
.post(RequestBody.create(new Gson().toJson(body), MediaType.parse("application/json")))
.build();

try (Response response = new OkHttpClient().newCall(request).execute()) {
System.out.println(response.body().string());
}
}
}
package main

import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)

func main() {
body, _ := json.Marshal(map[string]interface{}{
"model": "kimi-k2.6",
"messages": []map[string]interface{}{
{
"role": "user",
"content": []map[string]interface{}{
{"type": "text", "text": "Please describe this picture"},
{
"type": "image_url",
"image_url": map[string]string{"url": "https://www.gstatic.com/webp/gallery/1.jpg"},
},
},
},
},
})

req, _ := http.NewRequest("POST",
"https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions",
bytes.NewBuffer(body))
req.Header.Set("Authorization", "Bearer YOUR_API_KEY")
req.Header.Set("Content-Type", "application/json")

resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()

data, _ := io.ReadAll(resp.Body)
fmt.Println(string(data))
}
Note:
When using a direct URL link, ensure that the URL is accessible via a public network and requires no authentication. For images on a private network or URLs with signature verification, you must first download and then upload them in Base64 format.

3. Video Input (Use According to Model Support)

Video input is similar to image input, but the supported scope varies across different Kimi models: K3, K2.7 Code, and K2.6 can utilize video input based on platform capabilities, while K2.5 does not support video. Before use, refer to the TokenHub model list and current model restrictions.
cURL
Python
Node.js
Java
Go
# First, read the video as base64
VIDEO_B64=$(base64 -i demo.mp4 | tr -d '\\n')

# Use a temporary file to pass the body, avoiding the "Argument list too long" error triggered by an excessively large base64 string.
cat > /tmp/req.json <<EOF
{
"model": "kimi-k2.6",
"messages": [{
"role": "user",
"content": [
{"type": "text", "text": "Please summarize the video content"},
{"type": "video_url", "video_url": {"url": "data:video/mp4;base64,${VIDEO_B64}"}}
]
}]
}
EOF

curl -X POST 'https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions' \\
-H 'Authorization: Bearer YOUR_API_KEY' \\
-H 'Content-Type: application/json' \\
-d @/tmp/req.json
import base64
from openai import OpenAI

client = OpenAI(
api_key="YOUR_API_KEY",
base_url="https://tokenhub-intl.tencentcloudmaas.com/v1",
)

with open("demo.mp4", "rb") as f:
video_b64 = base64.b64encode(f.read()).decode()

response = client.chat.completions.create(
model="kimi-k2.6",
messages=[{
"role": "user",
"content": [
{"type": "text", "text": "Please summarize the video content"},
{"type": "video_url", "video_url": {"url": f"data:video/mp4;base64,{video_b64}"}},
],
}],
)
print(response.choices[0].message.content)
import fs from 'node:fs';
import OpenAI from 'openai';

const client = new OpenAI({
apiKey: 'YOUR_API_KEY',
baseURL: 'https://tokenhub-intl.tencentcloudmaas.com/v1',
});

const videoB64 = fs.readFileSync('demo.mp4').toString('base64');

const response = await client.chat.completions.create({
model: 'kimi-k2.6',
messages: [{
role: 'user',
content: [
{ type: 'text', text: 'Please summarize the video content' },
{ type: 'video_url', video_url: { url: `data:video/mp4;base64,${videoB64}` } },
],
}],
});
console.log(response.choices[0].message.content);
import okhttp3.*;
import com.google.gson.Gson;
import java.nio.file.*;
import java.util.*;

public class VideoChat {
public static void main(String[] args) throws Exception {
byte[] bytes = Files.readAllBytes(Paths.get("demo.mp4"));
String videoB64 = Base64.getEncoder().encodeToString(bytes);

Map<String, Object> body = new HashMap<>();
body.put("model", "kimi-k2.6");
body.put("messages", List.of(Map.of(
"role", "user",
"content", List.of(
Map.of("type", "text", "text", "Please summarize the video content"),
Map.of("type", "video_url", "video_url", Map.of(
"url", "data:video/mp4;base64," + videoB64
))
)
)));

Request request = new Request.Builder()
.url("https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions")
.header("Authorization", "Bearer YOUR_API_KEY")
.post(RequestBody.create(new Gson().toJson(body), MediaType.parse("application/json")))
.build();

try (Response response = new OkHttpClient().newCall(request).execute()) {
System.out.println(response.body().string());
}
}
}
package main

import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)

func main() {
video, _ := os.ReadFile("demo.mp4")
videoB64 := base64.StdEncoding.EncodeToString(video)

body, _ := json.Marshal(map[string]interface{}{
"model": "kimi-k2.6",
"messages": []map[string]interface{}{
{
"role": "user",
"content": []map[string]interface{}{
{"type": "text", "text": "Please summarize the video content"},
{
"type": "video_url",
"video_url": map[string]string{
"url": "data:video/mp4;base64," + videoB64,
},
},
},
},
},
})

req, _ := http.NewRequest("POST",
"https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions",
bytes.NewBuffer(body))
req.Header.Set("Authorization", "Bearer YOUR_API_KEY")
req.Header.Set("Content-Type", "application/json")

resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()

data, _ := io.ReadAll(resp.Body)
fmt.Println(string(data))
}
Note:
The request body size for a single request is limited by the platform (typically within 100MB). For excessively large videos, compress them or extract key segments before uploading.

Kimi Thinking Mode

The reasoning capability of the Kimi model series is categorized into two sets of parameters by model: kimi-k3 uses reasoning_effort, while the K2.x series uses thinking. Both return reasoning deltas / reasoning content in responses, but the request parameters cannot be mixed.

1. K3: reasoning_effort Parameter

kimi-k3 always has the reasoning mode enabled, with the reasoning intensity configured via the top-level reasoning_effort parameter. Currently, only the "max" level is supported, and it is the default setting "max".
{
"model": "kimi-k3",
"reasoning_effort": "max",
"messages": [
{"role": "user", "content": "Prove that the square root of 2 is an irrational number."}
]
}
Note:
When calling kimi-k3, do not pass the K2.x thinking parameter. For multi-turn conversations and tool calls, you must include the complete assistant message returned by the API as-is in the next request, rather than retaining only the content.

2. K2.x: thinking Parameter

The thinking field for K2.6 / K2.5 / K2.7 Code is located at the top level of the request body, with the following structure:
"thinking": {
"type": "enabled",
"keep": "all"
}
Field
Type
Default Value
Value
Description
type
string
"enabled"
"enabled" / "disabled"
Whether thinking capability is enabled for the current request.
keep
string | null
null
"all" / not passed
Whether to pass through historical reasoning_content in multi-turn conversations.
Note:
thinking is not a standard OpenAI field and is applicable only to the K2.x series. When using the official SDK, you must pass it through extra_body (Python) or directly expand it to the top level (Node.js). For direct HTTP calls, place it at the top level of the request body.

3. reasoning_content Field

After thinking is enabled, a reasoning_content field, which is at the same level as content, is added to the response message to carry the model's reasoning process:
{
"choices": [{
"message": {
"role": "assistant",
"reasoning_content": "First, we need to analyze...",
"content": "The final answer is ..."
}
}]
}

OpenAI SDK Access Restrictions (Important)

The ChatCompletionMessage / ChoiceDelta types in the official OpenAI SDK do not directly declare the reasoning_content attribute. Therefore, you cannot directly access it via obj.reasoning_content and must use the following method:
# ❌ Error
content = message.reasoning_content

# ✅ Correct
if hasattr(message, "reasoning_content"):
content = getattr(message, "reasoning_content")
If you call the API directly via HTTP or parse the JSON using a general-purpose framework like requests/httpx, this restriction does not apply, and you can directly read the sibling field.

4. Streaming Thought Output

When thinking is enabled, it is strongly recommended to use streaming calls (stream: true):
Avoid timeouts: The reasoning content can be lengthy, leading to a longer overall response time. Non-streaming calls can easily cause service timeouts.
Clear order: In streaming mode, the reasoning_content is always fully output before the content, allowing the UI to distinguish between the thinking and answering states.
cURL
Python
Node.js
Java
Go
curl -X POST 'https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions' \\
-H 'Authorization: Bearer YOUR_API_KEY' \\
-H 'Content-Type: application/json' \\
-d '{
"model": "kimi-k2.6",
"max_tokens": 32768,
"stream": true,
"thinking": {"type": "enabled"},
"messages": [
{"role": "user", "content": "Explain the Fourier transform in one sentence."}
]
}'
# The response is an SSE stream: each `data:` line contains a chunk,
# delta.reasoning_content always appears before delta.content
from openai import OpenAI

client = OpenAI(
api_key="YOUR_API_KEY",
base_url="tokenhub-intl.tencentcloudmaas.com/v1",
)

stream = client.chat.completions.create(
model="kimi-k2.6",
messages=[{"role": "user", "content": "Explain the Fourier transform in one sentence."}],
max_tokens=32768,
stream=True,
extra_body={"thinking": {"type": "enabled"}},
)

thinking = False
for chunk in stream:
if not chunk.choices:
continue
delta = chunk.choices[0].delta
# Thinking Phase
if hasattr(delta, "reasoning_content") and getattr(delta, "reasoning_content"):
if not thinking:
print("=== Start Thinking ===")
thinking = True
print(getattr(delta, "reasoning_content"), end="", flush=True)
# Answering Phase
if delta.content:
if thinking:
print("\\n=== Thinking Completed ===")
thinking = False
print(delta.content, end="", flush=True)
import OpenAI from 'openai';

const client = new OpenAI({
apiKey: 'YOUR_API_KEY',
baseURL: 'https://tokenhub-intl.tencentcloudmaas.com/v1',
});

// The Node.js SDK does not natively support the thinking / extra_body fields, so you can directly expand them to the top level.
// Note: If using TypeScript, append `as any` after the last object to bypass type checking.
const stream = await client.chat.completions.create({
model: 'kimi-k2.6',
messages: [{ role: 'user', content: 'Explain the Fourier transform in one sentence.' }],
max_tokens: 32768,
stream: true,
thinking: { type: 'enabled' },
});

let thinking = false;
for await (const chunk of stream) {
const delta = chunk.choices?.[0]?.delta;
if (!delta) continue;
if (delta.reasoning_content) {
if (!thinking) { console.log('=== Start Thinking ==='); thinking = true; }
process.stdout.write(delta.reasoning_content);
}
if (delta.content) {
if (thinking) { console.log('\\n=== Thinking Completed ==='); thinking = false; }
process.stdout.write(delta.content);
}
}
import okhttp3.*;
import okhttp3.sse.*;
import com.google.gson.*;
import java.util.*;

public class ThinkingStream {
public static void main(String[] args) {
Map<String, Object> body = new HashMap<>();
body.put("model", "kimi-k2.6");
body.put("max_tokens", 32768);
body.put("stream", true);
body.put("thinking", Map.of("type", "enabled"));
body.put("messages", List.of(
Map.of("role", "user", "content", "Explain the Fourier transform in one sentence.")
));

Request request = new Request.Builder()
.url("https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions")
.header("Authorization", "Bearer YOUR_API_KEY")
.header("Content-Type", "application/json")
.post(RequestBody.create(new Gson().toJson(body), MediaType.parse("application/json")))
.build();

EventSources.createFactory(new OkHttpClient()).newEventSource(request,
new EventSourceListener() {
@Override public void onEvent(EventSource es, String id, String type, String data) {
if ("[DONE]".equals(data)) return;
JsonObject delta = JsonParser.parseString(data).getAsJsonObject()
.getAsJsonArray("choices").get(0).getAsJsonObject()
.getAsJsonObject("delta");
if (delta.has("reasoning_content")) {
System.out.print(delta.get("reasoning_content").getAsString());
}
if (delta.has("content") && !delta.get("content").isJsonNull()) {
System.out.print(delta.get("content").getAsString());
}
}
});
}
}
package main

import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"net/http"
"strings"
)

func main() {
body, _ := json.Marshal(map[string]interface{}{
"model": "kimi-k2.6",
"max_tokens": 32768,
"stream": true,
"thinking": map[string]string{"type": "enabled"},
"messages": []map[string]string{
{"role": "user", "content": "Explain the Fourier transform in one sentence."},
},
})

req, _ := http.NewRequest("POST",
"https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions",
bytes.NewBuffer(body))
req.Header.Set("Authorization", "Bearer YOUR_API_KEY")
req.Header.Set("Content-Type", "application/json")

resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()

scanner := bufio.NewScanner(resp.Body)
thinking := false
for scanner.Scan() {
line := scanner.Text()
if !strings.HasPrefix(line, "data: ") {
continue
}
data := strings.TrimPrefix(line, "data: ")
if data == "[DONE]" {
break
}
var chunk map[string]interface{}
if err := json.Unmarshal([]byte(data), &chunk); err != nil {
continue
}
choices, _ := chunk["choices"].([]interface{})
if len(choices) == 0 {
continue
}
delta, _ := choices[0].(map[string]interface{})["delta"].(map[string]interface{})
if rc, ok := delta["reasoning_content"].(string); ok && rc != "" {
if !thinking {
fmt.Println("=== Start Thinking ===")
thinking = true
}
fmt.Print(rc)
}
if c, ok := delta["content"].(string); ok && c != "" {
if thinking {
fmt.Println("\\n=== Thinking Completed ===")
thinking = false
}
fmt.Print(c)
}
}
}

5. Preserved Thinking (Multi-turn Preserved Thinking, K2.x Only)

thinking.keep controls whether the historical turns' reasoning_content participates in the next round of reasoning:
Value
Meaning
Use Cases
Not passed / null (default)
The reasoning content from historical rounds is not passed through, resulting in a shorter context and lower cost.
General multi-turn conversation
"all"
Retains the reasoning process from historical rounds in full, enabling the model to continue its previous line of thought.
Complex multi-step reasoning, Agent tool calling, long-range code tasks
Note:
keep only affects whether the historical thinking is passed to the model, and does not affect whether the current turn generates thinking. It is recommended to use it in conjunction with type: "enabled" in scenarios requiring continuous reasoning.


ヘルプとサポート

この記事はお役に立ちましたか?

フィードバック