Skip to content
,

Kimi API Tutorial in Python: K3.1 Pro, Pricing, Tools and Claude Code

12โ€“18 minutes
Woman in a server room holding a tablet with a KIMI API card, hook $2 input Kimi K3.1 Pro API

Moonshot AI’s Kimi API now runs on Kimi K3.1 Pro, a 1M-token open-weight model that speaks both the OpenAI and Anthropic API formats. That means you can call it with the OpenAI Python SDK you already use.

This guide walks you through the whole thing in Python: the key, the right platform, the current model ids, streaming, tool calls, thinking mode, caching, prices, limits and errors.

I checked every model id, price and limit against the official Kimi platform docs on 4 December 2026, so you can copy the code with confidence.

TLDR

  • Platform: outside mainland China use platform.kimi.ai (the old platform.moonshot.ai now redirects there). Base URL: https://api.moonshot.ai/v1.
  • Models: kimi-k3.1-pro (flagship), kimi-k3.1-pro-highspeed (2-3x faster) and kimi-k3. K2 models retire by the end of December 2026.
  • Price: K3.1 Pro costs $2 input / $10 output per 1M tokens, with cached input at $0.20.
  • Thinking: always on. You tune it with reasoning_effort set to low, high or max.
  • Coding agents: an Anthropic-compatible endpoint at https://api.moonshot.ai/anthropic works with Claude Code.

What the Kimi API Is and When to Use It

The Kimi API is Moonshot AI’s pay-as-you-go developer platform. It gives you the same models that power kimi.com, but billed per token with no subscription.

It supports three request formats, so you rarely need a new SDK:

  • Chat Completions API: OpenAI-compatible. Works with the official openai Python and Node.js SDKs.
  • Responses API: also OpenAI-compatible, for text, JSON output and function tools.
  • Messages API: Anthropic-compatible, for the anthropic SDK, Claude Code and similar tools.

Kimi is a good pick when you want a 1M-token context, strong coding and agent skills, and a lower price than most closed flagships. The weights for K3.1 Pro are also public on Hugging Face, so you can self-host later if you need to.

Note: a Kimi membership or Kimi Code plan does not include API credit. The help center says API keys, Kimi Code keys and memberships are separate, and balances do not transfer between them.

International vs China Platform: Which One to Use

Moonshot runs separate regional platforms. Each has its own accounts, balances and keys, and they cannot be mixed.

Item International Mainland China
Console platform.kimi.ai (platform.moonshot.ai redirects here) platform.kimi.com
OpenAI-style base URL https://api.moonshot.ai/v1 https://api.moonshot.cn/v1
Anthropic-style base URL https://api.moonshot.ai/anthropic Check the China console docs
Who should use it Everyone outside mainland China Developers with a mainland China account

Warning: a key from one platform sent to the other platform’s base URL returns 401 invalid_authentication_error. This is the most common Kimi setup mistake, so check it first.

Current Kimi Model IDs (December 2026)

The latest release is Kimi K3.1 Pro. It went live on the API on 23 October 2026, and Moonshot published its weights on Hugging Face in early November. It is a post-trained version of Kimi K3, which launched in July 2026.

Model id Status Context Best for
kimi-k3.1-pro Current flagship 1,048,576 tokens Coding agents, 3D work, finance research, deep reasoning
kimi-k3.1-pro-highspeed Current 1,048,576 tokens Same model, about 2-3x faster output, double the price
kimi-k3 Previous flagship 1,048,576 tokens Long-horizon coding and knowledge work
kimi-k2.7-code, kimi-k2.7-code-highspeed, kimi-k2.6 Closed to new users 262,144 tokens Legacy only, retiring late December 2026
moonshot-v1-*, kimi-k2-thinking, kimi-latest and other K2 previews Deprecated n/a Migrate now

All three K3 models accept text, image and video input. If old code still calls kimi-latest or moonshot-v1-128k, switch it to kimi-k3.1-pro.

Get a Kimi API Key and Set Up Python

You need Python 3.9 or later and the OpenAI SDK version 1.0 or later, as the official quickstart states. The K3.1 Pro model unlocks after your first top-up of at least $1.

  1. Sign in to the platform. Open platform.kimi.ai (or platform.kimi.com for mainland China) and create an account.
  2. Top up at least $1. Go to the billing page and add credit. A $1 minimum is needed to use the API, and you get a $5 voucher once your total top-up reaches $5.
  3. Create a key. Open API Keys, create a new key and copy it right away.
  4. Save it as an environment variable. On macOS or Linux run export MOONSHOT_API_KEY="your-key". On Windows PowerShell use $env:MOONSHOT_API_KEY="your-key".
  5. Install the SDK. Run python3 -m pip install --upgrade 'openai>=1.0'. Add anthropic too if you want the Messages API.
  6. Test the key. Run the first example below. A short reply means the key, platform and model all match.

Tip: never hard-code the key. Keep it in an environment variable or a secrets manager, and add any .env file to .gitignore.

Your First Kimi API Call (OpenAI SDK and curl)

Point the OpenAI client at the Kimi base URL and pass a Kimi model id. Everything else looks like a normal OpenAI call.

import os
from openai import OpenAI

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

completion = client.chat.completions.create(
    model="kimi-k3.1-pro",
    messages=[
        {"role": "system", "content": "You are a helpful Python tutor."},
        {"role": "user", "content": "Explain list comprehensions in two sentences."},
    ],
)

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

The same request in curl looks like this:

curl https://api.moonshot.ai/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $MOONSHOT_API_KEY" \
  -d '{
    "model": "kimi-k3.1-pro",
    "messages": [{"role": "user", "content": "Say hello in five words."}]
  }'

Note: K3.1 Pro fixes temperature at 1.0, top_p at 0.95 and n at 1. The docs say to leave these fields out of your request.

Streaming Kimi Responses With Reasoning Output

Because K3.1 Pro always thinks first, a stream gives you two kinds of text. The reasoning_content deltas arrive first, then the normal content deltas carry the final answer.

The OpenAI SDK has no typed field for reasoning_content, so read it with getattr:

import os
from openai import OpenAI

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

stream = client.chat.completions.create(
    model="kimi-k3.1-pro",
    messages=[{"role": "user", "content": "Why is the sky blue? Keep it short."}],
    stream=True,
    stream_options={"include_usage": True},
)

answer_started = False
for chunk in stream:
    if not chunk.choices:
        if chunk.usage:
            print("\n\nUsage:", chunk.usage)
        continue
    delta = chunk.choices[0].delta
    reasoning = getattr(delta, "reasoning_content", None)
    if reasoning:
        print(reasoning, end="", flush=True)
    if delta.content:
        if not answer_started:
            print("\n\n--- Answer ---\n")
            answer_started = True
        print(delta.content, end="", flush=True)

Streaming also protects you from the gateway timeout. Kimi returns a 504 if the server sends nothing for 900 seconds, which can happen on long non-streaming jobs.

Thinking Mode and reasoning_effort

Both kimi-k3.1-pro and kimi-k3 always reason, and you cannot switch thinking off. The old thinking parameter is not supported on these models.

Instead, you control how hard the model thinks with a top-level field:

  • “low”: fastest and cheapest. Good for simple Q&A, routing and short edits.
  • “high”: a middle ground for most app traffic.
  • “max”: the default. Best for proofs, hard bugs and long agent runs.
completion = client.chat.completions.create(
    model="kimi-k3.1-pro",
    reasoning_effort="low",
    max_tokens=16000,
    messages=[{"role": "user", "content": "Is 221 a prime number?"}],
)

msg = completion.choices[0].message
print("Reasoning:", (getattr(msg, "reasoning_content", None) or "")[:300])
print("Answer:", msg.content)

Reasoning tokens count toward max_tokens and are billed like output. The docs suggest max_tokens of 16,000 or more for thinking tasks so the answer is not cut off. The default max_completion_tokens is 131,072.

Warning: in multi-turn chats, append the whole assistant message (including reasoning_content) back to messages. Kimi calls this Preserved Thinking, and it is always on for K3 models. Keeping only the text answer breaks tool loops.

If you want to compare how other providers price thinking tokens, my guide to reasoning effort settings and API cost covers OpenAI, Claude and Gemini.

Tool Calls in Python (Function Calling)

Kimi uses the standard OpenAI tools format. The model returns tool_calls, you run the function, and you send the result back as a tool message with the matching tool_call_id.

Here is a complete, runnable loop with a fake weather function:

import os
import json
from openai import OpenAI

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

def get_weather(city):
    # Replace with a real weather API call
    return {"city": city, "temp_c": 21, "sky": "clear"}

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get the current weather for a city.",
        "parameters": {
            "type": "object",
            "properties": {"city": {"type": "string", "description": "City name"}},
            "required": ["city"],
        },
    },
}]

messages = [{"role": "user", "content": "What is the weather in Paris and Tokyo?"}]

for step in range(5):
    completion = client.chat.completions.create(
        model="kimi-k3.1-pro",
        messages=messages,
        tools=tools,
        max_tokens=16000,
    )
    message = completion.choices[0].message
    messages.append(message)  # keep the full message, reasoning included

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

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

A few extras are worth knowing:

  • tool_choice=”required”: forces at least one tool call on the first turn.
  • Dynamic tool loading: you can add a tool definition in a system message mid-chat, and it applies from that point on.
  • Official tools: Kimi hosts ready-made tools (date, web search and more) through its Formula endpoints. The docs currently say web search is being updated and is not recommended for production.

Context Caching: Pay 10% for Repeated Prompts

Kimi caches repeated request prefixes automatically. You do not create a cache by hand. When a prefix hits, that part of the input costs one tenth of the normal price.

Each new prefix is written once, and the write is billed as its own line item. You can pick one of two lifetimes:

  • 5m (default): write costs the same as normal input. Each hit resets the 5-minute timer.
  • 1h: write costs double the input price, but the entry lives for an hour. Pick it when requests come more than 5 minutes apart.

The OpenAI SDK has no named argument for Kimi’s prompt_cache_options, so pass it through extra_body:

import os
from pathlib import Path
from openai import OpenAI

client = OpenAI(api_key=os.environ["MOONSHOT_API_KEY"], base_url="https://api.moonshot.ai/v1")
docs = Path("product-docs.md").read_text(encoding="utf-8")

for question in ["Which login methods are supported?", "How do refunds work?"]:
    completion = client.chat.completions.create(
        model="kimi-k3.1-pro",
        messages=[
            {"role": "system", "content": docs},      # stable prefix first
            {"role": "user", "content": question},    # changing part last
        ],
        extra_body={"prompt_cache_options": {"mode": "implicit", "ttl": "1h"}},
    )
    u = completion.usage
    details = getattr(u, "prompt_tokens_details", None)
    cached = getattr(details, "cached_tokens", 0) if details else 0
    written = getattr(details, "cache_write_tokens", 0) if details else 0
    print(question, "| input:", u.prompt_tokens, "| cached:", cached, "| written:", written)

To get good hit rates, put the system prompt, tool definitions and documents at the start, and the user question at the end. Keep timestamps and random ids out of the prefix. Caches are shared inside your organization and cannot be cleared by hand.

For the same idea across other vendors, see prompt caching for Claude, OpenAI and Gemini.

Kimi API Prices and a Worked Cost Example

Kimi bills per million tokens (MTok), pay as you go, with taxes added at checkout. These are the official prices on the pricing page as of 4 December 2026.

Model Input Output Cached input Cache write 5m Cache write 1h
kimi-k3.1-pro $2.00 $10.00 $0.20 $2.00 $4.00
kimi-k3.1-pro-highspeed $4.00 $20.00 $0.20 $4.00 $8.00
kimi-k3 $3.00 $15.00 $0.30 $3.00 $6.00
kimi-k2.7-code (legacy) $0.95 $4.00 $0.19 n/a n/a
kimi-k2.6 (legacy) $0.95 $4.00 $0.16 n/a n/a

Interestingly, the older kimi-k3 costs more than the newer K3.1 Pro. Unless you have a reason to stay on K3, the newer model is both better and cheaper.

Kimi API pricing page showing kimi-k3.1-pro at $2 input and $10 output per million tokens with $0.20 cached input
Official Kimi API Model Inference Pricing page, K3 series (checked 4 Dec 2026).

The Batch API runs kimi-k3.1-pro and kimi-k3 jobs at 60% of the standard price for work that does not need a live answer. File upload and text extraction are free for now, but the extracted text you send to the model is billed as input.

Worked example: a support bot on K3.1 Pro

Say your bot handles 1,000 questions. Each request sends a 20,000-token prompt (an 18,000-token help-docs prefix plus a 2,000-token question and chat history). Each reply uses 1,500 output tokens, reasoning included.

Scenario Math Cost
No cache hits 20M input x $2 + 1.5M output x $10 $40 + $15 = $55.00
Cache hits (5m TTL, steady traffic) First call writes 18K once ($0.036). Then 999 calls x (18K cached x $0.20 + 2K x $2 + 1.5K out x $10) about $22.63
Batch API, no cache $55 x 60% $33.00

So caching cuts this bill by roughly 59%. The output tokens are now the biggest cost, so lowering reasoning_effort on easy questions is the next lever.

To see how this stacks up against other providers, check my AI API pricing comparison.

Kimi API Rate Limits and Tiers

Your tier depends on your cumulative top-up, not your monthly spend. Vouchers do not count toward it.

Tier Total top-up Concurrency RPM TPM TPD Web search QPS
Tier0 $1 1 3 500,000 1,500,000 1
Tier1 $10 15 100 2,000,000 Unlimited 3
Tier2 $20 40 100 3,000,000 Unlimited 5
Tier3 $100 50 200 3,000,000 Unlimited 10
Tier4 $1,000 60 200 4,000,000 Unlimited 20
Tier5 $3,000 100 300 5,000,000 Unlimited 50

Tier0 allows only 3 requests per minute and 1 at a time, which is too tight for any agent. A $10 total top-up moves you to Tier1 with 100 RPM, so most developers should start there.

Moonshot also says limits may be lowered when the cluster is busy. If its systems flag abnormal activity, a risk-control limit kicks in and cannot be lifted. My LLM API rate limits guide explains how tiers work at other providers.

Using Kimi in Claude Code and Other Coding Agents

Yes, an Anthropic-compatible endpoint exists. Kimi’s Messages API lives at https://api.moonshot.ai/anthropic, and the docs include setup guides for Claude Code, Codex, Kimi Code CLI, OpenCode, OpenClaw and Hermes Agent.

Claude Code setup

  1. Install Claude Code. Follow my Claude Code install guide if you have not yet.
  2. Open the settings file. Edit ~/.claude/settings.json and add an env block.
  3. Add every model variable. Kimi’s guide sets the base URL, the auth token, and all model tiers (main, Opus, Sonnet, Haiku, Fable and subagent) to kimi-k3[1m]. Missing tiers make background tasks fail silently.
  4. Set the compact window and effort. Use CLAUDE_CODE_AUTO_COMPACT_WINDOW of 1000000 and CLAUDE_CODE_EFFORT_LEVEL of max.
  5. Restart and check. Start Claude Code, type /status, and confirm the base URL and model match.
Kimi docs settings.json env block for Claude Code with ANTHROPIC_BASE_URL https://api.moonshot.ai/anthropic and every model tier set to kimi-k3[1m]
Official Use Kimi in Claude Code guide, settings.json example (checked 4 Dec 2026).

Warning: this file holds your key in plain text. Do not commit it to git. Also, the env block in settings.json overrides any same-named variable in your terminal.

Calling the Messages API from Python

You can also use the official anthropic SDK. Kimi’s curl examples send the key as a Bearer token, so pass it as auth_token:

import os
import anthropic

client = anthropic.Anthropic(
    auth_token=os.environ["MOONSHOT_API_KEY"],
    base_url="https://api.moonshot.ai/anthropic",
)

message = client.messages.create(
    model="kimi-k3.1-pro",
    max_tokens=2048,
    messages=[{"role": "user", "content": "Write a Python one-liner to reverse a string."}],
)

for block in message.content:
    if block.type == "text":
        print(block.text)

On the Messages API, caching TTL is set with a top-level cache_control field, such as {"type": "ephemeral", "ttl": "1h"}. The same marker inside a message is ignored.

Troubleshooting Kimi API Errors

Kimi returns a JSON body with error.type and error.message. These are the real messages from the official error page, with the fix for each.

HTTP error.type / message Fix
400 content_filter: “The request was rejected because it was considered high risk” Reword the prompt. Input or output tripped the safety filter.
400 invalid_request_error: “Input token length too long” Trim input below the context window (1,048,576 for K3 models).
401 invalid_authentication_error: “Invalid Authentication” Check the key and the platform. A China key on api.moonshot.ai (or the reverse) fails here.
401 incorrect_api_key_error: “Incorrect API key provided” Key missing or wrong. Confirm MOONSHOT_API_KEY is set in the same shell.
403 permission_denied_error: “Your IP is not allowed to access this organization” Ask your org admin to add your IP to the allowlist.
404 resource_not_found_error: “Model not found…” Fix the model id spelling, top up to unlock K3.1 Pro, or set base_url (without it the SDK calls OpenAI).
429 engine_overloaded_error: “The engine is currently overloaded” Server-side load. Wait for Retry-After and back off. Topping up does not help.
429 rate_limit_reached_error: RPM, TPM, TPD or concurrency limit reached Slow down, reduce parallel calls, or raise your tier.
429 exceeded_current_quota_error: “Account balance is insufficient…” Top up your balance.
499 client_closed_request A proxy or your client cut the stream. Raise timeouts and keep-alive.
504 Gateway Time-out No output for 900 seconds. Use stream=True.

Other common problems

  • Tool loop forgets context: you appended only content. Append the full assistant message object instead.
  • reasoning_content raises AttributeError: use getattr(msg, "reasoning_content", None), since the SDK type lacks that field.
  • Image URL rejected: K3.1 Pro does not accept public image URLs. Send base64 or an ms:// file id, with content as an array.
  • Old model id stopped working: kimi-latest, moonshot-v1-* and kimi-k2-thinking are deprecated. Switch to kimi-k3.1-pro.

Frequently Asked Questions

Is the Kimi API free?

No. It is pay as you go, and you must top up at least $1 to start. Once your total top-up reaches $5, you get a $5 voucher.

What is the latest Kimi model id?

As of 4 December 2026 it is kimi-k3.1-pro, plus the faster kimi-k3.1-pro-highspeed. Both have a 1,048,576-token context window.

Can I turn off thinking on Kimi K3.1 Pro?

No. K3.1 Pro and K3 always reason. You can lower the cost and delay with reasoning_effort="low".

Is platform.moonshot.ai the same as platform.kimi.ai?

Yes. platform.moonshot.ai now redirects to platform.kimi.ai, and the API base URL is still https://api.moonshot.ai/v1. The mainland China platform is separate and uses https://api.moonshot.cn/v1.

Does my Kimi membership include API credit?

No. Kimi memberships, Kimi Code and the API platform are separate products. Their keys and balances do not transfer.

Can I use Kimi with Claude Code?

Yes. Set ANTHROPIC_BASE_URL to https://api.moonshot.ai/anthropic and map every model tier to a Kimi model in ~/.claude/settings.json, as shown above.

What happens to K2 models?

New accounts lost access to K2 models on 31 October 2026. Moonshot plans to retire all K2 models by the end of December 2026, so migrate existing code now.

Sources

Free weekly email

Get new AI guides every week

One short weekly email with our newest local AI, ComfyUI and AI tool guides. No spam, no pop-ups, just the good stuff.

Free. Unsubscribe anytime in one click. We only use your email to send this newsletter. See our privacy policy.

Woman in a server room holding a tablet with a KIMI API card, hook $2 input Kimi K3.1 Pro API