kimi-k2-preview

This documentation is valid for the following model: moonshot/kimi-k2-preview

Model Overview

A mixture-of-experts model with strong reasoning, coding, and agentic capabilities.

How to Make a Call

Step-by-Step Instructions

1️ Setup You Can’t Skip

▪️ Create an Account: Visit the AI/ML API website and create an account (if you don’t have one yet). ▪️ Generate an API Key: After logging in, navigate to your account dashboard and generate your API key. Ensure that key is enabled on UI.

2️ Copy the code example

At the bottom of this page, you'll find a code example that shows how to structure the request. Choose the code snippet in your preferred programming language and copy it into your development environment.

3️ Modify the code example

▪️ Replace <YOUR_AIMLAPI_KEY> with your actual AI/ML API key from your account. ▪️ Insert your question or request into the content field—this is what the model will respond to.

4️ (Optional) Adjust other optional parameters if needed

Only model and messages are required parameters for this model (and we’ve already filled them in for you in the example), but you can include optional parameters if needed to adjust the model’s behavior. Below, you can find the corresponding API schema, which lists all available parameters along with notes on how to use them.

5️ Run your modified code

Run your modified code in your development environment. Response time depends on various factors, but for simple prompts it rarely exceeds a few seconds.

API Schema

Generate a conversational response using a language model.

post

Creates a chat completion using a language model, allowing interactive conversation by predicting the next response based on the given chat history. This is useful for AI-driven dialogue systems and virtual assistants.

Authorizations
Body
modelundefined · enumRequiredPossible values:
max_completion_tokensinteger · min: 1Optional

An upper bound for the number of tokens that can be generated for a completion, including visible output tokens and reasoning tokens.

Default: 512
max_tokensnumber · min: 1Optional

The maximum number of tokens that can be generated in the chat completion. This value can be used to control costs for text generated via API.

Default: 512
streambooleanOptional

If set to True, the model response data will be streamed to the client as it is generated using server-sent events.

Default: false
tool_choiceany ofOptional

Controls which (if any) tool is called by the model. none means the model will not call any tool and instead generates a message. auto means the model can pick between generating a message or calling one or more tools. required means the model must call one or more tools. Specifying a particular tool via {"type": "function", "function": {"name": "my_function"}} forces the model to call that tool. none is the default when no tools are present. auto is the default if tools are present.

string · enumOptional

none means the model will not call any tool and instead generates a message. auto means the model can pick between generating a message or calling one or more tools. required means the model must call one or more tools.

Possible values:
or
parallel_tool_callsbooleanOptional

Whether to enable parallel function calling during tool use.

ninteger | nullableOptional

How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep n as 1 to minimize costs.

temperaturenumber · max: 2Optional

What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. We generally recommend altering this or top_p but not both.

top_pnumber · min: 0.01 · max: 1Optional

An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or temperature but not both.

stopany ofOptional

Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence.

stringOptional
or
string[]Optional
or
any | nullableOptional
frequency_penaltynumber | nullableOptional

Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.

presence_penaltynumber | nullableOptional

Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.

response_formatone ofOptional

An object specifying the format that the model must output.

or
or
Responses
201Success
post
POST /v1/chat/completions HTTP/1.1
Host: api.aimlapi.com
Authorization: Bearer <YOUR_AIMLAPI_KEY>
Content-Type: application/json
Accept: */*
Content-Length: 490

{
  "model": "moonshot/kimi-k2-preview",
  "messages": [
    {
      "role": "user",
      "content": "text",
      "name": "text"
    }
  ],
  "max_completion_tokens": 512,
  "max_tokens": 512,
  "stream": false,
  "stream_options": {
    "include_usage": true
  },
  "tools": [
    {
      "type": "function",
      "function": {
        "description": "text",
        "name": "$web_search",
        "parameters": null,
        "required": [
          "text"
        ]
      }
    }
  ],
  "tool_choice": "none",
  "parallel_tool_calls": true,
  "n": 1,
  "temperature": 1,
  "top_p": 1,
  "stop": "text",
  "frequency_penalty": 1,
  "presence_penalty": 1,
  "response_format": {
    "type": "text"
  }
}
201Success

No content

Code Example #1: Chat Completion

import requests
import json  # for getting a structured output with indentation

response = requests.post(
    "https://api.aimlapi.com/v1/chat/completions",
    headers={
        "Content-Type":"application/json", 

        # Insert your AIML API Key instead of <YOUR_AIMLAPI_KEY>:
        "Authorization":"Bearer <YOUR_AIMLAPI_KEY>",
        "Content-Type":"application/json"
    },
    json={
        "model":"moonshot/kimi-k2-preview",
        "messages":[
            {
                "role":"user",

                # Insert your question for the model here, instead of Hello:
                "content":"Hello!"
            }
        ]
    }
)

data = response.json()
print(json.dumps(data, indent=2, ensure_ascii=False))
Response
{
  "id": "chatcmpl-6881021ed173a2ae63fab92b",
  "object": "chat.completion",
  "choices": [
    {
      "index": 0,
      "finish_reason": "stop",
      "message": {
        "role": "assistant",
        "content": "Hello! How can I help you today?"
      }
    }
  ],
  "created": 1753285150,
  "model": "kimi-k2-0711-preview",
  "usage": {
    "prompt_tokens": 11,
    "completion_tokens": 53,
    "total_tokens": 64
  }
}
import json
import requests
from typing import Dict, Any

# Insert your AIML API Key instead of <YOUR_AIMLAPI_KEY>:
API_KEY = "<YOUR_AIMLAPI_KEY>"
BASE_URL = "https://api.aimlapi.com/v1"

HEADERS = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json",
}


def search_impl(arguments: Dict[str, Any]) -> Any:
    return arguments


def chat(messages):
    url = f"{BASE_URL}/chat/completions"
    payload = {
        "model": "moonshot/kimi-k2-preview",
        "messages": messages,
        "temperature": 0.6,
        "tools": [
            {
                "type": "builtin_function",
                "function": {"name": "$web_search"},
            }
        ]
    }

    response = requests.post(url, headers=HEADERS, json=payload)
    response.raise_for_status()
    return response.json()["choices"][0]


def main():
    messages = [
        {"role": "system", "content": "You are Kimi."},
        {"role": "user", "content": "Please search for Moonshot AI Context Caching technology and tell me what it is in English."}
    ]

    finish_reason = None
    while finish_reason is None or finish_reason == "tool_calls":
        choice = chat(messages)
        finish_reason = choice["finish_reason"]
        message = choice["message"]

        if finish_reason == "tool_calls":
            messages.append(message)

            for tool_call in message["tool_calls"]:
                tool_call_name = tool_call["function"]["name"]
                tool_call_arguments = json.loads(tool_call["function"]["arguments"])

                if tool_call_name == "$web_search":
                    tool_result = search_impl(tool_call_arguments)
                else:
                    tool_result = f"Error: unable to find tool by name '{tool_call_name}'"

                messages.append({
                    "role": "tool",
                    "tool_call_id": tool_call["id"],
                    "name": tool_call_name,
                    "content": json.dumps(tool_result),
                })

    print(message["content"])


if __name__ == "__main__":
    main()
Response
Moonshot AI’s “Context Caching” is a data-management layer for the Kimi large-language-model API.

What it does  
1. You upload or define a large, static context once (for example a 100-page product manual, a legal contract, or a code base).  
2. The platform stores this context in a fast-access cache and gives it a tag/ID.  
3. In every subsequent call you only send the new user question; the system re-uses the cached context instead of transmitting and re-processing the whole document each time.  
4. When the cache TTL expires it is deleted automatically; you can also refresh or invalidate it explicitly.

Benefits  
- Up to 90 % lower token consumption (you pay only for the incremental prompt and the new response).  
- 83 % shorter time-to-first-token latency, because the heavy prefill phase is skipped on every reuse.  
- API price stays the same; savings come from not re-sending the same long context.

Typical use cases  
- Customer-support bots that answer many questions against the same knowledge base.  
- Repeated analysis of a static code repository.  
- High-traffic AI applications that repeatedly query the same large document set.

Billing (during public beta)  
- Cache creation: 24 CNY per million tokens cached.  
- Storage: 10 CNY per million tokens per minute.  
- Cache hit: 0.02 CNY per successful call that re-uses the cache.

In short, Context Caching lets developers treat very long, seldom-changing context as a reusable asset, cutting both cost and latency for repeated queries.

Last updated

Was this helpful?