|
| 1 | +import json |
| 2 | + |
| 3 | +from fastapi import Header, HTTPException, Request |
| 4 | + |
| 5 | +from codegate.clients.detector import DetectClient |
| 6 | +from codegate.pipeline.factory import PipelineFactory |
| 7 | +from codegate.providers.openai import OpenAIProvider |
| 8 | + |
| 9 | + |
| 10 | +class OpenRouterProvider(OpenAIProvider): |
| 11 | + def __init__(self, pipeline_factory: PipelineFactory): |
| 12 | + super().__init__(pipeline_factory) |
| 13 | + |
| 14 | + @property |
| 15 | + def provider_route_name(self) -> str: |
| 16 | + return "openrouter" |
| 17 | + |
| 18 | + def _setup_routes(self): |
| 19 | + @self.router.post(f"/{self.provider_route_name}/api/v1/chat/completions") |
| 20 | + @self.router.post(f"/{self.provider_route_name}/chat/completions") |
| 21 | + @DetectClient() |
| 22 | + async def create_completion( |
| 23 | + request: Request, |
| 24 | + authorization: str = Header(..., description="Bearer token"), |
| 25 | + ): |
| 26 | + if not authorization.startswith("Bearer "): |
| 27 | + raise HTTPException(status_code=401, detail="Invalid authorization header") |
| 28 | + |
| 29 | + api_key = authorization.split(" ")[1] |
| 30 | + body = await request.body() |
| 31 | + data = json.loads(body) |
| 32 | + |
| 33 | + base_url = self._get_base_url() |
| 34 | + data["base_url"] = base_url |
| 35 | + |
| 36 | + # litellm workaround - add openrouter/ prefix to model name to make it openai-compatible |
| 37 | + # once we get rid of litellm, this can simply be removed |
| 38 | + original_model = data.get("model", "") |
| 39 | + if not original_model.startswith("openrouter/"): |
| 40 | + data["model"] = f"openrouter/{original_model}" |
| 41 | + |
| 42 | + return await self.process_request( |
| 43 | + data, |
| 44 | + api_key, |
| 45 | + request.url.path, |
| 46 | + request.state.detected_client, |
| 47 | + ) |
0 commit comments