GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • 快来体验吧!
  • Kimi API 开放平台 home page
  • 模型推理
  • 托管智能体
  • API 参考
  • 模型与定价
  • 企业订阅
  • 联系销售
  • 用户中心
  • 模型参数参考
  • 错误码说明
  • POSTChat Completions API
  • POSTResponses API
  • POSTMessages API

This view

  • Original page
  • New address

GeezerVison is showing platform.kimi.com — Chat Completions API - Kimi API 开放平台

POST
/
v1
/
chat
/
completions
创建聊天补全
curl --request POST \
  --url https://api.moonshot.cn/v1/chat/completions \
  --header 'Authorization: Bearer <token>' \
  --header 'Content-Type: application/json' \
  --data '
{
  "messages": [
    {
      "role": "user",
      "content": "你好",
      "name": null,
      "partial": false
    }
  ],
  "model": "kimi-k3.1-pro",
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "<string>",
        "parameters": {},
        "description": "<string>",
        "strict": true
      }
    }
  ]
}
'
import requests

url = "https://api.moonshot.cn/v1/chat/completions"

payload = {
    "messages": [
        {
            "role": "user",
            "content": "你好",
            "name": None,
            "partial": False
        }
    ],
    "model": "kimi-k3.1-pro",
    "tools": [
        {
            "type": "function",
            "function": {
                "name": "<string>",
                "parameters": {},
                "description": "<string>",
                "strict": True
            }
        }
    ]
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.text)
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: JSON.stringify({
    messages: [{role: 'user', content: '你好', name: null, partial: false}],
    model: 'kimi-k3.1-pro',
    tools: [
      {
        type: 'function',
        function: {name: '<string>', parameters: {}, description: '<string>', strict: true}
      }
    ]
  })
};

fetch('https://api.moonshot.cn/v1/chat/completions', options)
  .then(res => res.json())
  .then(res => console.log(res))
  .catch(err => console.error(err));
<?php

$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "https://api.moonshot.cn/v1/chat/completions",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => json_encode([
    'messages' => [
        [
                'role' => 'user',
                'content' => '你好',
                'name' => null,
                'partial' => false
        ]
    ],
    'model' => 'kimi-k3.1-pro',
    'tools' => [
        [
                'type' => 'function',
                'function' => [
                                'name' => '<string>',
                                'parameters' => [
                                                                
                                ],
                                'description' => '<string>',
                                'strict' => true
                ]
        ]
    ]
  ]),
  CURLOPT_HTTPHEADER => [
    "Authorization: Bearer <token>",
    "Content-Type: application/json"
  ],
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.moonshot.cn/v1/chat/completions"

	payload := strings.NewReader("{\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"你好\",\n      \"name\": null,\n      \"partial\": false\n    }\n  ],\n  \"model\": \"kimi-k3.1-pro\",\n  \"tools\": [\n    {\n      \"type\": \"function\",\n      \"function\": {\n        \"name\": \"<string>\",\n        \"parameters\": {},\n        \"description\": \"<string>\",\n        \"strict\": true\n      }\n    }\n  ]\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(string(body))

}
HttpResponse<String> response = Unirest.post("https://api.moonshot.cn/v1/chat/completions")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"你好\",\n      \"name\": null,\n      \"partial\": false\n    }\n  ],\n  \"model\": \"kimi-k3.1-pro\",\n  \"tools\": [\n    {\n      \"type\": \"function\",\n      \"function\": {\n        \"name\": \"<string>\",\n        \"parameters\": {},\n        \"description\": \"<string>\",\n        \"strict\": true\n      }\n    }\n  ]\n}")
  .asString();
require 'uri'
require 'net/http'

url = URI("https://api.moonshot.cn/v1/chat/completions")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"你好\",\n      \"name\": null,\n      \"partial\": false\n    }\n  ],\n  \"model\": \"kimi-k3.1-pro\",\n  \"tools\": [\n    {\n      \"type\": \"function\",\n      \"function\": {\n        \"name\": \"<string>\",\n        \"parameters\": {},\n        \"description\": \"<string>\",\n        \"strict\": true\n      }\n    }\n  ]\n}"

response = http.request(request)
puts response.read_body
{
  "id": "<string>",
  "object": "chat.completion",
  "created": 123,
  "model": "<string>",
  "choices": [
    {
      "index": 123,
      "message": {
        "role": "assistant",
        "content": "<string>",
        "tool_calls": [
          {
            "id": "<string>",
            "type": "function",
            "function": {
              "name": "<string>",
              "arguments": "<string>"
            }
          }
        ],
        "reasoning_content": "<string>"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 123,
    "completion_tokens": 123,
    "total_tokens": 123,
    "cached_tokens": 123,
    "prompt_tokens_details": {
      "cached_tokens": 123,
      "cache_write_tokens": 123
    }
  }
}
{
  "error": {
    "message": "<string>",
    "type": "<string>",
    "code": "<string>"
  }
}
{
  "error": {
    "message": "<string>",
    "type": "<string>",
    "code": "<string>"
  }
}
{
  "error": {
    "message": "<string>",
    "type": "<string>",
    "code": "<string>"
  }
}
创建一个对话补全请求,模型将根据输入的消息列表生成回复。

Content 字段说明

content 字段支持以下两种形式:纯文本字符串
{ "content": "你好" }
对象数组(用于多模态输入)数组中每个元素通过 type 字段区分类型:
{
    "content": [
        { "type": "text", "text": "描述这张图片" },
        { "type": "image_url", "image_url": { "url": "data:image/png;base64,..." } },
        { "type": "video_url", "video_url": { "url": "data:video/mp4;base64,..." } }
    ]
}
其中 image_url 和 video_url 也支持直接传入字符串,效果等同于对象形式中的 url 字段:
{ "type": "image_url", "image_url": "data:image/png;base64,..." }

参数说明

数组中每个元素的字段说明如下:
参数名称是否必须说明类型
typerequired内容类型"text" | "image_url" | "video_url"
text当 type=text 时必填文本内容string
image_url当 type=image_url 时必填用于传输图片,支持对象形式 {"url": "..."} 或直接传入 URL 字符串object | string
video_url当 type=video_url 时必填用于传输视频,支持对象形式 {"url": "..."} 或直接传入 URL 字符串object | string
当 image_url 传入对象时,其字段说明如下:
参数名称是否必须说明类型
urlrequired使用 base64 编码或通过 file id 指定的图片内容string
当 video_url 传入对象时,其字段说明如下:
参数名称是否必须说明类型
urlrequired使用 base64 编码或通过 file id 指定的视频内容,例如 data:video/mp4;base64,...string
无论使用对象形式(url 字段)还是字符串简写,均支持以下两种格式:
  • base64 编码:data:image/png;base64,... 或 data:video/mp4;base64,...
  • 文件引用:ms://<file_id>
详见使用 Kimi 视觉模型。

调用示例

import os
import base64

from openai import OpenAI
from openai.types.chat import ChatCompletion

client: OpenAI = OpenAI(
    api_key=os.environ.get("MOONSHOT_API_KEY"),
    base_url="https://api.moonshot.cn/v1",
)

# 对图片进行 base64 编码
with open("您的图片地址", "rb") as f:
    img_base: str = base64.b64encode(f.read()).decode("utf-8")

response: ChatCompletion = client.chat.completions.create(
    model="kimi-k3.1-pro",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {
                        "url": f"data:image/jpeg;base64,{img_base}",
                    },
                },
                {
                    "type": "text",
                    "text": "请描述这个图片",
                },
            ],
        }
    ],
)
print(response.choices[0].message.content)
curl https://api.moonshot.cn/v1/chat/completions \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $MOONSHOT_API_KEY" \
    -d '{
        "model": "kimi-k3.1-pro",
        "messages": [
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": "data:image/jpeg;base64,/9j/4AAQ..."
                        }
                    },
                    {
                        "type": "text",
                        "text": "请描述这个图片"
                    }
                ]
            }
        ]
    }'
const fs = require("fs");
const OpenAI = require("openai");

const client = new OpenAI({
    apiKey: process.env.MOONSHOT_API_KEY,
    baseURL: "https://api.moonshot.cn/v1",
});

async function main() {
    // 对图片进行 base64 编码
    const imgBase = fs.readFileSync("您的图片地址").toString("base64");

    const response = await client.chat.completions.create({
        model: "kimi-k3.1-pro",
        messages: [
            {
                role: "user",
                content: [
                    {
                        type: "image_url",
                        image_url: {
                            url: `data:image/jpeg;base64,${imgBase}`,
                        },
                    },
                    {
                        type: "text",
                        text: "请描述这个图片",
                    },
                ],
            },
        ],
    });
    console.log(response.choices[0].message.content);
}

main();

响应格式

非流式响应

{
    "id": "chatcmpl-6adb0d416a4a9c1d0fe639e3",
    "object": "chat.completion",
    "created": 1792740676,
    "model": "kimi-k3.1-pro",
    "choices": [
        {
            "index": 0,
            "message": {
                "content": "1 + 1 = 2",
                "role": "assistant",
                "reasoning_content": "The user is asking a simple math question in Chinese: \"1+1 等于多少?\" (What is 1+1?)\n\nThis is a trivial arithmetic question. The answer is 2. I should respond in Chinese since the conversation is in Chinese. Keep it simple and direct."
            },
            "finish_reason": "stop"
        }
    ],
    "usage": {
        "completion_tokens": 82,
        "prompt_tokens": 309,
        "total_tokens": 391,
        "completion_tokens_details": {
            "reasoning_tokens": 60
        },
        "prompt_tokens_details": {
            "cache_write_tokens": 256
        }
    }
}

流式响应

设置 stream=true 和 stream_options.include_usage=true;先返回 reasoning_content,再返回 content,最后的统计块为 choices: [],总用量位于顶层 usage。
data: {"id":"chatcmpl-6adb0ef5ba679679914a2719","object":"chat.completion.chunk","created":1792741109,"model":"kimi-k3.1-pro","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}],"system_fingerprint":"fpv0_dd3f7976"}

data: {"id":"chatcmpl-6adb0ef5ba679679914a2719","object":"chat.completion.chunk","created":1792741109,"model":"kimi-k3.1-pro","choices":[{"index":0,"delta":{"reasoning_content":"The"},"finish_reason":null}],"system_fingerprint":"fpv0_dd3f7976"}

...

data: {"id":"chatcmpl-6adb0ef5ba679679914a2719","object":"chat.completion.chunk","created":1792741109,"model":"kimi-k3.1-pro","choices":[{"index":0,"delta":{"content":"1"},"finish_reason":null}],"system_fingerprint":"fpv0_dd3f7976"}

...

data: {"id":"chatcmpl-6adb0ef5ba679679914a2719","object":"chat.completion.chunk","created":1792741109,"model":"kimi-k3.1-pro","choices":[],"usage":{"prompt_tokens":309,"completion_tokens":101,"total_tokens":410,"completion_tokens_details":{"reasoning_tokens":71},"prompt_tokens_details":{"cache_write_tokens":256}}}

data: [DONE]
响应示例中的模型名称会根据请求中的 model 参数返回。当使用 kimi-k3.1-pro 模型时,响应中的 "model" 字段将显示为 "kimi-k3.1-pro"。

上下文缓存(Cache Write)

Cache Write 适用于 kimi-k3.1-pro、kimi-k3.1-pro-highspeed 和 kimi-k3。Kimi API 会对重复的请求前缀自动启用上下文缓存,命中部分以更低价格计费且响应更快。通过 prompt_cache_options 可以控制缓存写入行为:
参数类型说明
prompt_cache_optionsobject上下文缓存写入选项。不传时默认开启缓存写入(5m 档)
prompt_cache_options.mode"implicit"缓存写入模式,仅支持 implicit:自动将请求前缀写入缓存
prompt_cache_options.ttl"5m" | "1h"缓存写入的有效期,仅支持 5m、1h 两档(默认 5m),两档缓存相互独立
{
    "model": "kimi-k3.1-pro",
    "messages": [{"role": "user", "content": "你好"}],
    "prompt_cache_options": { "mode": "implicit", "ttl": "1h" }
}
行为说明
  • 缓存以组织(org)为粒度隔离,组织之间不共享缓存。
  • 相同前缀的请求在缓存有效期内命中后,缓存的有效期会按原 TTL 刷新;命中部分只收取缓存读取费用,不再收取缓存写入费用。
  • 缓存写入按 TTL 分别计费,价格详见产品定价。
  • 不支持手动清除缓存,已缓存的前缀在至少 5 分钟不活动后自动过期。
  • 暂不支持显式缓存断点:content 中出现 prompt_cache_breakpoint 时请求会被拒绝(HTTP 400)。
用量字段usage.prompt_tokens 始终为总输入 Token 数,其内部分类通过 prompt_tokens_details 返回:
字段说明
usage.prompt_tokens_details.cached_tokens命中缓存的 Token 数量(缓存读取)
usage.prompt_tokens_details.cache_write_tokens本次写入缓存的 Token 数量(缓存写入)
cached_tokens、cache_write_tokens 与未缓存部分互斥,三者之和等于 prompt_tokens,即未缓存部分 = prompt_tokens − cached_tokens − cache_write_tokens。上方非流式响应中,输入为 309 Token,其中缓存写入 256 Token;输出为 82 Token,总计 309 + 82 = 391 Token。缓存读写已包含在 prompt_tokens 中,输出包含推理与正文,不应重复累加。流式请求中,完整的缓存读写明细仅在最后一个 chunk 的 usage 字段中返回(需设置 stream_options.include_usage=true)。Chat Completions 的响应不回显实际应用的 mode/ttl(与 Responses API 不同),请从请求发起侧记录所用取值。
Context Caching 的机制背景详见上下文缓存指南。

多轮对话

Kimi API 是无状态的,本身不具有记忆功能。要实现多轮对话,需在每次请求时把前一轮的 assistant 回复(以及工具执行结果,如适用)原样追加到 messages 数组中再发送。
messages = [
    {"role": "system", "content": "你是 Kimi。"},
    {"role": "user", "content": "你好,我叫李雷。"}
]

completion = client.chat.completions.create(model="kimi-k3.1-pro", messages=messages)
reply = completion.choices[0].message

# 原样保留完整 assistant 回复,包括 reasoning_content 和可能的 tool_calls
messages.append(reply.model_dump(exclude_none=True))
messages.append({"role": "user", "content": "1+1 等于多少?"})

completion = client.chat.completions.create(model="kimi-k3.1-pro", messages=messages)
print(completion.choices[0].message.content)
当对话历史过长时,建议只保留最近的若干条消息,或做消息压缩,以避免超出模型的上下文长度限制。
详见 配置多轮对话参数。

JSON Mode

通过 response_format 参数可约束模型输出格式:
  • {"type": "text"}(默认):普通文本输出
  • {"type": "json_object"}:强制输出合法 JSON Object
  • {"type": "json_schema", "json_schema": {...}}:按给定 JSON Schema 输出结构化数据(Structured Output)
使用 json_object 时,必须在 system prompt 或 user prompt 中明确描述期望的 JSON 字段和类型,否则模型可能输出不符合预期的结果。
{
  "model": "kimi-k3.1-pro",
  "messages": [
    {"role": "system", "content": "请输出 JSON,包含 title、author、summary 字段。"},
    {"role": "user", "content": "总结这篇文章:递归通过把问题分解为更小的同类子问题来求解,并通过终止条件结束调用。"}
  ],
  "response_format": {"type": "json_object"}
}
详见 使用 Kimi API 的 JSON Mode。

工具调用 Tool Use

通过 tools 参数传入 JSON Schema 定义的外部工具,模型可决定在适当时机调用它们。请求示例
{
  "model": "kimi-k3.1-pro",
  "messages": [{"role": "user", "content": "北京今天天气怎么样?"}],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "获取指定城市的天气",
        "parameters": {
          "type": "object",
          "properties": {
            "city": {"type": "string", "description": "城市名称"}
          },
          "required": ["city"]
        }
      }
    }
  ]
}
响应中的 tool_calls当 finish_reason 为 "tool_calls" 时,模型返回 tool_calls 数组,包含 id、function.name 和 function.arguments:
{
  "choices": [{
    "message": {
      "role": "assistant",
      "content": "",
      "reasoning_content": "用户问北京今天天气。需要调用天气工具。工具只需 city。调用 get_weather 城市北京。然后基于结果回答。注意当前日期系统提供2026-04-25,但天气工具会返回指定城市天气(可能实时)。调用。",
      "tool_calls": [
        {
          "id": "get_weather_0_995b2511",
          "type": "function",
          "function": {
            "arguments": "{\"city\":\"北京\"}",
            "name": "get_weather"
          }
        }
      ]
    },
    "finish_reason": "tool_calls"
  }]
}
提交工具执行结果在本地执行工具后,先将响应中的完整 assistant message(包括 reasoning_content 和 tool_calls)原样追加到原请求的 messages,再追加以下工具结果;tool_call_id 必须与 assistant 消息中的工具调用 id 对应:
{"role": "tool", "tool_call_id": "get_weather_0_995b2511", "content": "晴,25°C"}
详见 使用 Kimi API 完成工具调用。

思考模式与 Preserved Thinking

Kimi K3 系列始终开启思考与 Preserved Thinking,使用顶层 reasoning_effort(支持 "low"、"high"、"max",默认 "max"),不使用 thinking 参数。Kimi K2.6 和 Kimi K2.7 Code 请求参数
参数kimi-k2.6kimi-k2.7-code 和 kimi-k2.7-code-highspeed
thinking.type默认 "enabled",传 "disabled" 可关闭思考。仅支持 "enabled",传 "disabled" 会报错。
thinking.keep默认 null,不保留历史轮次的 reasoning_content。传 "all" 启用保留式思考(Preserved Thinking)。省略、传 null 或传 "all" 均按 "all" 处理,始终保留历史轮次的 reasoning_content。传入其他值会报错。
响应字段非流式响应中,choices[0].message 包含:
字段说明
content最终答案
reasoning_content推理过程(仅在思考模式启用时返回)
{
  "choices": [{
    "message": {
      "role": "assistant",
      "content": "1 + 1 = 2",
      "reasoning_content": "The user is asking a simple math question in Chinese: \"1+1 等于多少?\" (What is 1+1?)\n\nThis is a trivial arithmetic question. The answer is 2. I should respond in Chinese since the conversation is in Chinese. Keep it simple and direct."
    }
  }]
}
启用保留式思考时,请将历史 assistant 消息的 reasoning_content 原样回传到 messages,以保留推理上下文。
详见 配置思考模式。

流式输出 Streaming

设置 stream: true 可启用流式输出,模型会以 Server-Sent Events (SSE) 格式逐段返回生成的内容。推荐在聊天、代码生成、长文本输出等实时性要求高的场景中使用。
completion = client.chat.completions.create(
    model="kimi-k3.1-pro",
    messages=[{"role": "user", "content": "请解释什么是递归。"}],
    stream=True,
    stream_options={"include_usage": True},
)

for chunk in completion:
    if chunk.usage is not None:
        print("\nusage:", chunk.usage.model_dump())
    if not chunk.choices:
        continue
    delta = chunk.choices[0].delta
    reasoning: str = getattr(delta, "reasoning_content", None) or ""
    if reasoning:
        print(reasoning, end="")
    if delta.content:
        print(delta.content, end="")
SSE 响应格式每一行以 data: 开头,内容为 JSON 对象。先接收 delta.reasoning_content,再接收 delta.content;finish_reason="stop" 表示生成结束,其后的统计块 choices 为空,需从顶层 usage 读取用量:
data: {"id":"chatcmpl-6adb0efa76cd871ffe47cb4d","object":"chat.completion.chunk","created":1792741114,"model":"kimi-k3.1-pro","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}],"system_fingerprint":"fpv0_6e24f0d2"}

data: {"id":"chatcmpl-6adb0efa76cd871ffe47cb4d","object":"chat.completion.chunk","created":1792741114,"model":"kimi-k3.1-pro","choices":[{"index":0,"delta":{"reasoning_content":"The"},"finish_reason":null}],"system_fingerprint":"fpv0_6e24f0d2"}

...

data: {"id":"chatcmpl-6adb0efa76cd871ffe47cb4d","object":"chat.completion.chunk","created":1792741114,"model":"kimi-k3.1-pro","choices":[{"index":0,"delta":{"content":"#"},"finish_reason":null}],"system_fingerprint":"fpv0_6e24f0d2"}

...

data: {"id":"chatcmpl-6adb0efa76cd871ffe47cb4d","object":"chat.completion.chunk","created":1792741114,"model":"kimi-k3.1-pro","choices":[],"usage":{"prompt_tokens":90,"completion_tokens":1139,"total_tokens":1229,"completion_tokens_details":{"reasoning_tokens":620},"prompt_tokens_details":{"cache_write_tokens":0}}}

data: [DONE]
stream_options通过 stream_options: {"include_usage": true} 可在最后一个 chunk(data: [DONE] 之前)额外获取 usage 字段,显示本次请求的 Token 消耗:
stream=True,
stream_options={"include_usage": True}
详见 利用 Kimi API 的流式输出功能。

Partial Mode

Partial Mode(Prefill)允许你在 messages 的最后一条 assistant 消息中预填输出前缀,从而引导模型按照你期望的格式或方向继续生成。开启方式在 messages 数组末尾添加一条 role="assistant" 的消息,并设置 partial: true:
completion = client.chat.completions.create(
    model="kimi-k3.1-pro",
    messages=[
        {"role": "user", "content": "用 Python 实现快速排序。"},
        {"role": "assistant", "content": "```python\n", "partial": True}
    ]
)
模型从预填的代码块前缀之后续写;返回的 content 不包含该前缀。常见用途
  • 强制模型以特定格式开头(如 JSON 的 { 或 Markdown 代码块前缀)
  • 角色扮演中保持角色名称前缀(配合 name 字段)
  • 在 finish_reason="length" 且已有正文时,将已生成的正文作为前缀,并回传原 reasoning_content 继续生成
请勿将 Partial Mode 与 response_format={"type": "json_object"} 混用,否则可能获得预期外的模型回复。如需引导 JSON 输出,建议直接使用 Structured Output 或单独设置 partial: true 并预填 {。
详见 使用 Kimi API 的 Partial Mode。

授权

Authorization
string
header
必填

Authorization 请求头需要一个 Bearer 令牌。使用 MOONSHOT_API_KEY 作为令牌。这是一个服务端密钥,请在 API 密钥页面 生成。

请求头

X-Msh-Request-Nonce
string

客户端生成的随机 nonce(推荐使用 UUID v4),携带后即开启请求签名:Kimi API 会在响应头中返回 Msh-Request-Timestamp 与 Msh-Request-Signature,用于事后证明该请求确实由 Kimi API 处理。只允许一个非空的 Header 值;值不合法时请求照常执行,但不返回上述响应头。详见校验请求签名。

Minimum string length: 1
示例:

"7d929748-0ae6-41c2-ab5d-a186498ad721"

请求体

application/json
  • kimi-k3.1-pro 系列
  • kimi-k3
  • kimi-k2.7-code
  • kimi-k2.6
messages
(标准消息 · object | 动态工具消息 · object)[]
必填

对话消息列表。

支持标准对话消息和用于动态加载工具的 system 消息。

  • 标准消息
  • 动态工具消息

Show child attributes

model
enum<string>
默认值:kimi-k3.1-pro
必填

模型 ID

可用选项:
kimi-k3.1-pro,
kimi-k3.1-pro-highspeed
logprobs
boolean
默认值:false

是否返回输出 Token 的对数概率。设置为 true 时,在响应 message 的 logprobs 字段中返回每个输出 Token 的对数概率信息

top_logprobs
integer

指定在每个 Token 位置返回概率最高的候选 Token 数量(0-20),各候选 Token 附带对数概率。使用此参数时必须将 logprobs 设置为 true

必填范围: 0 <= x <= 20
prediction
object

Predicted Output 配置。当模型响应的大部分内容可以提前预知时(例如重新生成仅有少量修改的文件),可显著降低响应延迟

Show child attributes

max_tokens
integer
已弃用

已弃用,请使用 max_completion_tokens

max_completion_tokens
integer

聊天补全生成的最大 Token 数量。默认值因模型而异:Kimi K3 系列(kimi-k3.1-pro、kimi-k3.1-pro-highspeed、kimi-k3)默认为 131072,最大可设置为 1048576。如果结果达到最大 Token 数而未结束,finish reason 将为 "length";否则为 "stop"。此值为期望返回的 Token 长度,而非输入加输出的总长度。如果输入 Token 数(prompt_tokens)与 max_completion_tokens 之和超过模型上下文窗口,API 会根据剩余上下文空间自动调低本次请求的生成上限,并继续处理请求。输入 Token 数本身必须小于模型上下文窗口。

response_format
object

控制模型输出格式。默认值为 {"type": "text"},即纯文本输出。设置为 {"type": "json_object"} 可启用 JSON 模式,确保输出为合法 JSON 对象(需在 prompt 中引导模型输出 JSON 并指定格式)。设置为 {"type": "json_schema"} 可启用 Structured Output,按指定的 JSON Schema 约束输出结构(推荐,需配合 json_schema 字段使用)。如果您在使用 JSON Schema 时遇到校验问题,欢迎到 walle GitHub Issues (https://github.com/MoonshotAI/walle/issues) 提交反馈。

Show child attributes

stop
stringstring[]

停用词,完全匹配时将停止输出。匹配到的词本身不会被输出。最多允许 5 个字符串,每个不超过 32 字节

stream
boolean
默认值:false

是否以流式方式返回响应,默认 false

stream_options
object

流式响应选项

Show child attributes

tools
object[]

模型可调用的工具列表

Show child attributes

prompt_cache_key
string

用于缓存相似请求的响应以优化缓存命中率。对于 Coding Agent,通常是代表单个会话的 session id 或 task id;退出并恢复会话时应保持不变。对于 Kimi Code Plan,此字段为必填以提高缓存命中率。对于其他多轮对话 Agent,也建议使用此字段

prompt_cache_options
object

上下文缓存写入选项。不传时默认开启缓存写入(5m 档):系统自动将请求前缀写入 5m 档缓存

Show child attributes

safety_identifier
string

用于检测可能违反使用政策的用户的稳定标识符。应为唯一标识每个用户的字符串。建议对用户名或邮箱进行哈希处理以避免发送可识别信息

tool_choice
enum<string>object

控制模型是否调用工具。auto(默认):模型自行决定是否调用工具;none:不调用工具;required:强制调用工具;也可传入特定函数对象强制调用指定工具。

可用选项:
auto,
none,
required
reasoning_effort
enum<string>
默认值:max

Kimi K3 系列始终启用思考,并开启 Preserved Thinking。推理强度支持 low、high 和 max,默认为 max。

可用选项:
low,
high,
max

响应

聊天补全响应

id
string

补全结果的唯一标识符

object
string

对象类型

示例:

"chat.completion"

created
integer

补全创建时的 Unix 时间戳

model
string

用于补全的模型

choices
object[]

补全选项列表

Show child attributes

usage
object

Show child attributes

此页面对您有帮助吗?

⌘I
创建聊天补全
curl --request POST \
  --url https://api.moonshot.cn/v1/chat/completions \
  --header 'Authorization: Bearer <token>' \
  --header 'Content-Type: application/json' \
  --data '
{
  "messages": [
    {
      "role": "user",
      "content": "你好",
      "name": null,
      "partial": false
    }
  ],
  "model": "kimi-k3.1-pro",
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "<string>",
        "parameters": {},
        "description": "<string>",
        "strict": true
      }
    }
  ]
}
'
import requests

url = "https://api.moonshot.cn/v1/chat/completions"

payload = {
    "messages": [
        {
            "role": "user",
            "content": "你好",
            "name": None,
            "partial": False
        }
    ],
    "model": "kimi-k3.1-pro",
    "tools": [
        {
            "type": "function",
            "function": {
                "name": "<string>",
                "parameters": {},
                "description": "<string>",
                "strict": True
            }
        }
    ]
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.text)
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: JSON.stringify({
    messages: [{role: 'user', content: '你好', name: null, partial: false}],
    model: 'kimi-k3.1-pro',
    tools: [
      {
        type: 'function',
        function: {name: '<string>', parameters: {}, description: '<string>', strict: true}
      }
    ]
  })
};

fetch('https://api.moonshot.cn/v1/chat/completions', options)
  .then(res => res.json())
  .then(res => console.log(res))
  .catch(err => console.error(err));
<?php

$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "https://api.moonshot.cn/v1/chat/completions",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => json_encode([
    'messages' => [
        [
                'role' => 'user',
                'content' => '你好',
                'name' => null,
                'partial' => false
        ]
    ],
    'model' => 'kimi-k3.1-pro',
    'tools' => [
        [
                'type' => 'function',
                'function' => [
                                'name' => '<string>',
                                'parameters' => [
                                                                
                                ],
                                'description' => '<string>',
                                'strict' => true
                ]
        ]
    ]
  ]),
  CURLOPT_HTTPHEADER => [
    "Authorization: Bearer <token>",
    "Content-Type: application/json"
  ],
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.moonshot.cn/v1/chat/completions"

	payload := strings.NewReader("{\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"你好\",\n      \"name\": null,\n      \"partial\": false\n    }\n  ],\n  \"model\": \"kimi-k3.1-pro\",\n  \"tools\": [\n    {\n      \"type\": \"function\",\n      \"function\": {\n        \"name\": \"<string>\",\n        \"parameters\": {},\n        \"description\": \"<string>\",\n        \"strict\": true\n      }\n    }\n  ]\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(string(body))

}
HttpResponse<String> response = Unirest.post("https://api.moonshot.cn/v1/chat/completions")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"你好\",\n      \"name\": null,\n      \"partial\": false\n    }\n  ],\n  \"model\": \"kimi-k3.1-pro\",\n  \"tools\": [\n    {\n      \"type\": \"function\",\n      \"function\": {\n        \"name\": \"<string>\",\n        \"parameters\": {},\n        \"description\": \"<string>\",\n        \"strict\": true\n      }\n    }\n  ]\n}")
  .asString();
require 'uri'
require 'net/http'

url = URI("https://api.moonshot.cn/v1/chat/completions")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"你好\",\n      \"name\": null,\n      \"partial\": false\n    }\n  ],\n  \"model\": \"kimi-k3.1-pro\",\n  \"tools\": [\n    {\n      \"type\": \"function\",\n      \"function\": {\n        \"name\": \"<string>\",\n        \"parameters\": {},\n        \"description\": \"<string>\",\n        \"strict\": true\n      }\n    }\n  ]\n}"

response = http.request(request)
puts response.read_body
{
  "id": "<string>",
  "object": "chat.completion",
  "created": 123,
  "model": "<string>",
  "choices": [
    {
      "index": 123,
      "message": {
        "role": "assistant",
        "content": "<string>",
        "tool_calls": [
          {
            "id": "<string>",
            "type": "function",
            "function": {
              "name": "<string>",
              "arguments": "<string>"
            }
          }
        ],
        "reasoning_content": "<string>"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 123,
    "completion_tokens": 123,
    "total_tokens": 123,
    "cached_tokens": 123,
    "prompt_tokens_details": {
      "cached_tokens": 123,
      "cache_write_tokens": 123
    }
  }
}
{
  "error": {
    "message": "<string>",
    "type": "<string>",
    "code": "<string>"
  }
}
{
  "error": {
    "message": "<string>",
    "type": "<string>",
    "code": "<string>"
  }
}
{
  "error": {
    "message": "<string>",
    "type": "<string>",
    "code": "<string>"
  }
}
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.