Skip to main content

Kimi

This document describes how to call the Kimi model inference service deployed on Alibaba Cloud Model Studio.

Supported regions: Singapore, Japan (Tokyo), United States (Virginia), North China 2 (Beijing), Germany (Frankfurt), Hong Kong (China). Playground: You can go to the Playground to try out the Kimi model. kimi-k3.1-pro supports OpenAI Chat Completions, OpenAI Responses, Anthropic Messages, and the DashScope native API. The service endpoint varies by region. Configure the Base URL based on the region you select.
  • OpenAI compatible
  • DashScope
  • Anthropic-compatible
The base_url for each region below also applies to OpenAI Responses; the HTTP request URL appends /responses to the base_url, that is, POST {base_url}/responses.
  • Singapore
  • United States (Virginia)
  • Germany (Frankfurt)
  • North China 2 (Beijing)
  • Japan (Tokyo)
  • Hong Kong (China)
The base_url configured for SDK calls: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1HTTP request URL: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions
When calling, replace {WorkspaceId} with your actual Workspace ID. You must have obtained and configured an API Key and configured the API Key as an environment variable. If you call through an SDK, you need to install the SDK.

QuickStart

The following is a plain-text input example. For multimodal examples, see multimodal invocation examples.
  • OpenAI compatible
  • DashScope
  • Anthropic-compatible
  • Python
  • Node.js
  • HTTP
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 以下为新加坡地域的URL。请将 {WorkspaceId} 替换为您的百炼业务空间ID,各地域的URL不同。
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

completion = client.chat.completions.create(
    model="kimi-k3",
    messages=[{"role": "user", "content": "你是谁"}],
    stream=True,
    extra_body={"enable_thinking": True},
)

reasoning_content = ""  # 完整思考过程
answer_content = ""     # 完整回复
is_answering = False    # 是否进入回复阶段

print("\n" + "=" * 20 + "思考过程" + "=" * 20 + "\n")

for chunk in completion:
    if chunk.choices:
        delta = chunk.choices[0].delta
        # 只收集思考内容
        if hasattr(delta, "reasoning_content") and delta.reasoning_content is not None:
            if not is_answering:
                print(delta.reasoning_content, end="", flush=True)
            reasoning_content += delta.reasoning_content
        # 收到content,开始进行回复
        if hasattr(delta, "content") and delta.content:
            if not is_answering:
                print("\n" + "=" * 20 + "完整回复" + "=" * 20 + "\n")
                is_answering = True
            print(delta.content, end="", flush=True)
            answer_content += delta.content

Response

====================思考过程====================

用户问"你是谁",这是一个关于身份的直接问题。我需要根据我的实际身份如实回答。

我是由月之暗面科技有限公司(Moonshot AI)开发的人工智能助手,我的名字是Kimi。我应该清晰、简洁地介绍自己,包括:
1. 我的身份:AI助手
2. 我的开发者:月之暗面科技有限公司(Moonshot AI)
3. 我的名字:Kimi
4. 我的核心能力:长文本处理、智能对话、文件处理、搜索等

我应该保持友好、专业的语气,避免过于技术化的术语,让普通用户也能理解。同时,我应该强调我是一个AI,没有个人意识、情感或个人经历。

回答结构:
- 直接回答身份
- 说明开发者
- 简要介绍核心能力
- 保持简洁明了
====================完整回复====================

我是由月之暗面科技有限公司(Moonshot AI)开发的AI助手,名叫Kimi。我基于混合专家(MoE)架构,具备超长上下文理解、智能对话、文件处理、代码生成和复杂任务推理等能力。有什么可以帮您的吗?

Multimodal invocation examples

kimi-k3.1-pro, kimi-k3, kimi-k2.7-code, kimi-k2.6, and kimi-k2.5 support multimodal input and text output. Among them, kimi-k3.1-pro and kimi-k3 only support text and image input and do not support video input; kimi-k2.7-code, kimi-k2.6, and kimi-k2.5 can process text, image, or video input at the same time. You can enable thinking mode through the enable_thinking parameter. The following examples show how to invoke multimodal capabilities.

Enable or disable thinking mode

kimi-k2.6 and kimi-k2.5 are hybrid thinking models: they can respond after thinking or respond directly. Use the enable_thinking parameter to control whether thinking mode is enabled:
  • true: enable thinking mode
  • false (default): disable thinking mode
kimi-k2.7-code is a thinking-only model and always has thinking mode enabled (enable_thinking defaults to true and cannot be disabled); preserve_thinking defaults to true. kimi-k3.1-pro and kimi-k3 enable thinking by default (enable_thinking=true). You can set it to false to disable thinking, but keeping it enabled is recommended. Disabling thinking on kimi-k3.1-pro significantly degrades output quality, so keeping it enabled is strongly recommended. Both models retain the historical reasoning_content passed in by the client by default; in multi-turn requests, it is recommended to pass back the full reasoning_content of historical assistant messages. kimi-k2.6 supports passing the thinking process across multi-turn conversations through the preserve_thinking parameter. For details, see Passing the thinking process. The following example shows how to use an image URL and enable thinking mode, supporting single-image input (the main example) and multi-image input (the commented-out code).
  • OpenAI compatible
  • DashScope
Python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 以下为新加坡地域的URL。请将 {WorkspaceId} 替换为您的百炼业务空间ID,各地域的URL不同。
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

# 单图传入示例(开启思考模式)
completion = client.chat.completions.create(
    model="kimi-k3",
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "图中描绘的是什么景象?"},
                {
                    "type": "image_url",
                    "image_url": {
                        "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"
                    }
                }
            ]
        }
    ],
    extra_body={"enable_thinking":True}  # 开启思考模式
)

# 输出思考过程
if hasattr(completion.choices[0].message, 'reasoning_content') and completion.choices[0].message.reasoning_content:
    print("\n" + "=" * 20 + "思考过程" + "=" * 20 + "\n")
    print(completion.choices[0].message.reasoning_content)

# 输出回复内容
print("\n" + "=" * 20 + "完整回复" + "=" * 20 + "\n")
print(completion.choices[0].message.content)

# 多图传入示例(开启思考模式,取消注释使用)
# completion = client.chat.completions.create(
#     model="kimi-k2.6",
#     messages=[
#         {
#             "role": "user",
#             "content": [
#                 {"type": "text", "text": "这些图描绘了什么内容?"},
#                 {
#                     "type": "image_url",
#                     "image_url": {"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"}
#                 },
#                 {
#                     "type": "image_url",
#                     "image_url": {"url": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/tiger.png"}
#                 }
#             ]
#         }
#     ],
#     extra_body={"enable_thinking":True}
# )
#
# # 输出思考过程和回复
# if hasattr(completion.choices[0].message, 'reasoning_content') and completion.choices[0].message.reasoning_content:
#     print("\n思考过程:\n" + completion.choices[0].message.reasoning_content)
# print("\n完整回复:\n" + completion.choices[0].message.content)

Video Understanding

kimi-k3.1-pro and kimi-k3 do not support video input (they only support text and image input), so the video understanding examples in this section do not apply to these two models.
  • Video file
  • Image list
The kimi-k2.7-code, kimi-k2.6, and kimi-k2.5 models analyze content by extracting a sequence of frames from videos. You can control the frame extraction strategy with the following two parameters:
  • fps: controls the frame extraction frequency, extracting one frame every 1/fps seconds. The value range is [0.1, 10], and the default value is 2.0.
    • High-speed motion scenarios: a higher fps value is recommended to capture more details
    • Static scenes or long videos: a lower fps value is recommended to improve processing efficiency
  • max_frames: limits the maximum number of frames extracted from a video; the default and maximum values are both 2000. When the total number of frames calculated by fps exceeds this limit, the system automatically samples frames evenly within max_frames. This parameter is available only when using the DashScope SDK.
  • OpenAI compatible
  • DashScope
When you directly input a video file to the model using the OpenAI SDK or HTTP, set the "type" parameter in the user message to "video_url".
Python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 以下为华北2(北京)地域的URL。请将 {WorkspaceId} 替换为您的百炼业务空间ID,各地域的URL不同。
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)

completion = client.chat.completions.create(
    model="kimi-k2.6",
    messages=[
        {
            "role": "user",
            "content": [
                # 直接传入视频文件时,请将type的值设置为video_url
                {
                    "type": "video_url",
                    "video_url": {
                        "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241115/cqqkru/1.mp4"
                    },
                    "fps": 2
                },
                {
                    "type": "text",
                    "text": "这段视频的内容是什么?"
                }
            ]
        }
    ]
)

print(completion.choices[0].message.content)

Pass in local files

The following examples show how to pass in local files. The OpenAI-compatible interface supports only Base64 encoding, while DashScope supports both Base64 encoding and file paths.
  • OpenAI compatible
  • DashScope
Passing files via Base64 encoding requires constructing a Data URL. For how to construct one, see Build a Data URL.
Python
from openai import OpenAI
import os
import base64

#  编码函数: 将本地文件转换为 Base64 编码的字符串
def encode_image(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode("utf-8")

# 将xxx/eagle.png替换为你本地图像的绝对路径
base64_image = encode_image("xxx/eagle.png")

client = OpenAI(
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    # 以下为华北2(北京)地域的URL。请将 {WorkspaceId} 替换为您的百炼业务空间ID,各地域的URL不同。
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
    model="kimi-k2.6",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {"url": f"data:image/png;base64,{base64_image}"},
                },
                {"type": "text", "text": "图中描绘的是什么景象?"},
            ],
        }
    ],
)
print(completion.choices[0].message.content)

# 以下为传入本地视频文件、本地图像列表的示例

# 【本地视频文件】将本地视频编码为 Data URL 后传入 video_url:
#   def encode_video_to_data_url(video_path):
#       with open(video_path, "rb") as f:
#           return "data:video/mp4;base64," + base64.b64encode(f.read()).decode("utf-8")

#   video_data_url = encode_video_to_data_url("xxx/local.mp4")
#   content = [{"type": "video_url", "video_url": {"url": video_data_url}, "fps": 2}, {"type": "text", "text": "这段视频的内容是什么?"}]

# 【本地图像列表】将多张本地图片分别 Base64 后组成 video 列表传入:
#   image_data_urls = [f"data:image/jpeg;base64,{encode_image(p)}" for p in ["xxx/f1.jpg", "xxx/f2.jpg", "xxx/f3.jpg", "xxx/f4.jpg"]]
#   content = [{"type": "video", "video": image_data_urls, "fps": 2}, {"type": "text", "text": "描述这个视频的具体过程"}]

File limits

  • Image limits
  • Video limits
  • Image resolution:
    • Minimum size: both the width and height of the image must be greater than 10 pixels.
    • Aspect ratio: the ratio of the long side to the short side of the image must not exceed 200:1.
    • Pixel limit: we recommend keeping the image resolution within 8K(7680x4320). Images above this resolution may cause API call timeouts due to oversized files or lengthy network transfers.
  • Supported image formats
    • For resolutions below 4K(3840x2160), the supported image formats are as follows:

      Image format

      Common extensions

      MIME Type

      BMP

      .bmp

      image/bmp

      JPEG

      .jpe, .jpeg, .jpg

      image/jpeg

      PNG

      .png

      image/png

      TIFF

      .tif, .tiff

      image/tiff

      WEBP

      .webp

      image/webp

      HEIC

      .heic

      image/heic

    • For resolutions from 4K(3840x2160) to 8K(7680x4320), only the JPEG, JPG, and PNG formats are supported.
  • Image size:
    • When passing via public URL or local path: each image must be no larger than 10MB.
    • When passing via Base64 encoding: the encoded string must be no larger than 10MB.
    To compress files, see How to compress an image or video to meet the size requirements.
  • Number of images that can be passed: when passing multiple images, the number of images is limited by the model's maximum input; the total number of tokens of all images and text must be less than the model's maximum input.

Other features

Model

Multi-turn

Deep thinking

Function Calling

Structured output

Web search

Partial mode

Context cache

kimi-k3.1-pro

Supported

Supported

Supported

Supported (JSON Mode)

Supported

Not supported

Supported (implicit cache)

kimi-k3

Supported

Supported

Supported

Supported

Supported (Responses API)

Supported

Supported

kimi-k2.7-code

Supported

Supported

Supported

Not supported

Not supported

Not supported

Supported

kimi-k2.6

Supported

Supported

Supported

Not supported

Not supported

Not supported

Supported

kimi-k2.5

Supported

Supported

Supported

Not supported

Not supported

Not supported

Supported

Dynamically Loaded Tools

When an application needs to mount a large number of tools, putting all tool declarations into the request's top-level tools field at once leads to the Tool Definition Bloat problem: every request must carry the descriptions and parameter schemas of all tools, resulting in high token consumption; the more candidate tools there are, the more likely the model is to pick the wrong tool and construct incorrect call parameters. Dynamically Loaded Tools allow tools to be injected on demand during a conversation: mount only a few core tools first, and when the conversation progresses to the point where a specific tool is needed, dynamically insert it into messages, thereby reducing token consumption and improving the accuracy of tool selection.
kimi-k3.1-pro and kimi-k3 support dynamically loaded tools; requests on other models (such as kimi-k2.6) return a tokenization failed error.The format and examples in this section for injecting tools into messages via the tools field of the system message (system.tools) apply to the OpenAI Chat Completions API.

Injecting tool declarations into messages

Insert a message with role set to system into messages, and declare the tools to load via the tools field of that message. The declaration format is exactly the same as that of the request's top-level tools field, and complete tool information (name, description, parameters) must be provided.
  • A system message carrying tools has the same standing as an ordinary message: wherever it appears in the messages list is where the tools become visible to the model.
  • Dynamically loaded tools coexist with global tools declared in the request's top-level tools field, and the model can see both types of tools at the same time.
  • A dynamically injected tool declaration must be a complete tool definition; you cannot pass only a tool name or reference a tool already declared globally.
  • A system message carrying tools cannot also carry a content field; otherwise the request fails with a 400 error. When using the OpenAI SDK, you can pass the tools field through directly in messages.
Python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 以下为华北2(北京)地域的URL。请将 {WorkspaceId} 替换为您的百炼业务空间ID,各地域的URL不同。
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)

completion = client.chat.completions.create(
    model="kimi-k3",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "帮我计算一下 23 * 47 的结果。"},
        # 动态加载工具:在对话中插入一条携带 tools 字段的 system 消息
        {
            "role": "system",
            "tools": [
                {
                    "type": "function",
                    "function": {
                        "name": "Calculator",
                        "description": "计算器,只支持单个算术表达式的求值",
                        "parameters": {
                            "type": "object",
                            "properties": {
                                "expr": {
                                    "type": "string",
                                    "description": "算术表达式,支持四则运算、指数运算、对数函数、三角函数,使用 JavaScript 语法",
                                }
                            },
                            "required": ["expr"],
                        },
                    },
                }
            ],
        },
    ],
)

print(completion.choices[0].message.tool_calls)

On-demand loading with a search tool

There is no dedicated tool search API at the API level. If you have a large number of tools, you can combine a "custom search tool + dynamically loaded tools" approach to achieve on-demand loading:
  1. At the start of a session, declare in the request's top-level tools only a search_tools tool implemented by your application backend (which returns matching tool names and brief descriptions by keyword), plus a small number of core tools that may be needed in every turn.
  2. Declare searchable keywords in the System Prompt (for example, a tool catalog or domain tags) to guide the model to call search_tools first when it needs a tool. Setting tool_choice: "required" on the first request only guarantees that the model calls at least one tool, not that it calls search_tools first. If searching must come first, explicitly set tool_choice: {"type": "function", "function": {"name": "search_tools"}}, and restore tool_choice to "auto" once retrieval is complete. Modifying tool_choice does not break the prefix cache.
  3. Based on the results returned by search_tools, the application dynamically inserts the complete declarations of the corresponding tools into messages via a system message carrying tools.
  4. The model can then directly call these newly loaded tools in subsequent generation.
This way, no matter how large the total number of tools is, only a few tool declarations are actually present in each request, keeping both the context window and the model's selection pressure under control.

Notes

  • Dynamic tool declarations take effect per request and are not remembered by the server. Whether to keep including them in subsequent requests is up to the integrator: if you keep including them, the tools remain available, which also helps hit the prefix cache; if you stop including them, the tool declarations become invalid — if the tools are not declared elsewhere, the model will no longer be able to call them, and the prefix cache after the changed position may no longer be hit.
  • Appending dynamic tool declarations at the end of messages does not affect the cache of the existing prefix; deleting or modifying previous tool declarations may affect cache hits after the changed position. Declaring global tools in the request's top-level tools field likewise does not affect cache hits.
  • A system message carrying tools also consumes context length, so only dynamically inject tools that the current conversation truly needs.
  • Dynamic tool declarations and global tools declarations share exactly the same format, so integrators do not need to maintain two sets of schemas.

Default parameter values

Model

enable_thinking

temperature

top_p

presence_penalty

fps

max_frames

kimi-k3.1-pro

true (can be disabled; keeping it enabled is strongly recommended)

1.0

0.95

0.0

-

-

kimi-k3

true (can be disabled; keeping it enabled is recommended)

1.0

0.95

0.0

-

-

kimi-k2.7-code

true (thinking mode only; cannot be disabled)

1.0

0.95

0.0

2

2000

kimi-k2.6

false

Thinking mode: 1.0

Non-thinking mode: 0.6

Thinking/non-thinking mode: 0.95

Thinking/non-thinking mode: 0.0

2

2000

kimi-k2.5

false

Thinking mode: 1.0

Non-thinking mode: 0.6

Thinking/non-thinking mode: 0.95

Thinking/non-thinking mode: 0.0

2

2000

"-" indicates that there is no default value and setting one is not supported. The sampling parameters of kimi-k3.1-pro are fixed values: temperature=1.0, top_p=0.95, presence_penalty=0.0. The temperature and top_p of kimi-k3 are fixed values: temperature=1.0, top_p=0.95. Passing any non-default value for these parameters will cause an error. The following reasoning effort levels apply only to kimi-k3.1-pro, with the default value max:
  • max (default): deep reasoning
  • high: enhanced reasoning
  • medium: medium reasoning
  • low: light reasoning
The location of the reasoning effort parameter varies by protocol:
  • OpenAI Chat Completions: the top-level reasoning_effort in the request; when using the OpenAI Python SDK, pass reasoning_effort="max" directly.
  • DashScope: the SDK uses the reasoning_effort parameter, and HTTP requests use parameters.reasoning_effort.
  • OpenAI Responses: uses reasoning.effort.
  • Anthropic Messages: uses output_config.effort.

Model list and billing

The Kimi series models are large language models developed by Moonshot AI.
  • kimi-k3.1-pro: Supports text and image input, text output, and dynamic tool loading; does not support video input, Batch, or fine-tuning.
  • kimi-k3: Kimi's flagship model, which performs reasoning by default and adopts reserved thinking. Supports text and image input (video input not yet supported), conversation and Agent tasks, and dynamic tool loading.
  • kimi-k2.7-code: Kimi's coding model, with more reliable long-context instruction following and a higher success rate on coding tasks. Supports text, image, and video input; thinking mode; and conversation and Agent tasks.
  • kimi-k2.6: A Kimi model with stronger and more stable long-range coding capabilities, and significantly improved instruction following and self-correction. Also supports text, image, and video input; thinking and non-thinking modes; and conversation and Agent tasks.
  • kimi-k2.5: Achieves open-source SOTA performance on Agent, code generation, visual understanding, and a range of general intelligence tasks. Also supports image, video, and text input; thinking and non-thinking modes; and conversation and Agent tasks.
kimi-k3.1-pro and kimi-k3 do not support the thinking_budget parameter; the thinking length cannot be limited via this parameter.
For pricing information, see Model invocation billing.
For model context length and pricing information, see the Model Studio console. Billing is based on the number of input and output tokens processed by the model.
In thinking mode, the chain of thought is billed as output tokens.

Error codes

If a model call fails and returns an error message, see Error codes to resolve the issue.