AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Using Kimi for Long Document Analysis and Multi-File Information Extraction

365Finds Editorial
Indexed 11,430 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

Analyzing dense technical documentation, hundred-page financial disclosures, and multi-party commercial contracts frequently overwhelms conventional AI tools constrained by short context windows. Kimi, developed by Moonshot AI, addresses this bottleneck through native ultra-long context reasoning, supporting up to one million tokens in its flagship models alongside robust multi-document processing. This guide outlines how to use Kimi to analyze lengthy individual documents, perform comparative multi-file information extraction, leverage automated context caching in automated pipelines, and enforce verification controls across high-stakes research and enterprise workflows.

Understanding Kimi's Long-Context Architecture and File Limits

Kimi eliminates the need to manually partition documents into fragmented snippets before querying an AI model. Its underlying models—including Kimi K3, powered by a hybrid architecture combining Kimi Delta Attention (KDA) and Gated Multi-Head Latent Attention (MLA)—enable global comprehension across hundreds of thousands of words without losing coherence or missing buried details.

Supported File Formats and Specifications

Kimi accepts a wide range of document and data formats across its web interface, desktop workspace, and developer API:

For developer applications, uploaded files intended for textual extraction are designated with purpose="file-extract". Single files may reach up to 100 MiB. While individual organizations operate within a default 10 GiB storage ceiling, there is no rigid limit on the total count of uploaded files. Users of the Kimi Web and Kimi Work applications can upload up to 50 individual documents into a single analytical session.

Text Extraction Versus Native Visual Inspection

Kimi distinguishes between text extraction and native visual reasoning:

Step-by-Step Workflow for Single Long Document Analysis

Whether reviewing an academic thesis, an annual 10-K SEC filing, or a clinical trial report, analyzing a single comprehensive document with Kimi follows a structured path from upload to targeted verification.

Option A: Interactive Document Exploration via Kimi Web

For research analysts, legal teams, and knowledge workers working in a browser or desktop client:

  1. Access the Interface: Navigate to kimi.ai (or kimi.com) and open a new conversation.
  2. Attach Document: Click the attachment icon or drag and drop a file directly into the prompt box.
  3. Wait for Ingestion: The interface parses the document and presents a file tag confirming that full text extraction is complete.
  4. Generate Initial Orientation: Request a structured overview to establish document scope before diving into specific details.
  5. Drill Down Interactively: Submit targeted inquiries, referencing specific sections, fiscal periods, or technical definitions.

Option B: Programmatic Document Analysis via Kimi API

For developers integrating document analysis into backend pipelines, Kimi provides an OpenAI-compatible API endpoint hosted at https://api.moonshot.cn/v1. The process requires four concise steps:

import os
from pathlib import Path
from openai import OpenAI

# Initialize client pointing to Moonshot API
client = OpenAI(
    api_key=os.environ["MOONSHOT_API_KEY"],
    base_url="https://api.moonshot.cn/v1",
)

# Step 1: Upload document for text extraction
uploaded_file = client.files.create(
    file=Path("annual_report_2025.pdf"),
    purpose="file-extract",
)

# Step 2: Retrieve extracted text content
extracted_text = client.files.content(file_id=uploaded_file.id).text

# Step 3: Inject extracted text into system messages
system_persona = (
    "You are Kimi, an AI assistant developed by Moonshot AI. Provide accurate, "
    "well-structured, and verified answers based strictly on provided documentation."
)

messages = [
    {"role": "system", "content": system_persona},
    {"role": "system", "content": extracted_text},
    {
        "role": "user",
        "content": "Provide an executive summary of key revenue drivers and identify the top three operational risks disclosed in this filing.",
    },
]

# Step 4: Execute inference using Kimi K3
response = client.chat.completions.create(
    model="kimi-k3",
    messages=messages,
    temperature=0.3,
)

print(response.choices[0].message.content)

[!IMPORTANT] When querying documents via the API, always fetch the extracted string and pass it directly inside messages. Never submit the raw file_id as the message content, and do not inline large documents as base64 strings, which causes unnecessary token overhead and bypasses text extraction optimizations.

Core Query Patterns for In-Depth Single Document Analysis

To maximize extraction quality from a massive text, use specific prompting angles:

Multi-File Information Extraction and Comparative Analysis

One of Kimi's greatest operational advantages is its capacity to evaluate multiple dense documents simultaneously. Rather than analyzing files in isolation and manually compiling findings, you can ingest several files at once to generate cross-document syntheses, contract redlines, and longitudinal trend analyses.

Ingestion Pattern for Multi-File Analysis

In the API, each distinct document is passed as an independent system message positioned at the beginning of the messages array:

def prepare_multi_file_context(file_paths: list[str]) -> list[dict]:
    """Uploads multiple files and generates a system message for each extracted document."""
    file_messages = []
    for path in file_paths:
        file_obj = client.files.create(file=Path(path), purpose="file-extract")
        file_text = client.files.content(file_id=file_obj.id).text
        file_messages.append({"role": "system", "content": file_text})
    return file_messages

# Ingest multiple annual filings or competitor reports
docs = ["filing_2023.pdf", "filing_2024.pdf", "filing_2025.pdf"]
file_messages = prepare_multi_file_context(docs)

multi_doc_messages = [
    *file_messages,
    {"role": "system", "content": system_persona},
    {
        "role": "user",
        "content": (
            "Compare financial performance across 2023, 2024, and 2025. "
            "Construct a Markdown table comparing Total Revenue, Operating Margin, "
            "and Free Cash Flow, followed by an explanation of major margin variances."
        ),
    },
]

completion = client.chat.completions.create(
    model="kimi-k3",
    messages=multi_doc_messages,
)
print(completion.choices[0].message.content)

High-Value Multi-File Use Cases

Analyzing multiple documents in a single context window unlocks several powerful workflows:

Use CaseInput DocumentsExtraction and Synthesis ObjectiveOutput Format
Multi-Year Financial TrendsConsecutive annual reports (10-K, audited statements)Identify revenue growth trajectories, shifting debt liabilities, and evolving risk factors over timeComparative metrics table and variance analysis
Contract Redlining and Vendor AlignmentStandard Master Services Agreement (MSA) vs. Counterparty DraftLocate deviations in liability caps, intellectual property rights, indemnification, and payment termsClause-by-clause discrepancy matrix
Competitive BenchmarkingProduct whitepapers, technical specifications, or datasheetsCompare architectural throughput, latency, security compliance, and licensing constraintsFeature parity checklist with trade-off evaluation
Cross-Disciplinary Literature SynthesisMultiple scientific papers exploring related hypothesesExtract consensus methodologies, isolate conflicting experimental results, and identify literature gapsSystematic thematic literature review

Constructing Effective Comparative Prompts

When comparing multiple documents, open-ended questions like "tell me what is different" often yield generic responses. Formulate prompts that enforce explicit comparison axes:

Optimizing Latency and Cost with Context Caching

Submitting dozens of pages across multiple conversational turns can become computationally expensive if the entire document text is reprocessed on every request. Kimi resolves this through an automated Context Caching engine.

How Kimi Context Caching Operates

Context Caching stores the processed representation of an extensive input prefix on server clusters. When subsequent requests share the identical initial context, Kimi skips reprocessing the prefix and charges a fraction of the standard input rate.

Architectural Rule: Maintain Prefix Stability

To maximize cache hits, the layout of your messages array must remain consistent. Keep the static parts of your prompt—document contents, system personas, and formatting rules—at the beginning of the list, and append conversational turns strictly at the end:

# Fixed document prefix (cached across turns)
base_context = [
    *file_messages,
    {"role": "system", "content": system_persona},
    {"role": "system", "content": "Format all tabular data in GitHub Flavored Markdown."},
]

# Turn 1
conversation = list(base_context)
conversation.append({"role": "user", "content": "What are the total assets listed?"})
turn1_reply = client.chat.completions.create(model="kimi-k3", messages=conversation)

# Turn 2: Preserves original prefix, hits context cache
conversation.append({"role": "assistant", "content": turn1_reply.choices[0].message.content})
conversation.append({"role": "user", "content": "How does that compare to cash reserves?"})
turn2_reply = client.chat.completions.create(model="kimi-k3", messages=conversation)

# Check cache utilization in token usage metadata
usage = turn2_reply.usage
cached_tokens = getattr(usage.prompt_tokens_details, "cached_tokens", 0)
print(f"Total Prompt Tokens: {usage.prompt_tokens}")
print(f"Cached Tokens Reused: {cached_tokens}")

Context Caching Versus Retrieval-Augmented Generation (RAG)

Understanding when to feed raw documents into Kimi's context window versus deploying an external vector RAG architecture is key to balancing operational simplicity and cost:

Evaluation DimensionKimi Long-Context with Context CachingTraditional Chunk-Based RAG
Contextual IntegrityComplete holistic context; zero retrieval misses; preserves multi-page tables and cross-chapter dependenciesProne to chunk-boundary slicing; may miss nuances spread across disparate chapters
Engineering ComplexityMinimal: upload text and prompt the model; no embeddings, chunkers, or vector databasesHigh: requires embedding models, chunking heuristics, vector index tuning, and rerankers
Latency ProfileSub-5-second TTFT once prefix cache is warm; predictable response timesFast initial retrieval, but latency accumulates across multi-stage search and reranking
Cost DynamicsUp to 90% cheaper on warm prefix; cost-effective for deep, repeated queries on fixed document setsLower raw per-query cost across massive document corpora, but overhead in maintaining vector infrastructure
Optimal ApplicationAnalyzing targeted document bundles (1 to 50 files, financial audits, legal review, diligence)Enterprise-wide search across millions of disconnected internal tickets, emails, or wiki pages

Prompting Best Practices and Output Governance

Achieving reliable results when analyzing hundreds of pages requires disciplined prompt construction, clear answer constraints, and systematic factual verification.

Constraining Answers with Explicit Rules

Unconstrained models can produce overly verbose narratives. You can enforce concise, auditable responses by appending a dedicated rule set to your system prompt:

structured_rules = """
Adhere strictly to these response constraints:
1. Provide a maximum of 5 bullet points.
2. For every assertion or metric, cite the exact source section, page number, or table title.
3. If an answer cannot be deduced directly from the uploaded files, state explicitly: "Information not present in source documents."
4. Do not extrapolate, speculate, or introduce external industry generalities.
"""

governed_messages = [
    *file_messages,
    {"role": "system", "content": system_persona},
    {"role": "system", "content": structured_rules},
    {"role": "user", "content": "Summarize the customer churn rate and retention benchmarks."},
]

Verifying High-Stakes Financial and Legal Facts

While Kimi's long-context attention minimizes retrieval hallucinations, mission-critical decisions require systematic verification:

Storage and File Lifecycle Management

Uploaded files remain stored under your account to facilitate ongoing extraction and caching, counting against your organization's storage quota (default 10 GiB). Once analysis is complete, clean up ephemeral files to ensure sufficient capacity for future jobs:

# Remove a specific completed file
client.files.delete(file_id=uploaded_file.id)

# Batch cleanup: List and delete all transient extraction files
all_files = client.files.list()
for file_record in all_files.data:
    client.files.delete(file_id=file_record.id)

Platform Options, Access Tiers, and Enterprise Privacy

Moonshot AI offers multiple deployment paths and privacy safeguards tailored to individual analysts, developer teams, and regulated organizations.

Choosing Between Consumer Workspaces and Developer APIs

Enterprise Data Protection and Zero Data Retention (ZDR)

For organizations handling sensitive intellectual property, proprietary financial statements, or confidential customer agreements, data exposure is a primary concern:

Sources