Feat : Gitbook

This commit is contained in:
decolua
2026-05-11 11:50:24 +07:00
parent 7ad538bcf2
commit fd92af77a0
124 changed files with 34154 additions and 4 deletions

View File

@@ -0,0 +1,109 @@
# Claude Code Integration
Integrate 9Router with Claude Code CLI to route your Anthropic API requests through 9Router's intelligent routing system.
## Prerequisites
- Claude Code CLI installed
- 9Router running locally or cloud endpoint configured
- API key from 9Router dashboard
## Setup
### 1. Configure Environment Variables
Set the following environment variables in your shell configuration file (`~/.bashrc`, `~/.zshrc`, or `~/.bash_profile`):
```bash
# Base URL for 9Router
export ANTHROPIC_BASE_URL="http://localhost:20128/v1"
# Optional: Set default models for aliases
export ANTHROPIC_DEFAULT_OPUS_MODEL="cc/claude-opus-4-5-20251101"
export ANTHROPIC_DEFAULT_SONNET_MODEL="cc/claude-sonnet-4-5-20250929"
export ANTHROPIC_DEFAULT_HAIKU_MODEL="cc/claude-haiku-4-5-20251001"
```
### 2. Reload Shell Configuration
```bash
source ~/.zshrc # or ~/.bashrc
```
### 3. Verify Configuration
Check that the environment variables are set correctly:
```bash
echo $ANTHROPIC_BASE_URL
```
## Model Aliases
Claude Code supports the following model aliases that map to 9Router models:
| Alias | Model | Environment Variable |
|-------|-------|---------------------|
| `opus` | Claude Opus 4.5 | `ANTHROPIC_DEFAULT_OPUS_MODEL` |
| `sonnet` | Claude Sonnet 4.5 | `ANTHROPIC_DEFAULT_SONNET_MODEL` |
| `haiku` | Claude Haiku 4.5 | `ANTHROPIC_DEFAULT_HAIKU_MODEL` |
## Usage Examples
### Using Model Aliases
```bash
# Use Opus model
claude --model opus "Explain quantum computing"
# Use Sonnet model
claude --model sonnet "Write a Python function"
# Use Haiku model
claude --model haiku "Quick code review"
```
### Using Full Model Names
```bash
claude --model cc/claude-opus-4-5-20251101 "Your prompt here"
```
## Settings File
Claude Code stores its configuration in `~/.claude/settings.json`. You can manually edit this file if needed:
```json
{
"baseUrl": "http://localhost:20128/v1",
"defaultModel": "sonnet"
}
```
## Troubleshooting
### Connection Issues
If you encounter connection errors:
1. Verify 9Router is running: `curl http://localhost:20128/health`
2. Check environment variables are set correctly
3. Ensure no firewall is blocking port 20128
### Model Not Found
If you get "model not found" errors:
1. Verify the model name matches your 9Router configuration
2. Check that the provider connection is active in 9Router dashboard
3. Ensure the model is available in your connected providers
## Cloud Endpoint
To use 9Router cloud endpoint instead of localhost:
```bash
export ANTHROPIC_BASE_URL="https://9router.com"
```
Make sure you have configured your API key in the 9Router cloud dashboard.

View File

@@ -0,0 +1,201 @@
# Cline Integration
Integrate 9Router with Cline VSCode extension to route your AI requests through 9Router's intelligent routing system.
## Prerequisites
- Visual Studio Code installed
- Cline extension installed from VSCode marketplace
- 9Router running locally or cloud endpoint configured
- API key from 9Router dashboard
## Setup
### 1. Open Cline Settings
1. Open Visual Studio Code
2. Open the Cline extension panel (click the Cline icon in the sidebar)
3. Click the **Settings** icon (gear icon) in the Cline panel
### 2. Select API Provider
1. In the Cline settings, find **API Provider** dropdown
2. Select **Ollama** from the list
- Note: We use Ollama provider type because it's compatible with OpenAI-style APIs
### 3. Configure Base URL
Set the base URL to your 9Router endpoint:
**For Local 9Router:**
```
http://localhost:20128/v1
```
**For Cloud 9Router:**
```
https://9router.com
```
**Steps:**
1. In the **Base URL** field, enter your 9Router endpoint
2. Make sure to include `/v1` at the end
### 4. Add API Key
1. In the **API Key** field, enter your 9Router API key
2. You can find your API key in the 9Router dashboard under **Settings → API Keys**
3. The key should start with `sk-9router-`
### 5. Select Model
1. In the **Model** dropdown, you can either:
- Select from available models (if Cline auto-detects them)
- Manually enter the model name from your 9Router configuration
2. Common model names:
- `gpt-4`
- `gpt-4o`
- `claude-opus-4-5`
- `claude-sonnet-4-5`
- `gemini-2.0-flash`
### 6. Save Configuration
Click **Save** or close the settings panel. Cline will automatically save your configuration.
## Configuration Example
Your Cline settings should look like this:
```
API Provider: Ollama
Base URL: http://localhost:20128/v1
API Key: sk-9router-xxxxxxxxxxxxx
Model: gpt-4
```
## Available Models
You can use any model configured in your 9Router dashboard. Common examples:
| Model Name | Provider | Description |
|------------|----------|-------------|
| `gpt-4` | OpenAI | GPT-4 Turbo |
| `gpt-4o` | OpenAI | GPT-4 Optimized |
| `claude-opus-4-5` | Anthropic | Claude Opus 4.5 |
| `claude-sonnet-4-5` | Anthropic | Claude Sonnet 4.5 |
| `gemini-2.0-flash` | Google | Gemini 2.0 Flash |
## Usage
### Chat with AI
1. Open the Cline panel in VSCode
2. Type your message in the chat input
3. Press Enter to send
4. Cline will use 9Router to process your request
### Code Generation
1. Ask Cline to generate code: "Create a React component for a login form"
2. Cline will generate code using 9Router
3. Review and accept the generated code
### Code Explanation
1. Select code in your editor
2. Ask Cline: "Explain this code"
3. Get AI-powered explanations through 9Router
### File Operations
1. Ask Cline to create, modify, or delete files
2. Cline will use 9Router to understand context and make changes
3. Review changes before accepting
## Troubleshooting
### "Connection Failed" Error
1. Verify 9Router is running: `curl http://localhost:20128/health`
2. Check that the base URL is correct and includes `/v1`
3. Ensure no firewall is blocking port 20128
4. Try restarting VSCode
### "Invalid API Key" Error
1. Verify your API key in 9Router dashboard
2. Make sure you copied the entire key including the `sk-9router-` prefix
3. Check that the API key has not expired
4. Try regenerating a new API key
### "Model Not Found" Error
1. Verify the model name matches exactly with your 9Router configuration
2. Check that the provider connection is active in 9Router dashboard
3. Ensure the model is available in your connected providers
4. Try using the full model name (e.g., `openai/gpt-4` instead of `gpt-4`)
### Cline Not Responding
1. Check the Cline output panel for error messages
2. Verify your 9Router instance is running and healthy
3. Try reloading VSCode window (Cmd/Ctrl + Shift + P → "Reload Window")
4. Check 9Router logs for any errors
## Advanced Configuration
### Using Cloud Endpoint
To use 9Router cloud endpoint instead of localhost:
1. In Cline settings, set Base URL to: `https://9router.com`
2. Make sure you have configured your API key in the 9Router cloud dashboard
3. Ensure your cloud endpoint is active and accessible
### Multiple Models
You can quickly switch between models:
1. Open Cline settings
2. Change the **Model** field to a different model
3. Save and continue chatting with the new model
### Custom Timeout
If you experience timeout issues with large requests:
1. Open VSCode settings (Cmd/Ctrl + ,)
2. Search for "Cline timeout"
3. Increase the timeout value (default is usually 30 seconds)
## Best Practices
1. **Use Appropriate Models**: Choose faster models (like Haiku or Flash) for simple tasks, and more powerful models (like Opus or GPT-4) for complex tasks
2. **Monitor Usage**: Check 9Router dashboard for usage statistics and costs
3. **Context Management**: Keep your conversations focused to reduce token usage
4. **Model Switching**: Switch models based on task complexity to optimize cost and performance
5. **API Key Security**: Never commit your API key to version control
## Integration with 9Router Features
### Model Routing
9Router automatically routes your requests to the best available provider based on:
- Model availability
- Provider health status
- Cost optimization
- Load balancing
### Fallback Support
If a provider fails, 9Router automatically falls back to alternative providers configured in your dashboard.
### Usage Tracking
Monitor your Cline usage through 9Router dashboard:
- Total requests
- Token usage
- Cost per model
- Provider distribution

View File

@@ -0,0 +1,136 @@
# OpenAI Codex CLI Integration
Integrate 9Router with OpenAI Codex CLI to route your OpenAI API requests through 9Router's intelligent routing system.
## Prerequisites
- OpenAI Codex CLI installed
- 9Router running locally or cloud endpoint configured
- API key from 9Router dashboard
## Setup
### 1. Configure Environment Variables
Set the following environment variables in your shell configuration file (`~/.bashrc`, `~/.zshrc`, or `~/.bash_profile`):
```bash
# Base URL for 9Router
export OPENAI_BASE_URL="http://localhost:20128/v1"
# API Key from 9Router dashboard
export OPENAI_API_KEY="your-9router-api-key"
```
### 2. Reload Shell Configuration
```bash
source ~/.zshrc # or ~/.bashrc
```
### 3. Verify Configuration
Check that the environment variables are set correctly:
```bash
echo $OPENAI_BASE_URL
echo $OPENAI_API_KEY
```
## Available Models
9Router provides the following Codex models:
| Model ID | Description |
|----------|-------------|
| `cx/gpt-5.2-codex` | GPT-5.2 Codex - Latest version |
| `cx/gpt-5.1-codex-max` | GPT-5.1 Codex Max - Extended context |
## Usage Examples
### Basic Usage
```bash
# Use GPT-5.2 Codex
codex --model cx/gpt-5.2-codex "Write a function to sort an array"
# Use GPT-5.1 Codex Max
codex --model cx/gpt-5.1-codex-max "Explain this complex algorithm"
```
### Code Generation
```bash
codex --model cx/gpt-5.2-codex "Create a REST API endpoint for user authentication"
```
### Code Explanation
```bash
codex --model cx/gpt-5.1-codex-max "Explain what this code does: $(cat myfile.js)"
```
## Configuration File
You can also configure Codex CLI using a configuration file. Create or edit `~/.codex/config.json`:
```json
{
"baseUrl": "http://localhost:20128/v1",
"apiKey": "your-9router-api-key",
"defaultModel": "cx/gpt-5.2-codex"
}
```
## Troubleshooting
### Authentication Errors
If you encounter authentication errors:
1. Verify your API key is correct in 9Router dashboard
2. Check that `OPENAI_API_KEY` environment variable is set
3. Ensure the API key has not expired
### Connection Issues
If you encounter connection errors:
1. Verify 9Router is running: `curl http://localhost:20128/health`
2. Check environment variables are set correctly
3. Ensure no firewall is blocking port 20128
### Model Not Available
If you get "model not available" errors:
1. Verify the model name matches your 9Router configuration
2. Check that the OpenAI provider connection is active in 9Router dashboard
3. Ensure the model is available in your connected providers
## Cloud Endpoint
To use 9Router cloud endpoint instead of localhost:
```bash
export OPENAI_BASE_URL="https://9router.com"
```
Make sure you have configured your API key in the 9Router cloud dashboard.
## Advanced Configuration
### Custom Timeout
```bash
export OPENAI_TIMEOUT=60 # seconds
```
### Debug Mode
Enable debug mode to see detailed request/response logs:
```bash
export CODEX_DEBUG=true
codex --model cx/gpt-5.2-codex "Your prompt"
```

View File

@@ -0,0 +1,249 @@
# Continue VSCode Extension Integration
Integrate 9Router with Continue extension to bring AI assistance directly into Visual Studio Code.
## Prerequisites
- Visual Studio Code installed
- Continue extension installed from VSCode marketplace
- 9Router API key from [dashboard](https://9router.com/dashboard)
- 9Router running (local or cloud)
## Configuration Steps
### 1. Open Continue Configuration
1. Open VSCode
2. Press `Cmd+Shift+P` (Mac) or `Ctrl+Shift+P` (Windows/Linux)
3. Type "Continue: Open Config" and select it
4. This opens `~/.continue/config.json`
### 2. Add 9Router Model Configuration
Add the following configuration to your `config.json`:
**Single Model Setup:**
```json
{
"models": [
{
"title": "9Router - Claude Opus",
"provider": "openai",
"model": "cc/claude-opus-4-5-20251101",
"apiKey": "your-api-key-from-dashboard",
"apiBase": "http://localhost:20128/v1"
}
]
}
```
**Multiple Models Setup:**
```json
{
"models": [
{
"title": "9Router - Claude Opus (Best)",
"provider": "openai",
"model": "cc/claude-opus-4-5-20251101",
"apiKey": "your-api-key-from-dashboard",
"apiBase": "http://localhost:20128/v1"
},
{
"title": "9Router - Claude Sonnet (Balanced)",
"provider": "openai",
"model": "cc/claude-sonnet-4-20250514",
"apiKey": "your-api-key-from-dashboard",
"apiBase": "http://localhost:20128/v1"
},
{
"title": "9Router - DeepSeek Chat (Code)",
"provider": "openai",
"model": "cx/deepseek-chat",
"apiKey": "your-api-key-from-dashboard",
"apiBase": "http://localhost:20128/v1"
},
{
"title": "9Router - Claude Haiku (Fast)",
"provider": "openai",
"model": "cc/claude-haiku-4-20250514",
"apiKey": "your-api-key-from-dashboard",
"apiBase": "http://localhost:20128/v1"
}
]
}
```
**For Cloud 9Router:**
Replace `apiBase` with:
```json
"apiBase": "https://9router.com/v1"
```
### 3. Save and Reload
1. Save the configuration file
2. Reload VSCode window: `Cmd+Shift+P` → "Developer: Reload Window"
3. Continue extension will load the new configuration
### 4. Select Model
1. Open Continue sidebar (click Continue icon in left panel)
2. Click model selector dropdown at the top
3. Choose your preferred 9Router model
## Available Models
### Claude Models (Anthropic)
- `cc/claude-opus-4-5-20251101` - Most capable, best for complex tasks
- `cc/claude-sonnet-4-20250514` - Balanced performance and speed
- `cc/claude-haiku-4-20250514` - Fastest, good for simple tasks
### DeepSeek Models
- `cx/deepseek-chat` - Excellent for code generation
- `cx/deepseek-reasoner` - Best for complex problem solving
### GLM Models (Zhipu AI)
- `glm/glm-4-plus` - Advanced Chinese and English
- `glm/glm-4-flash` - Fast responses
## Usage Examples
### Code Explanation
1. Select code in editor
2. Open Continue sidebar
3. Type: "Explain this code"
4. Model: `cc/claude-sonnet-4-20250514`
### Code Generation
1. Open Continue sidebar
2. Type: "Create a React component for user profile card"
3. Model: `cx/deepseek-chat`
### Refactoring
1. Select code to refactor
2. Type: "Refactor this to use async/await"
3. Model: `cc/claude-sonnet-4-20250514`
### Bug Fixing
1. Select problematic code
2. Type: "Find and fix the bug in this code"
3. Model: `cx/deepseek-reasoner`
## Advanced Configuration
### Custom System Prompts
Add custom system prompts for specific behaviors:
```json
{
"models": [
{
"title": "9Router - Code Expert",
"provider": "openai",
"model": "cx/deepseek-chat",
"apiKey": "your-api-key",
"apiBase": "http://localhost:20128/v1",
"systemMessage": "You are an expert programmer. Always provide clean, well-documented code with best practices."
}
]
}
```
### Temperature and Parameters
Adjust model behavior with parameters:
```json
{
"models": [
{
"title": "9Router - Creative Writer",
"provider": "openai",
"model": "cc/claude-opus-4-5-20251101",
"apiKey": "your-api-key",
"apiBase": "http://localhost:20128/v1",
"temperature": 0.9,
"topP": 0.95
}
]
}
```
### Context Providers
Configure what context Continue sends to the model:
```json
{
"contextProviders": [
{
"name": "code",
"params": {
"maxLines": 100
}
},
{
"name": "diff",
"params": {}
},
{
"name": "terminal",
"params": {}
}
]
}
```
## Keyboard Shortcuts
- `Cmd+L` (Mac) / `Ctrl+L` (Windows/Linux) - Open Continue chat
- `Cmd+I` (Mac) / `Ctrl+I` (Windows/Linux) - Inline edit
- `Cmd+Shift+R` (Mac) / `Ctrl+Shift+R` (Windows/Linux) - Regenerate response
## Troubleshooting
### Model Not Responding
- Check 9Router is running: `curl http://localhost:20128/health`
- Verify API key in config.json
- Check VSCode Developer Console for errors: `Help` → `Toggle Developer Tools`
### Wrong Model Selected
- Click model dropdown in Continue sidebar
- Select correct 9Router model
- Model name must match exactly (case-sensitive)
### Configuration Not Loading
- Verify JSON syntax is valid (use JSON validator)
- Check file location: `~/.continue/config.json`
- Reload VSCode window after changes
### Slow Performance
- Switch to faster models (haiku, flash)
- Reduce context size in contextProviders
- Check network latency to 9Router
## Best Practices
### Model Selection Strategy
- **Quick edits**: Use `cc/claude-haiku-4-20250514`
- **Code generation**: Use `cx/deepseek-chat`
- **Complex refactoring**: Use `cc/claude-opus-4-5-20251101`
- **Problem solving**: Use `cx/deepseek-reasoner`
### Context Management
- Select only relevant code before asking
- Use specific, clear prompts
- Break complex tasks into smaller steps
### Cost Optimization
- Use faster/cheaper models for simple tasks
- Limit context size when possible
- Cache frequently used responses
## Next Steps
- [Configure Cursor](cursor.md) for enhanced IDE integration
- [Set up Roo](roo.md) for AI assistant
- [Explore CLI usage](../cli/basic-usage.md)
- [Learn about model selection](../models/overview.md)

View File

@@ -0,0 +1,149 @@
# Cursor Integration
Integrate 9Router with Cursor IDE to route your AI requests through 9Router's intelligent routing system.
## Prerequisites
- Cursor IDE installed
- Cursor Pro account (required for custom API endpoints)
- 9Router cloud endpoint configured
- API key from 9Router dashboard
## ⚠️ Important Notes
> **Cloud Endpoint Required**: Cursor routes requests through its own server and does not support localhost endpoints. You must use the 9Router cloud endpoint: `https://9router.com`
> **Cursor Pro Required**: This feature requires a Cursor Pro account to use custom API endpoints.
## Setup
### 1. Open Cursor Settings
1. Open Cursor IDE
2. Go to **Settings** (Cmd/Ctrl + ,)
3. Navigate to **Models** section
### 2. Enable OpenAI API
1. Find the **OpenAI API key** option
2. Enable the toggle to activate custom API configuration
### 3. Configure Base URL
Set the base URL to 9Router cloud endpoint:
```
https://9router.com
```
**Steps:**
1. In the Models settings, locate the **Base URL** field
2. Enter: `https://9router.com`
3. Click **Save**
### 4. Add API Key
1. In the **API Key** field, enter your 9Router API key
2. You can find your API key in the 9Router dashboard under **Settings → API Keys**
3. Click **Save**
### 5. Add Custom Model
1. Click **View All Models** button
2. Click **Add Custom Model**
3. Enter the model name from your 9Router configuration (e.g., `gpt-4`, `claude-opus-4-5`, etc.)
4. Click **Add**
### 6. Select Model
1. In the Cursor chat interface, click the model selector dropdown
2. Choose your custom model from the list
3. Start using 9Router with Cursor!
## Configuration Example
Your Cursor settings should look like this:
```
OpenAI API: ✓ Enabled
Base URL: https://9router.com
API Key: sk-9router-xxxxxxxxxxxxx
Custom Models: gpt-4, claude-opus-4-5, gemini-2.0-flash
```
## Available Models
You can use any model configured in your 9Router dashboard. Common examples:
| Model Name | Provider | Description |
|------------|----------|-------------|
| `gpt-4` | OpenAI | GPT-4 Turbo |
| `gpt-4o` | OpenAI | GPT-4 Optimized |
| `claude-opus-4-5` | Anthropic | Claude Opus 4.5 |
| `claude-sonnet-4-5` | Anthropic | Claude Sonnet 4.5 |
| `gemini-2.0-flash` | Google | Gemini 2.0 Flash |
## Usage
### Chat Interface
1. Open Cursor chat (Cmd/Ctrl + L)
2. Select your model from the dropdown
3. Start chatting with AI through 9Router
### Inline Code Generation
1. Select code in your editor
2. Press Cmd/Ctrl + K
3. Enter your prompt
4. Cursor will use 9Router to generate code
### Code Explanation
1. Select code in your editor
2. Press Cmd/Ctrl + L
3. Ask "Explain this code"
4. Get AI-powered explanations through 9Router
## Troubleshooting
### "Invalid API Key" Error
1. Verify your API key in 9Router dashboard
2. Make sure you copied the entire key including the `sk-9router-` prefix
3. Check that the API key has not expired
4. Try regenerating a new API key
### "Model Not Found" Error
1. Verify the model name matches exactly with your 9Router configuration
2. Check that the provider connection is active in 9Router dashboard
3. Ensure the model is available in your connected providers
4. Try using the full model name (e.g., `openai/gpt-4` instead of `gpt-4`)
### Connection Issues
1. Verify you are using the cloud endpoint: `https://9router.com`
2. Check your internet connection
3. Ensure 9Router cloud service is operational
4. Try disabling VPN or proxy if enabled
### Localhost Not Working
> **Remember**: Cursor does not support localhost endpoints. You must use the cloud endpoint `https://9router.com`. If you need to use a local 9Router instance, consider using a tunneling service like ngrok to expose your local endpoint.
## Cloud Endpoint Setup
If you're running 9Router locally and want to use it with Cursor:
1. Enable cloud endpoint in 9Router settings
2. Configure your cloud endpoint URL in 9Router dashboard
3. Use the cloud URL in Cursor settings
4. Ensure your local 9Router instance is accessible from the internet
## Best Practices
1. **Use Model Aliases**: Create short aliases for frequently used models in 9Router
2. **Monitor Usage**: Check 9Router dashboard for usage statistics and costs
3. **Rotate API Keys**: Regularly rotate your API keys for security
4. **Test Models**: Try different models to find the best one for your use case

View File

@@ -0,0 +1,416 @@
# Other Tools Integration
9Router is compatible with any tool that supports the OpenAI API format. This guide covers generic integration patterns for various tools and custom applications.
## Overview
9Router provides an OpenAI-compatible API endpoint that works with:
- Custom scripts and applications
- API clients and testing tools
- CLI tools and utilities
- Third-party integrations
- Development frameworks
## Generic Setup Pattern
Any OpenAI-compatible tool can connect to 9Router using these settings:
**Local 9Router:**
```
Base URL: http://localhost:20128/v1
API Key: your-api-key-from-dashboard
Model: any 9Router model (cc/*, cx/*, glm/*, etc.)
```
**Cloud 9Router:**
```
Base URL: https://9router.com/v1
API Key: your-api-key-from-dashboard
Model: any 9Router model (cc/*, cx/*, glm/*, etc.)
```
## Available Models
### Claude Models (Anthropic)
- `cc/claude-opus-4-5-20251101`
- `cc/claude-sonnet-4-20250514`
- `cc/claude-haiku-4-20250514`
### DeepSeek Models
- `cx/deepseek-chat`
- `cx/deepseek-reasoner`
### GLM Models (Zhipu AI)
- `glm/glm-4-plus`
- `glm/glm-4-flash`
## Integration Examples
### Python with OpenAI SDK
```python
from openai import OpenAI
client = OpenAI(
api_key="your-api-key-from-dashboard",
base_url="http://localhost:20128/v1"
)
response = client.chat.completions.create(
model="cc/claude-sonnet-4-20250514",
messages=[
{"role": "user", "content": "Hello, how are you?"}
]
)
print(response.choices[0].message.content)
```
### Node.js with OpenAI SDK
```javascript
import OpenAI from "openai";
const client = new OpenAI({
apiKey: "your-api-key-from-dashboard",
baseURL: "http://localhost:20128/v1"
});
const response = await client.chat.completions.create({
model: "cc/claude-sonnet-4-20250514",
messages: [
{ role: "user", content: "Hello, how are you?" }
]
});
console.log(response.choices[0].message.content);
```
### cURL Command
```bash
curl http://localhost:20128/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-api-key-from-dashboard" \
-d '{
"model": "cc/claude-sonnet-4-20250514",
"messages": [
{"role": "user", "content": "Hello, how are you?"}
]
}'
```
### HTTP Client (Postman, Insomnia)
**Request:**
```
POST http://localhost:20128/v1/chat/completions
```
**Headers:**
```
Content-Type: application/json
Authorization: Bearer your-api-key-from-dashboard
```
**Body:**
```json
{
"model": "cc/claude-sonnet-4-20250514",
"messages": [
{"role": "user", "content": "Hello, how are you?"}
],
"temperature": 0.7,
"max_tokens": 1000
}
```
### LangChain Integration
```python
from langchain.chat_models import ChatOpenAI
from langchain.schema import HumanMessage
llm = ChatOpenAI(
model_name="cc/claude-sonnet-4-20250514",
openai_api_key="your-api-key-from-dashboard",
openai_api_base="http://localhost:20128/v1",
temperature=0.7
)
messages = [HumanMessage(content="Explain quantum computing")]
response = llm(messages)
print(response.content)
```
### LlamaIndex Integration
```python
from llama_index.llms import OpenAI
llm = OpenAI(
model="cc/claude-sonnet-4-20250514",
api_key="your-api-key-from-dashboard",
api_base="http://localhost:20128/v1"
)
response = llm.complete("What is machine learning?")
print(response.text)
```
## Custom Script Examples
### Batch Processing Script
```python
import openai
import json
openai.api_key = "your-api-key-from-dashboard"
openai.api_base = "http://localhost:20128/v1"
def process_batch(prompts, model="cx/deepseek-chat"):
results = []
for prompt in prompts:
response = openai.ChatCompletion.create(
model=model,
messages=[{"role": "user", "content": prompt}]
)
results.append({
"prompt": prompt,
"response": response.choices[0].message.content
})
return results
prompts = [
"Explain AI in one sentence",
"What is machine learning?",
"Define neural networks"
]
results = process_batch(prompts)
print(json.dumps(results, indent=2))
```
### Streaming Response Handler
```javascript
import OpenAI from "openai";
const client = new OpenAI({
apiKey: "your-api-key-from-dashboard",
baseURL: "http://localhost:20128/v1"
});
async function streamResponse(prompt) {
const stream = await client.chat.completions.create({
model: "cc/claude-sonnet-4-20250514",
messages: [{ role: "user", content: prompt }],
stream: true
});
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content || "";
process.stdout.write(content);
}
}
streamResponse("Write a short story about AI");
```
### Multi-Model Comparison
```python
from openai import OpenAI
client = OpenAI(
api_key="your-api-key-from-dashboard",
base_url="http://localhost:20128/v1"
)
models = [
"cc/claude-sonnet-4-20250514",
"cx/deepseek-chat",
"glm/glm-4-plus"
]
prompt = "Explain quantum computing in simple terms"
for model in models:
response = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": prompt}]
)
print(f"\n=== {model} ===")
print(response.choices[0].message.content)
```
## Common Integration Patterns
### Environment Variables
Store credentials securely:
```bash
# .env file
ROUTER_API_KEY=your-api-key-from-dashboard
ROUTER_BASE_URL=http://localhost:20128/v1
ROUTER_MODEL=cc/claude-sonnet-4-20250514
```
```python
import os
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("ROUTER_API_KEY"),
base_url=os.getenv("ROUTER_BASE_URL")
)
```
### Error Handling
```python
from openai import OpenAI, OpenAIError
client = OpenAI(
api_key="your-api-key",
base_url="http://localhost:20128/v1"
)
try:
response = client.chat.completions.create(
model="cc/claude-sonnet-4-20250514",
messages=[{"role": "user", "content": "Hello"}]
)
print(response.choices[0].message.content)
except OpenAIError as e:
print(f"Error: {e}")
```
### Retry Logic
```python
import time
from openai import OpenAI, RateLimitError
client = OpenAI(
api_key="your-api-key",
base_url="http://localhost:20128/v1"
)
def chat_with_retry(prompt, max_retries=3):
for attempt in range(max_retries):
try:
response = client.chat.completions.create(
model="cc/claude-sonnet-4-20250514",
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content
except RateLimitError:
if attempt < max_retries - 1:
time.sleep(2 ** attempt) # Exponential backoff
else:
raise
```
## Troubleshooting
### Connection Issues
**Problem:** Cannot connect to 9Router
```bash
# Check if 9Router is running
curl http://localhost:20128/health
# Expected response:
{"status": "ok"}
```
**Solution:**
- Verify 9Router is running
- Check port 20128 is not blocked
- Ensure correct base URL (include `/v1`)
### Authentication Errors
**Problem:** 401 Unauthorized
```
Error: Invalid API key
```
**Solution:**
- Verify API key from dashboard
- Check Authorization header format: `Bearer your-api-key`
- Ensure no extra spaces or newlines in API key
### Model Not Found
**Problem:** 404 Model not found
```
Error: Model 'cc/claude-opus' not found
```
**Solution:**
- Use exact model name (case-sensitive)
- Check available models: `curl http://localhost:20128/v1/models`
- Verify model is enabled in your plan
### Timeout Issues
**Problem:** Request timeout
```
Error: Request timed out after 30s
```
**Solution:**
- Increase timeout in client configuration
- Use faster models for time-sensitive tasks
- Check network connection to 9Router
### Rate Limiting
**Problem:** 429 Too Many Requests
```
Error: Rate limit exceeded
```
**Solution:**
- Implement exponential backoff
- Reduce request frequency
- Check rate limits in dashboard
- Consider upgrading plan
## Best Practices
### Security
- Store API keys in environment variables
- Never commit API keys to version control
- Use HTTPS for cloud deployments
- Rotate API keys regularly
### Performance
- Use appropriate models for task complexity
- Implement caching for repeated queries
- Use streaming for long responses
- Batch requests when possible
### Error Handling
- Always implement try-catch blocks
- Add retry logic with exponential backoff
- Log errors for debugging
- Provide fallback mechanisms
### Cost Optimization
- Choose cost-effective models for simple tasks
- Cache responses when appropriate
- Monitor usage in dashboard
- Set request limits in code
## Next Steps
- [Configure Cursor](cursor.md) for IDE integration
- [Set up Continue](continue.md) for VSCode
- [Explore CLI usage](../cli/basic-usage.md)
- [Learn about model selection](../models/overview.md)
- [API Reference](../api/reference.md)

View File

@@ -0,0 +1,127 @@
# Roo AI Assistant Integration
Integrate 9Router with Roo AI Assistant to access multiple AI models through a unified interface.
## Prerequisites
- Roo AI Assistant installed
- 9Router API key from [dashboard](https://9router.com/dashboard)
- 9Router running (local or cloud)
## Configuration Steps
### 1. Open Roo Settings
Launch Roo AI Assistant and open the settings panel.
### 2. Configure API Provider
1. Navigate to **API Provider** settings
2. Select **Ollama** as the provider type
3. Configure the following settings:
**For Local 9Router:**
```
Base URL: http://localhost:20128/v1
API Key: your-api-key-from-dashboard
```
**For Cloud 9Router:**
```
Base URL: https://9router.com/v1
API Key: your-api-key-from-dashboard
```
### 3. Select Model
Choose from available 9Router models:
**Claude Models:**
- `cc/claude-opus-4-5-20251101` - Most capable
- `cc/claude-sonnet-4-20250514` - Balanced
- `cc/claude-haiku-4-20250514` - Fast
**DeepSeek Models:**
- `cx/deepseek-chat` - General purpose
- `cx/deepseek-reasoner` - Complex reasoning
**GLM Models:**
- `glm/glm-4-plus` - Advanced
- `glm/glm-4-flash` - Fast responses
### 4. Test Connection
Send a test message to verify the integration:
```
Hello! Can you confirm you're connected through 9Router?
```
## Usage Examples
### Basic Chat
```
Ask Roo: "Explain quantum computing in simple terms"
Model: cc/claude-sonnet-4-20250514
```
### Code Generation
```
Ask Roo: "Write a Python function to calculate Fibonacci numbers"
Model: cx/deepseek-chat
```
### Complex Reasoning
```
Ask Roo: "Analyze the trade-offs between microservices and monolithic architecture"
Model: cx/deepseek-reasoner
```
## Model Selection Tips
- **Quick tasks**: Use `cc/claude-haiku-4-20250514` or `glm/glm-4-flash`
- **Balanced performance**: Use `cc/claude-sonnet-4-20250514` or `cx/deepseek-chat`
- **Complex reasoning**: Use `cc/claude-opus-4-5-20251101` or `cx/deepseek-reasoner`
- **Cost optimization**: Use DeepSeek or GLM models
## Troubleshooting
### Connection Failed
- Verify 9Router is running: `curl http://localhost:20128/health`
- Check API key is correct
- Ensure Base URL includes `/v1` suffix
### Model Not Available
- Check model name matches exactly (case-sensitive)
- Verify model is enabled in your 9Router plan
- Try a different model from the list
### Slow Responses
- Switch to faster models (haiku, flash)
- Check network connection
- Monitor 9Router logs for issues
## Advanced Configuration
### Custom Model Aliases
You can create shortcuts for frequently used models in Roo settings:
```
Alias: "fast" → cc/claude-haiku-4-20250514
Alias: "smart" → cc/claude-opus-4-5-20251101
Alias: "code" → cx/deepseek-chat
```
### Multiple Profiles
Set up different profiles for different use cases:
- **Development**: DeepSeek models for code
- **Writing**: Claude models for content
- **Research**: Reasoner models for analysis
## Next Steps
- [Configure Cursor](cursor.md) for IDE integration
- [Set up Continue](continue.md) for VSCode
- [Explore CLI usage](../cli/basic-usage.md)