AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Configuring Context Caching in the Moonshot AI (Kimi) API for Long-Document Workflows

Solène Génard · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

Sending a 150,000-token legal brief or multi-year annual report into an LLM context window is exhilarating right up until the monthly API invoice arrives—or when your users stare at a frozen spinner for 20 seconds waiting for the first token to render. In iterative document auditing, multi-turn contract review, or financial RAG pipelines, repeating the same static context on every prompt turn burns through budget and kills UX.

Moonshot AI (Kimi) offers server-side Context Caching across its flagship models (such as kimi-k3 and kimi-k3.1-pro). At 365Finds, our stance is clear: leaving Context Caching disabled or misconfigured in long-context production environments is operational negligence. When configured correctly, cached input tokens receive a 90% price discount, and time-to-first-token (TTFT) latency drops by upwards of 80%.

Achieving those gains requires understanding Kimi's prefix-matching mechanics, time-to-live (TTL) lifecycle policies, cluster-routing hints, and payload ordering discipline.


How Kimi Context Caching Works

Large language models process input prompts in two distinct computational stages: the prefill phase (computing Key-Value attention matrices for all prompt tokens in parallel) and the generation phase (autoregressive decoding of new tokens). In a 150,000-token document, computing the prefill stage consumes virtually all GPU compute and memory bandwidth, resulting in 10 to 25 seconds of initial silence.

Moonshot AI addresses this with server-side KV caching. When you transmit a massive document prefix, Kimi's serving infrastructure computes the KV tensor states once and stores them in high-throughput host and GPU memory.

Subsequent calls that share the exact token-level prefix bypass the compute-heavy prefill phase entirely. The model engine loads the pre-computed KV tensors directly into attention heads and immediately begins generating response tokens.

Prefix Matching Rule

Kimi's cache lookup uses strict prefix matching. The cache engine builds a deterministic radix tree of tokens starting from token index zero:


TTL Tiers and the Economics of Break-Even

Moonshot AI operates on an implicit caching architecture with configurable Time-To-Live (TTL) tiers:

Cache ConfigurationRetention PeriodCache Write Cost (kimi-k3)Cache Hit Cost (kimi-k3)Standard Uncached Input
Default / 5-minute TTL5 minutes (5m)$3.00 / 1M tokens (¥20)$0.30 / 1M tokens (¥2)$3.00 / 1M tokens (¥20)
Extended / 1-hour TTL1 hour (1h)$6.00 / 1M tokens (¥40)$0.30 / 1M tokens (¥2)$3.00 / 1M tokens (¥20)

Every successful cache hit automatically renews the TTL timer for another full cycle at zero additional write cost.

The 365Finds Lifecycle Rule

We evaluate TTL selection through strict break-even economics:

  1. High-Frequency Chat Loops (5m TTL): If your application supports real-time human chat or rapid agent tool loops where requests arrive within seconds of one another, stay on the default 5-minute TTL. The lower write fee saves overhead, and continuous user engagement resets the 5-minute timer without ever paying for an extended retention window.
  2. Asynchronous Analysis and Spaced Audits (1h TTL): If human reviewers spend 8 to 20 minutes analyzing each AI response before asking the next question, a 5-minute cache will expire between turns. Re-writing a 5-minute cache every 10 minutes turns your application into an expensive cache-thrashing machine. Specifying "ttl": "1h" carries double the initial write cost, but it breaks even after just two subsequent queries and saves up to 85% of input costs over a multi-turn review session.

Payload Architecture: The Golden Order

To guarantee high cache hit ratios, your message payload must follow a strict architectural hierarchy:

[Level 1: Completely Static] -> System Identity & Invariant Instructions
[Level 2: Long Static Context] -> Corporate Knowledge, Legal Dossiers, Regulatory Texts
[Level 3: Stable Tool Definitions] -> Function Schemas & Tool Call Signatures
[Level 4: Dynamic History & Turns] -> User Prompts, Model Outputs, Tool Execution Payloads

Keep levels 1, 2, and 3 byte-for-byte identical across every call. Append conversation turns only at Level 4.


Implementation Guide: Python Integration

You can integrate Kimi Context Caching through the official OpenAI-compatible endpoint (https://api.moonshot.cn/v1 or https://api.moonshot.ai/v1).

Pass prompt_cache_options to specify the TTL tier, and pass prompt_cache_key to pin the request to the specific server cluster holding your cached state.

import os
from openai import OpenAI

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

# Reference document (100k+ tokens)
LARGE_DOCUMENT_CONTEXT = """... [Full 100-page Financial Audit Report] ..."""

def query_kimi_document(
    session_id: str,
    user_query: str,
    conversation_history: list,
    ttl_setting: str = "1h"
):
    # Construct strictly ordered messages
    messages = [
        {
            "role": "system",
            "content": (
                "You are an enterprise financial auditor. Base your findings "
                "strictly on the provided audit dossier.\n\n"
                f"=== DOCUMENT ARCHIVE ===\n{LARGE_DOCUMENT_CONTEXT}"
            )
        }
    ]
    
    # Append dynamic conversation history after the static context
    messages.extend(conversation_history)
    messages.append({"role": "user", "content": user_query})
    
    response = client.chat.completions.create(
        model="kimi-k3",
        messages=messages,
        extra_body={
            # prompt_cache_key ensures sticky routing to the cluster node holding the KV cache
            "prompt_cache_key": f"audit_doc_{session_id}",
            "prompt_cache_options": {
                "mode": "implicit",
                "ttl": ttl_setting
            }
        }
    )
    
    # Inspect telemetry details
    usage = response.usage
    details = getattr(usage, "prompt_tokens_details", None)
    
    cached_tokens = getattr(details, "cached_tokens", 0) if details else 0
    cache_write_tokens = getattr(details, "cache_write_tokens", 0) if details else 0
    
    return {
        "reply": response.choices[0].message.content,
        "total_prompt_tokens": usage.prompt_tokens,
        "cached_tokens": cached_tokens,
        "cache_write_tokens": cache_write_tokens,
        "completion_tokens": usage.completion_tokens
    }

Monitoring Usage and Telemetry

Moonshot AI returns cache execution telemetry directly within the usage.prompt_tokens_details response payload:

{
  "id": "chatcmpl-91b7d8...",
  "object": "chat.completion",
  "model": "kimi-k3",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "The net profit reported in Section 4.2 stands at $48.2 million."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 128450,
    "completion_tokens": 28,
    "total_tokens": 128478,
    "prompt_tokens_details": {
      "cached_tokens": 128200,
      "cache_write_tokens": 0
    }
  }
}

In the response above, 128,200 tokens were processed from cache. For that turn on kimi-k3, input billing drops from $0.385 down to $0.038, and TTFT arrives in under two seconds instead of 16 seconds.


Common Pitfalls and Engineering Checklist

At 365Finds, when reviewing long-context agent pipelines that show unexpectedly low cache hit rates, we look for three classic missteps:

  1. Dynamic Datetime Injection in System Prompts: Placing "Current Time: 2026-11-09 15:55:00" at the top of the system prompt ensures a 0% cache hit rate across every minute of the day. If the model needs temporal grounding, inject the timestamp into the user message at the very end of the array.
  2. Missing prompt_cache_key Routing Hints: In high-concurrency environments, Moonshot AI balances traffic across multiple clusters. Without prompt_cache_key, request 1 may write the cache on Node A, while request 2 lands on Node B, triggering an unwanted cache re-write. Always supply a deterministic hash of the static context or session ID as the key.
  3. Session-Level Model Switching: Switching between kimi-k3 and kimi-k3.1-pro mid-workflow purges cache reuse, as KV tensors cannot be shared across different parameter checkpoints.

References