DEV Community

zhangjj1988
zhangjj1988

Posted on Originally published at taotok.io

Kimi K2 API Integration: A No-Fluff Getting Started

Kimi K2 API Integration: A No-Fluff Getting Started

Kimi K2 is Moonshot AI's flagship Mixture-of-Experts model, and the first thing developers notice is what it can see. Unlike text-only models, K2 takes images natively through the same chat-completions interface you already know — an image_url array inside the message content is all it takes. If your workload involves long-document QA, screenshot analysis, or an agent swarm that needs to read what's on screen, K2 is worth a serious look.

Setup is deliberately boring. You hit the standard v1 endpoint, send the same request shape used everywhere, and turn on multimodal only when you need it. This guide walks the fastest path from zero to a working request: cURL first, then Python, then the parts — function calling, error handling, token math — that tend to trip people up in production.

What you're working with

  • Provider: Moonshot AI
  • Model: kimi-k2
  • Base URL: https://api.moonshot.cn/v1
  • Context: 256K tokens
  • Inputs: text + images (native)
  • Extras: function calling, streaming, agent-swarm friendly

1. cURL quickstart

export MOONSHOT_API_KEY="sk-..."

curl https://api.moonshot.cn/v1/chat/completions \
  -H "Authorization: Bearer $MOONSHOT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "kimi-k2",
    "messages": [{"role": "user", "content": "Summarize the key points of this contract."}],
    "max_tokens": 1024
  }'
Enter fullscreen mode Exit fullscreen mode

2. Python with the OpenAI SDK

import os
from openai import OpenAI

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

resp = client.chat.completions.create(
    model="kimi-k2",
    messages=[{"role": "user", "content": "Rewrite this error message in plain language: " + err}],
    max_tokens=512,
)
print(resp.choices[0].message.content)
Enter fullscreen mode Exit fullscreen mode

3. Multimodal image input (the K2 difference)

The biggest difference between K2 and text-only models like DeepSeek V4 is that content can be an array of parts:

resp = client.chat.completions.create(
    model="kimi-k2",
    messages=[{
        "role": "user",
        "content": [
            {"type": "text", "text": "What is wrong with this dashboard? Be specific."},
            {"type": "image_url", "image_url": {"url": "https://example.com/dashboard.png"}},
        ],
    }],
)
Enter fullscreen mode Exit fullscreen mode

Pass remote URLs or base64 data URLs. Each image consumes tokens against the 256K window, so keep images reasonably sized and crop where you can. This capability alone is why K2 often wins for document and screen-understanding tasks — for a text-only comparison, see our DeepSeek V4 guide.

4. Streaming

stream = client.chat.completions.create(
    model="kimi-k2",
    messages=[{"role": "user", "content": "Give me 5 tips for prompt engineering."}],
    stream=True,
)
for chunk in stream:
    print(chunk.choices[0].delta.content or "", end="")
Enter fullscreen mode Exit fullscreen mode

5. Function calling

Define tools the usual way, then let the model emit tool_calls:

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

resp = client.chat.completions.create(
    model="kimi-k2",
    messages=[{"role": "user", "content": "What's the weather in Tokyo?"}],
    tools=tools,
)
print(resp.choices[0].message.tool_calls)
Enter fullscreen mode Exit fullscreen mode

Execute the tool, append the result as a tool role message, and loop until the model finishes.

6. Error handling

  • 429 / rate limits: use exponential backoff with jitter; batch if you're polling.
  • Context overflow: 256K is generous but finite — chunk long documents and summarize before you hit the ceiling.
  • Multimodal token spend: images count against the context and the bill; don't send full-resolution screenshots when a thumbnail carries the same information.

7. Production tips

  • Enable multimodal on demand — a text-only fallback for image inputs keeps costs predictable.
  • Cache repeated documents — contracts and specs rarely change; store extracted summaries.
  • Route by task — send vision and long-doc work to K2, simple text to a cheaper model.
  • Monitor separately — track text vs image token usage independently so spikes are explainable.

The extended Kimi K2 guide with more examples is on the taotok.io blog at https://taotok.io/kimi-k2-api-integration, and if you're deciding between K2 and DeepSeek V4, the side-by-side comparison will save you an afternoon.

Top comments (0)