Kimi Code Setup
This tutorial walks you through installing, configuring, and using Kimi Code — the open-weight AI coding agent from Moonshot AI with 256K context and Agent Swarm capabilities.
Time Required: 25 minutes
Prerequisites: Terminal familiarity, Kimi API account
Overview
By the end of this tutorial, you will have:
- Installed Kimi Code on your machine
- Configured API access and project settings
- Run your first agentic coding session
- Experimented with Agent Swarm capabilities
- Set up vision-to-code workflows
Step 1: Create Kimi Account (5 minutes)
Sign Up
- Visit platform.moonshot.cn (international) or your regional endpoint
- Click Sign Up and complete registration
- Verify email address
Get API Key
- Navigate to API Keys → Create API Key
- Name your key (e.g., "Development Environment")
- Copy the API key (starts with your account prefix)
- Important: Store securely — key shown only once
Check Account Balance
- Go to Billing → Overview
- Note current balance and rate limits
- Set up billing alerts if needed
Pricing Reference:
- Input: $0.60 per million tokens
- Output: $2.50 per million tokens
- Vision: Same as text (no premium)
Step 2: Installation (3 minutes)
Via npm
npm install -g @moonshotai/kimi-code
Via pip
pip install kimi-code
Verify Installation
kimi --version
# Output: kimicode version 1.x.x
kimi --help
# Shows available commands and modes
Step 3: Authentication (2 minutes)
Configure API Key
# Interactive login
kimi login
# Enter API key when prompted
# Or set environment variable
export KIMI_API_KEY="your-api-key-here"
# Verify authentication
kimi whoami
# Output: Logged in as user@example.com
# Balance: $50.00
# Rate limit: 100 RPM
Test Connection
kimi test
# Output: ✓ Connected to Kimi API
# ✓ Model: kimi-k2.5
# ✓ Context: 256K tokens
# ✓ Ready to use
Step 4: Project Configuration (5 minutes)
Initialize Project
cd /path/to/your-project
# Create Kimi configuration
mkdir -p .kimi
Create Configuration File
cat > .kimi/config.yaml << 'EOF'
project:
name: "My Project"
description: "Full-stack web application"
model:
default: "kimi-k2.5"
context_window: 256000
modes:
instant:
temperature: 0.6
thinking: false
use_case: "Quick lookups, simple tasks"
thinking:
temperature: 1.0
thinking: true
reasoning_budget: 32000
use_case: "Complex problem solving"
agent:
temperature: 0.8
tools: true
use_case: "Multi-step workflows"
swarm:
max_agents: 10
coordination: auto
use_case: "Parallel task execution"
governance:
audit_logging: true
log_level: info
token_budget_per_session: 500000
require_approval_for:
- git_push
- npm_publish
- database_migration
context:
exclude:
- node_modules/
- .git/
- dist/
- coverage/
- "*.log"
include:
- README.md
- package.json
- tsconfig.json
- src/**/*.ts
cost_control:
warn_threshold: 5.00
hard_limit: 20.00
alert_email: "dev@company.com"
EOF
Create Project Context
cat > .kimi/CONTEXT.md << 'EOF'
# Project Context
## Overview
Modern web application built with React and Node.js.
## Tech Stack
- **Frontend**: React 18, TypeScript, Tailwind CSS, Vite
- **Backend**: Node.js, Express, TypeScript
- **Database**: PostgreSQL with Prisma ORM
- **Testing**: Jest, React Testing Library, Playwright
- **State**: Zustand for client state
- **API**: tRPC for type-safe APIs
## Architecture
frontend/ src/ components/ # Reusable UI pages/ # Route components hooks/ # Custom hooks stores/ # Zustand stores utils/ # Helpers api/ # tRPC client backend/ src/ routers/ # tRPC routers services/ # Business logic models/ # Database models middleware/ # Express middleware
## Code Standards
- Functional components with hooks
- Explicit TypeScript types (strict mode)
- Async/await for async operations
- Error handling with specific error types
- Accessibility (ARIA labels, keyboard nav)
- Tests for all business logic
## Environment
- Node.js 18+
- PostgreSQL 14+
- Redis (for caching)
EOF
Configure .kimiignore
cat > .kimiignore << 'EOF'
# Secrets
.env*
*.pem
*.key
credentials.json
config/local*
# Dependencies
node_modules/
vendor/
.pnpm-store/
# Build outputs
dist/
build/
.next/
*.bundle.js
# Generated
coverage/
.nyc_output/
*.min.js
*.min.css
# Large files
*.mp4
*.mov
*.avi
*.zip
*.tar.gz
*.iso
# IDE
.vscode/
.idea/
*.swp
*.swo
# OS
.DS_Store
Thumbs.db
EOF
Step 5: Your First Session (5 minutes)
Instant Mode (Quick Tasks)
kimi --mode instant "What's the regex for email validation?"
# Output: ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
Thinking Mode (Complex Problems)
kimi --mode thinking "Design a rate limiter with sliding window"
# Kimi shows reasoning process, then implementation
Agent Mode (Multi-Step Tasks)
kimi --mode agent "Create a LoginForm component with validation"
# Kimi will:
# 1. Read project context
# 2. Check existing patterns
# 3. Create the component
# 4. Add validation logic
# 5. Create tests
Expected interaction:
Kimi: I'll create a LoginForm component. First, let me check the existing form patterns...
[Reads existing components]
Kimi: I see you use React Hook Form. I'll create:
1. LoginForm.tsx with React Hook Form + Zod validation
2. LoginForm.test.tsx with tests
3. Update types if needed
Proceed? (y/n/details)
> y
[Files created]
Step 6: Agent Swarm (5 minutes)
Simple Swarm Example
# Create multiple related components in parallel
kimi --mode swarm "Generate form components: Input, Select, Checkbox, Button"
# Kimi spawns multiple agents:
# - Agent 1: Input component
# - Agent 2: Select component
# - Agent 3: Checkbox component
# - Agent 4: Button component
# - Agent 5: Consolidate and ensure consistency
Production Refactoring Example
# Large-scale refactoring with checkpointing
kimi --mode swarm \
--checkpoint-interval 5 \
--max-agents 5 \
--token-budget 1000000 \
"Migrate all JavaScript files to TypeScript"
What happens:
- Orchestrator analyzes codebase
- Spawns 5 agents for different directories
- Each agent converts files in parallel
- Checkpoint every 5 files for recovery
- Consolidator ensures consistent patterns
- Total time: ~4-5x faster than sequential
Monitor Swarm Progress
# In another terminal, watch logs
tail -f .kimi/logs/swarm-$(date +%Y%m%d).log
# Or use built-in status
kimi swarm --status
Step 7: Vision-to-Code (3 minutes)
From Mockup to Component
# Have a mockup image ready (mockup.png)
kimi vision --input mockup.png --mode agent \
"Implement this design as a React component"
Process:
- Kimi analyzes the visual design
- Extracts colors, typography, layout
- Generates matching component
- Asks for approval before writing
From Screenshot
kimi vision --input screenshot.png --mode thinking \
"Reproduce this UI component, maintaining accessibility"
Batch Processing
# Multiple mockups at once
kimi vision --batch mockups/ --output components/ \
"Generate components for all mockups"
Step 8: Cost Management (2 minutes)
Monitor Usage
# Check current session cost
kimi status
# Output: Session: 45K input, 12K output tokens
# Cost: $0.057
# Budget remaining: $19.94
# View detailed breakdown
kimi status --detailed
Set Budget Alerts
# Configure in .kimi/config.yaml
cost_control:
warn_threshold: 5.00
hard_limit: 20.00
action_on_limit: pause_and_notify
Estimate Before Execution
kimi --estimate --mode swarm "Large refactoring task"
# Output: Estimated cost: $8.50
# Estimated tokens: 2.5M input, 800K output
# Proceed? (y/n)
Security Best Practices
1. API Key Security
# Never commit API keys
echo ".kimi/" >> .gitignore
echo "KIMI_API_KEY" >> .gitignore
# Use environment-specific keys
export KIMI_API_KEY="$KIMI_PROD_KEY" # Production
export KIMI_API_KEY="$KIMI_DEV_KEY" # Development
2. Audit Logging
# Enable comprehensive logging
export KIMI_AUDIT_LOG=/var/log/kimi/audit.log
# Review logs
cat .kimi/logs/audit-$(date +%Y%m%d).log | grep "file_write"
3. Self-Hosting (Advanced)
For maximum data control:
# Download model weights
git lfs clone https://huggingface.co/moonshotai/kimi-k2.5
# Run with vLLM
vllm serve moonshotai/kimi-k2.5 \
--tensor-parallel-size 8 \
--max-model-len 256000
# Point Kimi Code to local endpoint
export KIMI_BASE_URL="http://localhost:8000/v1"
kimi test
Troubleshooting
Issue: "API key invalid"
# Verify key format
echo $KIMI_API_KEY | wc -c
# Should be ~50+ characters
# Check account status
kimi login --refresh
# Verify at platform
open https://platform.moonshot.cn/keys
Issue: "Context window exceeded"
# Check current context usage
kimi status --context
# Exclude large files
echo "large-file.json" >> .kimiignore
# Use progressive context
kimi --context src/utils/ "Task for utils"
kimi --context src/components/ "Task for components"
Issue: "Rate limit exceeded"
# Check rate limits
kimi limits
# Output: RPM: 100, TPM: 100000
# Add delays between requests
kimi --delay 1 "Series of tasks"
# Use batch mode for efficiency
kimi --batch tasks/ "Process all"
Issue: "Swarm agent failure"
# Check swarm logs
kimi swarm --logs --last-failed
# Retry with checkpoint
kimi swarm --resume-from-checkpoint 5
# Reduce agent count
kimi --mode swarm --max-agents 3
Next Steps
Learn More
- Kimi Code Guide — Comprehensive reference
- Agent Swarm Patterns — Advanced coordination
- Vision-to-Code Workflows — Visual development
- PRD-STD-019: Agent Swarm Governance
Practice Exercises
- Component Library: Use Agent Swarm to generate a complete form library
- API Migration: Migrate REST endpoints to GraphQL with swarm coordination
- Design System: Use vision-to-code to implement a design system from Figma
- Test Generation: Generate comprehensive test suites in parallel
Join the Community
- GitHub: github.com/MoonshotAI/kimi-cli
- Documentation: platform.moonshot.cn/docs
- AEEF Community: Contributing Guide
Summary
You've successfully:
- ✅ Created Kimi account and obtained API key
- ✅ Installed Kimi Code
- ✅ Configured project settings and governance
- ✅ Used Instant, Thinking, and Agent modes
- ✅ Executed your first Agent Swarm
- ✅ Experimented with vision-to-code
- ✅ Set up cost monitoring
Kimi Code is now ready for production use under AEEF governance standards.