Kimi K2 Thinking — Python integration and production patterns
Kimi’s explicit reasoning mode for hard planning and tool-calling DAGs. SDK setup, retries, streaming, JSON mode, timeouts and typed outputs.
Minimal Python example
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.moonshot.cn/v1", api_key=os.environ["MOONSHOT_API_KEY"])
resp = client.chat.completions.create(
model="kimi-k2-thinking",
messages=[{"role":"user","content":"Summarize the spec in five bullets"}],
)
print(resp.choices[0].message.content)
Hardening for production
- Retries: tenacity exponential backoff with jitter; total 8 attempts; respect
Retry-After. - Timeouts: connect 10s, read 180s; for 1M-context streaming, async streaming and keep-alive.
- Streaming: stream chunks; render incrementally; abort after N seconds of silence.
- JSON mode: request object schemas; validate with
pydantic; fail closed to a clarification prompt. - Tracing: OpenTelemetry spans for request, tool calls, token counts and redaction decisions.
Async + batch
import asyncio
async def main():
sem = asyncio.Semaphore(16)
tasks = [call_one(prompt, sem) for prompt in prompts]
return await asyncio.gather(*tasks)
Rate limits
Most enterprise keys are token-per-minute × requests-per-minute; batch overnight; split high-cost chains across two keys only with governance control.
Frequently asked questions
How current is this guide for Kimi K2 Thinking?
Pricing, model IDs and availability change monthly. Check the console/provider docs before you deploy; mark every figure “as of Nov 2026” in your internal notes.
Can I use Kimi K2 Thinking for regulated decisions?
Use it as decision support, never as an unattended decision maker. Redact PII, require human approval, keep an evidence trail and match DPA/region to your policy.
Where do Moonshot AI guides fit beside the AI Models Atlas?
The Atlas card answers “should I use it?”; this guide answers “how do I ship it?” — keys, code, agents, pricing, evaluation and failure handling.
Security defaults
Never commit keys; use a secrets manager; rotate after any leak; scope keys to least privilege; keep a blocked-model allowlist/denylist.
← All Knowledge Base minisites · Moonshot AI hub · Prompt Library