OpenRouter Integration: Using Free Models with Claude Code
Tags: openrouter kimi-k2 free-models cost-optimization alternative-providers
This guide demonstrates how to use Claude Code with OpenRouter to access free and cost-effective models, including the powerful Kimi K2 model.
Table of Contents
- Overview
- Why OpenRouter + Claude Code
- Kimi K2: The Free Powerhouse
- Integration Methods
- Performance and Cost Benefits
- Troubleshooting
- Best Practices
Overview
OpenRouter provides a unified API gateway for accessing multiple LLM providers through a single interface. By integrating OpenRouter with Claude Code, you can:
- Access free and low-cost models
- Use open-source alternatives like Kimi K2
- Maintain the familiar Claude Code interface
- Switch between models seamlessly
Why OpenRouter + Claude Code
Benefits
- Cost Reduction: Access free models or pay-per-use pricing
- Model Diversity: Choose from 200+ models across providers
- No Vendor Lock-in: Switch providers without changing code
- Unified Interface: Single API for all models
- Usage Tracking: Built-in analytics and monitoring
Key Features
- Anthropic-compatible API: Works seamlessly with Claude Code
- Automatic failover: Switch to backup models if primary fails
- Rate limit handling: Built-in retry logic
- Cost controls: Set spending limits per model
Kimi K2: The Free Powerhouse
Kimi K2 is Moonshot AI’s latest Mixture-of-Experts model offering exceptional performance:
Specifications
- Parameters: 32B activated / 1T total
- License: Modified MIT (open source)
- Context: 128K tokens
- Languages: Multilingual support
- Release: July 2025
Performance Benchmarks (Updated 2025)
- SWE-bench Verified: 65.8% (single attempt), 71.6% (multiple attempts)
- SWE-bench Multilingual: 47.3% (far ahead of other open-source models)
- HumanEval: 83.2%
- MBPP: 70.8%
- LiveCodeBench: 43.4%
- TerminalBench: Excels in terminal operations
- Aider-Polyglot: Strong multi-language development capabilities
Cost Comparison (Updated July 2025)
| Model | Provider | Input Cost | Output Cost | Speed |
|---|---|---|---|---|
| Kimi K2 | OpenRouter | $0.15/1M tokens | $2.50/1M tokens | Fast (3x faster) |
| Kimi K2 | Kimi App/Browser | Free | Free | Medium |
| Kimi K2 | Groq | ~5x cheaper than Sonnet | ~5x cheaper | Very Fast |
| Claude Sonnet 4 | Anthropic | $3/1M tokens | $15/1M tokens | Medium |
| GPT-4 | OpenAI | $10/1M tokens | $30/1M tokens | Medium |
*Note: Kimi K2 is available free through their app/browser interface, while API access has competitive pricing
Integration Methods
Method 1: Y-Router Proxy (Recommended)
Y-Router is a Cloudflare Worker that translates between Anthropic’s API and OpenRouter.
Setup Steps
-
Get OpenRouter API Key
# Sign up at https://openrouter.ai # Generate API key from dashboard -
Configure Environment
# Basic configuration export ANTHROPIC_BASE_URL="https://cc.yovy.app" export ANTHROPIC_API_KEY="your-openrouter-api-key" # Optional: Specify models export ANTHROPIC_MODEL="moonshotai/kimi-k2" export ANTHROPIC_SMALL_FAST_MODEL="google/gemini-2.5-flash" -
Run Claude Code
claude "Help me write a Python script"
Self-Hosting Y-Router
Deploy your own instance on Cloudflare Workers:
// worker.js
export default {
async fetch(request, env) {
const url = new URL(request.url);
// Rewrite to OpenRouter endpoint
url.hostname = 'openrouter.ai';
url.pathname = url.pathname.replace('/v1/messages', '/api/v1/chat/completions');
// Transform request
const body = await request.json();
const openRouterBody = transformToOpenRouter(body);
// Forward request
const response = await fetch(url, {
method: request.method,
headers: {
'Authorization': request.headers.get('Authorization'),
'Content-Type': 'application/json',
'HTTP-Referer': 'https://github.com/your-username/claude-code-usage',
'X-Title': 'Claude Code Session'
},
body: JSON.stringify(openRouterBody)
});
// Transform response back
const data = await response.json();
return new Response(JSON.stringify(transformFromOpenRouter(data)), {
headers: response.headers
});
}
};Method 2: Direct Configuration with LiteLLM
Use LiteLLM as an intermediary proxy:
-
Install LiteLLM
pip install litellm -
Configure Proxy
# litellm_config.yaml model_list: - model_name: claude-sonnet litellm_params: model: openrouter/moonshotai/kimi-k2 api_key: ${OPENROUTER_API_KEY} api_base: https://openrouter.ai/api/v1 -
Start Proxy
litellm --config litellm_config.yaml --port 8000 -
Configure Claude Code
export ANTHROPIC_BASE_URL="http://localhost:8000" export ANTHROPIC_API_KEY="any-value"
Method 3: Multiple Configuration Aliases
Maintain different configurations for various use cases:
# ~/.zshrc or ~/.bashrc
# Production - Original Claude
alias claude-prod='claude'
# Development - Kimi K2 via OpenRouter
alias claude-dev='ANTHROPIC_BASE_URL="https://cc.yovy.app" \
ANTHROPIC_API_KEY="$OPENROUTER_KEY" \
ANTHROPIC_MODEL="moonshotai/kimi-k2" \
claude'
# Testing - Gemini Flash for speed
alias claude-test='ANTHROPIC_BASE_URL="https://cc.yovy.app" \
ANTHROPIC_API_KEY="$OPENROUTER_KEY" \
ANTHROPIC_MODEL="google/gemini-2.5-flash" \
claude'
# Research - DeepSeek for complex reasoning
alias claude-research='ANTHROPIC_BASE_URL="https://cc.yovy.app" \
ANTHROPIC_API_KEY="$OPENROUTER_KEY" \
ANTHROPIC_MODEL="deepseek/deepseek-r1" \
claude'Configuration Examples
Project-Level Configuration
.claude/settings.json:
{
"api_base_url": "https://cc.yovy.app",
"model": "moonshotai/kimi-k2",
"permission_mode": "relaxed",
"system_prompt": "You are Claude Code running with Kimi K2 model via OpenRouter.",
"hooks": {
"PreToolUse": [
{
"matcher": ".*",
"hooks": [
{
"type": "command",
"command": "echo 'Using Kimi K2 via OpenRouter'",
"timeout": 1000
}
]
}
]
}
}Environment File
.env:
# OpenRouter Configuration
OPENROUTER_API_KEY=sk-or-v1-your-key-here
ANTHROPIC_BASE_URL=https://cc.yovy.app
ANTHROPIC_API_KEY=$OPENROUTER_API_KEY
# Model Selection
ANTHROPIC_MODEL=moonshotai/kimi-k2
ANTHROPIC_SMALL_FAST_MODEL=google/gemini-2.5-flash
# Optional: Headers for OpenRouter
HTTP_REFERER=https://github.com/your-username/project
X_TITLE=Claude Code DevelopmentPerformance and Cost Benefits
Speed Comparison (Groq Integration)
| Model | Tokens/Second | Relative Speed |
|---|---|---|
| Kimi K2 (Groq) | ~500 | 3x faster |
| Claude Sonnet 4 | ~170 | Baseline |
| GPT-4 | ~150 | 0.9x |
Note: Using Kimi K2 through Groq provides nearly 3x speed improvement and about 5x cost reduction compared to Claude Sonnet 4.
Cost Analysis
For a typical development session (100K tokens):
| Model | Cost | Savings |
|---|---|---|
| Kimi K2 | $0 (free tier) | 100% |
| Claude Sonnet 4 | ~$1.80 | - |
| GPT-4 | ~$2.00 | - |
Use Case Recommendations
- Development & Testing: Kimi K2 (free, fast)
- Code Reviews: Gemini 2.5 Flash (very fast, low cost)
- Complex Reasoning: DeepSeek R1 (strong performance)
- Production: Original Claude (when required)
Advanced Features
Model Routing
Route different tasks to appropriate models:
# Router configuration
export CLAUDE_ROUTER_RULES='
{
"patterns": {
"test": "google/gemini-2.5-flash",
"debug": "moonshotai/kimi-k2",
"review": "anthropic/claude-sonnet",
"docs": "meta-llama/llama-3.1-8b"
}
}'Fallback Configuration
{
"primary_model": "moonshotai/kimi-k2",
"fallback_models": [
"google/gemini-2.5-flash",
"meta-llama/llama-3.1-8b",
"anthropic/claude-haiku"
],
"retry_attempts": 3
}Troubleshooting
Common Issues
-
Authentication Errors
- Verify OpenRouter API key is valid
- Check environment variable names
- Ensure proper URL encoding
-
Model Not Found
- Verify model name format:
provider/model - Check model availability on OpenRouter
- Some models require credits
- Verify model name format:
-
Rate Limits
- Free tier has request limits
- Add credits for unlimited access
- Use fallback models
Debug Mode
# Enable debug logging
export CLAUDE_DEBUG=true
export OPENROUTER_DEBUG=true
# Test connection
curl -X POST https://openrouter.ai/api/v1/chat/completions \
-H "Authorization: Bearer $OPENROUTER_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "moonshotai/kimi-k2",
"messages": [{"role": "user", "content": "Hello"}]
}'Best Practices
-
API Key Security
- Never commit API keys
- Use environment variables
- Rotate keys regularly
-
Model Selection
- Match model to task complexity
- Use free tiers for development
- Reserve premium models for production
-
Cost Management
- Set spending limits in OpenRouter
- Monitor usage dashboard
- Use webhooks for alerts
-
Performance Optimization
- Cache common responses
- Use streaming for long outputs
- Batch similar requests
Real-World Usage Insights
Best Use Cases for Kimi K2
- Agentic Coding: Kimi K2 excels at tool calling and execution, critical for autonomous coding tasks
- Act Mode: Strong execution of well-defined plans (let planning models create strategy, Kimi K2 executes)
- Multi-language Development: Proven performance across different programming languages
- Cost-Sensitive Projects: Significantly cheaper than proprietary alternatives
Integration Tips
- Use Kimi K2’s large context window (128K tokens) to provide relevant code and documentation
- Break complex tasks into smaller requests for better results
- Maintain session continuity by referencing previous interactions
- Consider using Groq for maximum speed when latency is critical
References
- OpenRouter Documentation
- Kimi K2 Technical Report
- Y-Router GitHub
- Claude Code Settings Guide
- LiteLLM Proxy Documentation
- Kimi K2 on OpenRouter
See Also
Verifications
- Kimi K2 Performance: Verified latest benchmarks from official Moonshot AI website at https://moonshotai.github.io/Kimi-K2/ (2025-07-20)
- Pricing Information: Updated pricing from CNBC report and official Kimi website at https://www.cnbc.com/2025/07/14/alibaba-backed-moonshot-releases-kimi-k2-ai-rivaling-chatgpt-claude.html
- Integration Methods: Confirmed Claude Code Router and Groq integration from Medium articles and HuggingFace blog
- Speed Comparisons: Validated Groq performance claims from https://medium.com/@hungry.soul/vibe-coding-with-claude-code-groq-kimi-k2-ef814bbcdac5