Try Kimi at kimi.com →

Kimi K2.7 Code API

This guide shows developers how to call Kimi K2.7 Code, Moonshot AI's coding model, from their own software. It covers the model names, a first request you can copy, the settings that cause errors, tool calls, prices and fixes for common problems. Everything here follows Moonshot's own documentation.

For developersCopy-and-paste code
Your appsends a requestwith your API key Moonshot APIkimi-k2.7-code thinking... requestreply THE REPLY HAS TWO PARTS "reasoning_content":"A prime has no divisors except..." "content":"def is_prime(n): ..." Show "content" to your users. Keep both in the history.

An illustration of the request and reply. The text shown is an example, not real output.

We are an independent guide. We are not Moonshot AI. API keys are created only on Moonshot's platform, and we never ask for yours. The code on this page follows Moonshot's documentation, but we could not run it against the live API, so test it with a small request first.
CHEAT SHEET

The key facts

MODEL NAMES
kimi-k2.7-code
kimi-k2.7-code-highspeed
BASE URL
https://api.moonshot.ai/v1
WORKS WITH
The OpenAI SDK. An Anthropic-style address is also offered
CONTEXT
262,144 tokens, input and output together
DEFAULT OUTPUT LIMIT
32,768 tokens (max_tokens)
THINKING
Always on. It cannot be switched off
INPUT
Text and images. Video too, through Moonshot's API
PRICE PER MILLION TOKENS
$0.95 in · $0.19 cached · $4.00 out

From Moonshot's Kimi K2.7 Code quickstart, models page and price page. Prices exclude tax.

Step 1

Before you start

  1. Sign in to Moonshot's API platform at platform.kimi.ai and add a small balance. The minimum is $1.
  2. Create an API key in the console. Copy it straight away.
  3. Save it as an environment variable named MOONSHOT_API_KEY. Do not paste it into your code.
  4. For Python, install the OpenAI SDK: pip install --upgrade "openai>=1.0". For Node, run npm install openai.
Keep your key private. Anyone with the key can spend your balance. Never put it in a website's front-end code, a public repository or a chat message.

Need more detail on keys and accounts? See Kimi API setup.

Step 2

Your first request

All three examples do the same thing: ask Kimi K2.7 Code to write a small function and print its answer.

curl
curl https://api.moonshot.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $MOONSHOT_API_KEY" \
  -d '{
    "model": "kimi-k2.7-code",
    "max_tokens": 4096,
    "messages": [
      {"role": "user", "content": "Write a Python function that checks if a number is prime."}
    ]
  }'

The Python example follows Moonshot's quickstart. The curl and Node versions use the same request in the standard OpenAI format. Notice what is missing: no temperature setting.

Step 3

Reading the reply

Because the model always thinks first, each reply has two parts.

reasoning_content

  • The model's thinking
  • Useful for debugging
  • Counts as output tokens on your bill

content

  • The final answer
  • This is what you show to users
  • Parse this part if you expect code or JSON
Set max_tokens with thinking in mind. Thinking and the answer share the same limit. If the limit is too low, the model can run out before it finishes answering. The default is 32,768.
IMPORTANT

Settings you cannot change

This is the most common source of errors. Moonshot fixes several settings for this model. Sending any other value returns an error, so the simplest approach is to leave them out.

SettingFixed atWhat to do
temperature1.0Leave it out
top_p0.95Leave it out
n1Leave it out. One answer per request
presence_penalty0Leave it out
frequency_penalty0Leave it out
thinkingEnabledDo not disable it
tool_choiceauto or noneDo not use required or a named tool

On a small screen, swipe the table sideways to see every column.

Many coding tools and libraries send a temperature by default. If yours does, look for a way to remove it. Need thinking switched off for fast, simple calls? Use kimi-k2.6 for those.

BUILD

Tool calls

Tools are how a coding model does real work: reading files, running tests, searching a project. You describe each tool, the model asks to use one, your code runs it and sends the result back.

python · a simple tool loop
import json, os
from openai import OpenAI

client = OpenAI(api_key=os.environ["MOONSHOT_API_KEY"],
                base_url="https://api.moonshot.ai/v1")

tools = [{
    "type": "function",
    "function": {
        "name": "read_file",
        "description": "Read a text file from the project",
        "parameters": {
            "type": "object",
            "properties": {"path": {"type": "string"}},
            "required": ["path"],
        },
    },
}]

def read_file(path):
    with open(path, encoding="utf-8") as f:
        return f.read()

messages = [{"role": "user", "content": "Explain what main.py does."}]

while True:
    response = client.chat.completions.create(
        model="kimi-k2.7-code",
        messages=messages,
        tools=tools,
        tool_choice="auto",
        max_tokens=8192,
    )
    message = response.choices[0].message
    # Keep the whole assistant turn, including its thinking
    messages.append(message.model_dump(exclude_none=True))

    if not message.tool_calls:
        print(message.content)
        break

    for call in message.tool_calls:
        args = json.loads(call.function.arguments)
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "content": read_file(**args),
        })

A teaching example written for this guide, based on the pattern in Moonshot's quickstart. In real use, limit which files a tool may read and add a cap on the number of loops.

BUILD

Images and video

Kimi K2.7 Code can look at a screenshot or mockup and write code from it. Send the picture inside the message as base64 text.

  • Image links are not supported. Send base64 or an uploaded file.
  • Image types: PNG, JPEG, WebP and GIF.
  • Going above 4K for images or 1080p for video adds time without better results.
  • The whole request must stay under 100 MB. Upload large videos as files instead.
json · a message with an image
{
  "role": "user",
  "content": [
    {"type": "image_url",
     "image_url": {"url": "data:image/png;base64,PASTE_BASE64_HERE"}},
    {"type": "text", "text": "Write the HTML and CSS for this screen."}
  ]
}

No code needed for this in the app: see Visual Coding and Design to Code.

SPEED

HighSpeed

To use the faster version, change one thing: the model name.

What you get

About 180 tokens a second, and up to 260 in short conversations. It is the same model, so answers are the same quality.

What it costs

Double: $1.90 in, $0.38 cached and $8.00 out per million tokens.

The catch

Moonshot says capacity is limited, so speed can vary while it adds more.

More: K2.7 Code HighSpeed.

TOOLS

Use it in a coding tool

You do not have to write your own agent. Moonshot documents how to connect its API to several existing coding tools, including Claude Code, OpenCode and its own Kimi Code CLI.

Example: Claude Code

Claude Code talks to Moonshot's Anthropic-style address. Put these values in the env part of ~/.claude/settings.json, then restart it.

  • Turn thinking on in Claude Code. With it off, Kimi K2.7 Code returns a 400 error.
  • Set every model line. Moonshot warns that skipped ones can fail without a clear message.
  • Remove any old ANTHROPIC_API_KEY value, which can clash.
  • This file holds your key in plain text. Never commit it to a repository.
json · settings.json
{
  "env": {
    "ANTHROPIC_BASE_URL": "https://api.moonshot.ai/anthropic",
    "ANTHROPIC_AUTH_TOKEN": "YOUR_MOONSHOT_API_KEY",
    "ANTHROPIC_MODEL": "kimi-k2.7-code",
    "ANTHROPIC_DEFAULT_OPUS_MODEL": "kimi-k2.7-code",
    "ANTHROPIC_DEFAULT_SONNET_MODEL": "kimi-k2.7-code",
    "ANTHROPIC_DEFAULT_HAIKU_MODEL": "kimi-k2.7-code",
    "ANTHROPIC_DEFAULT_FABLE_MODEL": "kimi-k2.7-code",
    "CLAUDE_CODE_SUBAGENT_MODEL": "kimi-k2.7-code"
  }
}

Adapted from Moonshot's Claude Code guide. Moonshot's own example uses kimi-k3 for most lines and kimi-k2.7-code for the lightest one. This version uses kimi-k2.7-code throughout to keep costs low.

Prefer Moonshot's own tool? See Kimi Code setup. Paying monthly instead of per token? See API vs subscription.

COST

Prices and batch jobs

Per million tokensInputCached inputOutput
Standard$0.95$0.19$4.00
HighSpeed$1.90$0.38$8.00
Batch$0.57$0.114$2.40

On a small screen, swipe the table sideways to see every column.

Estimate a monthly bill with the calculator on the Kimi K2.7 Code page. More: API pricing · rate limits and enterprise pricing

FIX

Common errors

CodeWhat it meansWhat to do
400A setting is not allowedRemove temperature, top_p, n and the penalty settings. Do not turn thinking off. Use tool_choice of auto or none only
400The request is too longShorten the input or lower max_tokens. Input and output together must fit in 262,144 tokens
401The key is wrong or missingCheck the Authorization: Bearer header. A Kimi Code membership key will not work on this address
404Model not foundCheck the spelling: kimi-k2.7-code. Older names such as kimi-k2.5 are retired
429Rate limit reachedSlow down or wait. New accounts are limited to 3 requests a minute until total top-ups reach $10
429Balance too lowTop up your balance on the platform
429Servers are busyWait and retry with growing pauses. Topping up does not help with this one
504Timed outTurn on streaming with "stream": true for long answers

On a small screen, swipe the table sideways to see every column.

From Moonshot's error code page and Kimi K2.7 Code quickstart. More help: Kimi not working?

CHECKLIST

Before you go live

0 of 6 done
Start on a low limit. A new account at Tier 0 allows 1 request at a time and 3 a minute. Total top-ups of $10 raise that to 15 at a time and 100 a minute.
Review what it writes. A coding model can produce code that looks right and is not. Run tests and read changes before they reach production.
FAQ

Kimi K2.7 Code API questions

Use kimi-k2.7-code for the standard model and kimi-k2.7-code-highspeed for the faster version. The base URL is https://api.moonshot.ai/v1.

$0.95 per million input tokens, $0.19 for cached input and $4.00 per million output tokens. HighSpeed is double. Batch jobs cost 60% of the standard price. All prices exclude tax.

The usual causes are sending a temperature or top_p value, turning thinking off, or using a tool_choice other than auto or none. Remove those settings and try again.

No. Moonshot's documentation says Kimi K2.7 Code does not support non-thinking mode, and disabling it returns an error. Use kimi-k2.6 if you need thinking switched off.

Yes. It is OpenAI-compatible. Point the OpenAI SDK at https://api.moonshot.ai/v1 and use your Moonshot API key. An Anthropic-compatible address is also offered for tools such as Claude Code.

No. Kimi Code membership keys are for coding tools and use a different address. For your own apps, create a pay-as-you-go key on Moonshot's API platform.
NEXT

Related guides

Create your key on Moonshot's platform

API keys and billing are on Moonshot AI's own site, never on this page. We are an independent guide.