feat(provider): add OpenRouter provider with HTTP-Referer and X-Title headers#1192
feat(provider): add OpenRouter provider with HTTP-Referer and X-Title headers#1192seoeaa wants to merge 10 commits intoagentscope-ai:mainfrom
Conversation
Summary of ChangesHello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request introduces comprehensive support for OpenRouter as a new model provider, significantly expanding the range of available language models within the application. It includes the implementation of a dedicated provider class that handles API interactions, model discovery, and connection management, while also ensuring compliance with OpenRouter's specific HTTP header requirements for proper attribution. Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Changelog
Activity
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
There was a problem hiding this comment.
Code Review
This pull request introduces a new OpenRouterProvider to connect with OpenRouter's API. The implementation is well-structured, but there are a couple of areas for improvement. I've pointed out a case of code duplication with the request headers that can be refactored for better maintainability. Additionally, I've suggested a more efficient implementation for the model list normalization logic. Overall, a good addition.
| from copaw.providers.provider import ModelInfo, Provider | ||
|
|
||
|
|
||
| class OpenRouterProvider(Provider): |
There was a problem hiding this comment.
The default_headers dictionary is hardcoded and duplicated in both the _client method (lines 22-25) and the get_chat_model_instance method (lines 100-103). This violates the DRY (Don't Repeat Yourself) principle and makes the code harder to maintain.
To improve this, you can define the headers as a class-level constant. This ensures that the headers are defined in a single place, making future updates easier.
Example:
class OpenRouterProvider(Provider):
"""OpenRouter provider with required HTTP-Referer and X-Title headers."""
_DEFAULT_HEADERS = {
"HTTP-Referer": "https://copaw.ai",
"X-Title": "CoPaw",
}
def _client(self, timeout: float = 30) -> AsyncOpenAI:
return AsyncOpenAI(
base_url=self.base_url,
api_key=self.api_key,
timeout=timeout,
default_headers=self._DEFAULT_HEADERS,
)
# ... other methods
def get_chat_model_instance(self, model_id: str) -> ChatModelBase:
from .openai_chat_model_compat import OpenAIChatModelCompat
return OpenAIChatModelCompat(
model_name=model_id,
stream=True,
api_key=self.api_key,
client_kwargs={
"base_url": self.base_url,
"default_headers": self._DEFAULT_HEADERS,
},
)| def _normalize_models_payload(payload: Any) -> List[ModelInfo]: | ||
| models: List[ModelInfo] = [] | ||
| rows = getattr(payload, "data", []) | ||
| for row in rows or []: | ||
| model_id = str(getattr(row, "id", "") or "").strip() | ||
| if not model_id: | ||
| continue | ||
| model_name = ( | ||
| str(getattr(row, "name", "") or model_id).strip() or model_id | ||
| ) | ||
| models.append(ModelInfo(id=model_id, name=model_name)) | ||
|
|
||
| deduped: List[ModelInfo] = [] | ||
| seen: set[str] = set() | ||
| for model in models: | ||
| if model.id in seen: | ||
| continue | ||
| seen.add(model.id) | ||
| deduped.append(model) | ||
| return deduped |
There was a problem hiding this comment.
This method can be simplified and made more efficient by using a dictionary for deduplication and combining the two loops into one. This avoids creating an intermediate list and iterating over it a second time. Using a dictionary to store models by their ID is a common and efficient pattern for deduplication while iterating.
| def _normalize_models_payload(payload: Any) -> List[ModelInfo]: | |
| models: List[ModelInfo] = [] | |
| rows = getattr(payload, "data", []) | |
| for row in rows or []: | |
| model_id = str(getattr(row, "id", "") or "").strip() | |
| if not model_id: | |
| continue | |
| model_name = ( | |
| str(getattr(row, "name", "") or model_id).strip() or model_id | |
| ) | |
| models.append(ModelInfo(id=model_id, name=model_name)) | |
| deduped: List[ModelInfo] = [] | |
| seen: set[str] = set() | |
| for model in models: | |
| if model.id in seen: | |
| continue | |
| seen.add(model.id) | |
| deduped.append(model) | |
| return deduped | |
| def _normalize_models_payload(payload: Any) -> List[ModelInfo]: | |
| models: dict[str, ModelInfo] = {} | |
| rows = getattr(payload, "data", []) | |
| for row in rows or []: | |
| model_id = str(getattr(row, "id", "") or "").strip() | |
| if not model_id or model_id in models: | |
| continue | |
| model_name = ( | |
| str(getattr(row, "name", "") or model_id).strip() or model_id | |
| ) | |
| models[model_id] = ModelInfo(id=model_id, name=model_name) | |
| return list(models.values()) |
727f3a5 to
895e62f
Compare
a849a8f to
83ac2fe
Compare
| // Enable discover for providers that support it | ||
| // For local providers (ollama, llama.cpp, mlx) - check base_url | ||
| // For built-in providers with frozen URL - check api_key | ||
| const canDiscover = provider.is_local |
There was a problem hiding this comment.
We add a support_model_discovery field to the ProviderInfo structure in #1342 , try use it instead.
Enhanced OpenRouter Model Filtering - Implementation Summary
This PR has been enhanced with model filtering capabilities for OpenRouter. Here's what was implemented:
Backend Changes (Python)
1. Extended Model Metadata
ExtendedModelInfoclass with fields:provider- provider name (openai, google, anthropic)input_modalities- supported input types (text, image, audio, video, file)output_modalities- supported output types (text, image, audio)pricing- pricing information2. Enhanced OpenRouterProvider (
src/copaw/providers/openrouter_provider.py)_extract_provider()- extracts provider from model ID (e.g., 'openai' from 'openai/gpt-4o')_extract_model_name()- extracts model name after slash (e.g., 'gpt-4o')fetch_extended_models()- fetches all models with full metadataget_available_providers()- returns unique provider list3. New API Endpoints (
src/copaw/app/routers/providers.py)GET /api/models/openrouter/series- get available providersPOST /api/models/openrouter/discover-extended- discover models with metadataPOST /api/models/openrouter/models/filter- filter by provider/modalityFrontend Changes (TypeScript/React)
1. Filter UI (
console/src/pages/Settings/Models/components/modals/RemoteModelManageModal.tsx)2. i18n Translations
Added translations for all 4 languages (EN, RU, JA, ZH):
models.filterModels,models.filterByProvider,models.filterByModalitymodels.getModels,models.discovered,models.addmodels.clearAll,models.clearAllModels,models.allModelsClearedKey Features
This enhancement provides users with full control over which OpenRouter models they want to add to their configuration.