File size: 8,999 Bytes
bed5cc5 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 |
"""
Cursor Rules Generator - OpenRouter Adapter
This module implements the LLM adapter for OpenRouter API.
"""
import json
import requests
from typing import Dict, List, Optional, Any
from ..config.settings import Settings
from .adapter import LLMAdapter
class OpenRouterAdapter(LLMAdapter):
"""Adapter for OpenRouter API."""
def __init__(self):
"""Initialize the OpenRouter adapter."""
self.api_key = None
self.api_url = Settings.OPENROUTER_API_URL
self.initialized = False
def initialize(self, api_key: str, **kwargs) -> None:
"""Initialize the adapter with API key and optional parameters.
Args:
api_key: The OpenRouter API key
**kwargs: Additional provider-specific parameters
"""
self.api_key = api_key
self.api_url = kwargs.get('api_url', Settings.OPENROUTER_API_URL)
self.site_url = kwargs.get('site_url', 'https://cursor-rules-generator.example.com')
self.site_name = kwargs.get('site_name', 'Cursor Rules Generator')
self.initialized = True
def validate_api_key(self, api_key: str) -> bool:
"""Validate the OpenRouter API key.
Args:
api_key: The API key to validate
Returns:
bool: True if the API key is valid, False otherwise
"""
try:
# Try to list models with the provided API key
url = f"{self.api_url}/models"
headers = {
"Authorization": f"Bearer {api_key}"
}
response = requests.get(url, headers=headers)
# Check if the request was successful
if response.status_code == 200:
return True
return False
except Exception:
return False
def get_available_models(self) -> List[Dict[str, str]]:
"""Get a list of available OpenRouter models.
Returns:
List[Dict[str, str]]: A list of model information dictionaries
"""
if not self.initialized:
raise ValueError("Adapter not initialized. Call initialize() first.")
try:
# Get available models
url = f"{self.api_url}/models"
headers = {
"Authorization": f"Bearer {self.api_key}"
}
response = requests.get(url, headers=headers)
if response.status_code != 200:
raise ValueError(f"Failed to get models: {response.text}")
data = response.json()
# Format the response
models = []
for model in data.get('data', []):
model_id = model.get('id')
model_name = model.get('name', model_id)
# Skip non-chat models
if not model.get('capabilities', {}).get('chat'):
continue
models.append({
'id': model_id,
'name': model_name
})
# If no models found, return default models
if not models:
models = [
{'id': 'openai/gpt-4o', 'name': 'OpenAI GPT-4o'},
{'id': 'anthropic/claude-3-opus', 'name': 'Anthropic Claude 3 Opus'},
{'id': 'google/gemini-2.5-pro', 'name': 'Google Gemini 2.5 Pro'},
{'id': 'meta-llama/llama-3-70b-instruct', 'name': 'Meta Llama 3 70B'}
]
return models
except Exception as e:
# Return default models on error
return [
{'id': 'openai/gpt-4o', 'name': 'OpenAI GPT-4o'},
{'id': 'anthropic/claude-3-opus', 'name': 'Anthropic Claude 3 Opus'},
{'id': 'google/gemini-2.5-pro', 'name': 'Google Gemini 2.5 Pro'},
{'id': 'meta-llama/llama-3-70b-instruct', 'name': 'Meta Llama 3 70B'}
]
def generate_rule(
self,
model: str,
rule_type: str,
description: str,
content: str,
parameters: Optional[Dict[str, Any]] = None
) -> str:
"""Generate a Cursor Rule using OpenRouter.
Args:
model: The OpenRouter model ID to use
rule_type: The type of rule to generate
description: A short description of the rule's purpose
content: The main content of the rule
parameters: Additional parameters for rule generation
Returns:
str: The generated rule in MDC format
"""
if not self.initialized:
raise ValueError("Adapter not initialized. Call initialize() first.")
# Set default parameters if not provided
if parameters is None:
parameters = {}
# Extract parameters
temperature = parameters.get('temperature', Settings.DEFAULT_TEMPERATURE)
globs = parameters.get('globs', '')
referenced_files = parameters.get('referenced_files', '')
prompt = parameters.get('prompt', '')
# Prepare the prompt for OpenRouter
system_prompt = """
You are a Cursor Rules expert. Create a rule in MDC format based on the provided information.
MDC format example:
---
description: RPC Service boilerplate
globs:
alwaysApply: false
---
- Use our internal RPC pattern when defining services
- Always use snake_case for service names.
@service-template.ts
"""
user_prompt = f"""
Create a Cursor Rule with the following details:
Rule Type: {rule_type}
Description: {description}
Content: {content}
"""
if globs:
user_prompt += f"\nGlobs: {globs}"
if referenced_files:
user_prompt += f"\nReferenced Files: {referenced_files}"
if prompt:
user_prompt += f"\nAdditional Instructions: {prompt}"
# Prepare the API request
url = f"{self.api_url}/chat/completions"
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json",
"HTTP-Referer": self.site_url,
"X-Title": self.site_name
}
payload = {
"model": model,
"messages": [
{
"role": "system",
"content": system_prompt
},
{
"role": "user",
"content": user_prompt
}
],
"temperature": temperature,
"max_tokens": 2048
}
# Make the API request
try:
response = requests.post(url, headers=headers, json=payload)
if response.status_code != 200:
raise ValueError(f"Failed to generate rule: {response.text}")
data = response.json()
# Extract the generated text
generated_text = data.get('choices', [{}])[0].get('message', {}).get('content', '')
# If no text was generated, create a basic rule
if not generated_text:
return self._create_basic_rule(rule_type, description, content, globs, referenced_files)
return generated_text
except Exception as e:
# Create a basic rule on error
return self._create_basic_rule(rule_type, description, content, globs, referenced_files)
def _create_basic_rule(
self,
rule_type: str,
description: str,
content: str,
globs: str = '',
referenced_files: str = ''
) -> str:
"""Create a basic rule in MDC format without using the LLM.
Args:
rule_type: The type of rule
description: The rule description
content: The rule content
globs: Glob patterns for Auto Attached rules
referenced_files: Referenced files
Returns:
str: The rule in MDC format
"""
# Create MDC format
mdc = '---\n'
mdc += f'description: {description}\n'
if rule_type == 'Auto Attached' and globs:
mdc += f'globs: {globs}\n'
if rule_type == 'Always':
mdc += 'alwaysApply: true\n'
else:
mdc += 'alwaysApply: false\n'
mdc += '---\n\n'
mdc += content + '\n'
# Add referenced files
if referenced_files:
mdc += '\n' + referenced_files
return mdc
|