How to Generate Code Snippets with kimi-cli: Interactive and Scripted Methods

To generate code snippets with kimi-cli, launch an interactive session with the kimi command and describe your requirements in natural language; the CLI processes the request through its Kimi Soul loop and returns syntax-highlighted code via the terminal interface.

kimi-cli is the official Python-based command-line interface for interacting with MoonshotAI's large language models. It functions as an interactive agent that synthesizes code on demand, allowing developers to generate, display, and persist code snippets directly from their terminal without context switching.

How the kimisoul.py Loop Handles Code Generation

The core of code generation resides in src/kimi_cli/soul/kimisoul.py, which implements the Kimi Soul loop. This loop accepts natural-language prompts and routes them to the configured LLM provider via kosong.generate.

When you submit a prompt containing keywords like "code", "function", or "snippet", the system processes it through the default system prompt defined in src/kimi_cli/agents/default/system.md. This prompt instructs the model to "read them, understand them and do the user requested" and to "use tools when needed."

The LLM response includes a code snippet object accessible via message.codeSnippet. The shell UI component in src/kimi_cli/ui/shell/assistant_message.py extracts this object and renders it with syntax highlighting using the rich library.

Generating Code Snippets Interactively

To start generating code, run the kimi command to enter the interactive shell:

$ kimi

Once inside the session, type your request naturally:

> generate a Python function that computes the nth Fibonacci number

The assistant returns a formatted code block:

def fibonacci(n: int) -> int:
    """Return the nth Fibonacci number."""
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
    return a

Persisting Snippets to Disk

To save generated code without leaving the CLI, request a file write operation. The file tool implemented in src/kimi_cli/tools/file/write.py handles the persistence automatically:

> write the above function to file src/utils/fib.py

Non-Interactive Code Generation

For automation and scripting, pipe prompts directly to the CLI using the --no-interactive flag:

$ echo "create a Bash script that backs up ~/projects" | kimi --no-interactive

This mode processes the input through the same kosong.generate pipeline but returns the result directly to stdout, making it suitable for CI/CD pipelines and shell scripts.

Multi-Line Prompts and Complex Requests

For complex code requiring multiple lines or detailed specifications, use Ctrl-J (or Alt-Enter) to insert newlines without submitting the prompt. This allows you to paste full program requirements or structured specifications:

> generate a Rust program that reads stdin and prints JSON-escaped output

# press Ctrl-J to add the next line without exiting

> (include error handling)

The prompt-processing logic in src/kimi_cli/cli/__init__.py handles these multi-line inputs, ensuring the entire context reaches the LLM provider as a single coherent request.

Session State and Context Management

Each generated snippet is stored in the session's Context object defined in src/kimi_cli/soul/context.py. This preserves your conversation history and any code blocks for later reference or modification within the same session.

If you reference "the above function" or "the previous snippet," the context manager retrieves the relevant message.codeSnippet instances from the conversation history, enabling iterative refinement of generated code.

Web API Integration

The same generation mechanism powers the web interface. The HTTP endpoint POST /{session_id}/generate-title in src/kimi_cli/web/api/sessions.py (lines 749-791) uses an analogous flow to produce snippets via API calls, while src/kimi_cli/tools/web/search.py (lines 143-155) demonstrates how snippet data is formatted for web display.

Summary

Frequently Asked Questions

How do I save generated code to a file?

Request a file write operation in natural language (e.g., "write this to file.py"). The CLI invokes the write_file tool from src/kimi_cli/tools/file/write.py automatically, persisting the snippet to disk without requiring you to copy-paste.

Can I use kimi-cli in scripts without interactive mode?

Yes. Pipe your prompt to kimi --no-interactive to receive the generated code directly in stdout. This bypasses the interactive shell UI in src/kimi_cli/ui/shell/assistant_message.py while still processing through the kosong.generate provider.

How does the syntax highlighting work?

The terminal UI extracts the message.codeSnippet object from the LLM response and passes it to the rich library for rendering. This occurs in src/kimi_cli/ui/shell/assistant_message.py, which identifies the programming language and applies appropriate color highlighting.

Where are snippets stored during a session?

Generated snippets persist in the session's Context object managed by src/kimi_cli/soul/context.py. This enables references to "the previous code" or "that function" in subsequent prompts, as the context maintains the full conversation history including all message.codeSnippet instances.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →