MCPcopy Create free account
hub / github.com/Roy3838/Observer / handle_request

Method handle_request

api/openrouter_handler.py:119–247  ·  view source on GitHub ↗

Process a /v1/chat/completions request asynchronously via OpenRouter. Translates display model name to actual OpenRouter model ID. Returns either dict (non-streaming) or StreamingResponse (streaming).

(self, request_data: dict)

Source from the content-addressed store, hash-verified

117 }
118
119 async def handle_request(self, request_data: dict):
120 """
121 Process a /v1/chat/completions request asynchronously via OpenRouter.
122 Translates display model name to actual OpenRouter model ID.
123 Returns either dict (non-streaming) or StreamingResponse (streaming).
124 """
125 if not self.api_key:
126 raise ConfigError("OPENROUTER_API_KEY is not configured on the server.")
127
128 # --- Get Display Name and Translate to Actual Model ID ---
129 display_model_name = request_data.get("model")
130 if not display_model_name:
131 raise ValueError("Request data must include a 'model' field (using the display name).")
132
133 # --- Special Case: NULL Model ---
134 if display_model_name == "NULL":
135 logger.info("NULL model requested, returning empty response without API call")
136
137 if request_data.get("stream", False):
138 # Return streaming response for NULL
139 return StreamingResponse(
140 self._generate_null_stream(),
141 media_type="text/event-stream"
142 )
143 else:
144 # Return non-streaming response for NULL
145 return {
146 "id": f"chatcmpl-null-{int(time.time())}",
147 "object": "chat.completion",
148 "created": int(time.time()),
149 "model": "NULL",
150 "choices": [{
151 "index": 0,
152 "message": {
153 "role": "assistant",
154 "content": " "
155 },
156 "finish_reason": "stop"
157 }],
158 "usage": {
159 "prompt_tokens": 0,
160 "completion_tokens": 1,
161 "total_tokens": 1
162 }
163 }
164 # --- End Special Case ---
165
166 # Look up the display name in our map
167 model_info = self.model_map.get(display_model_name)
168 if not model_info:
169 # If the display name isn't found, the model is unsupported by this mapping
170 logger.warning(f"Received request for unmapped OpenRouter model display name: {display_model_name}")
171 raise ValueError(f"Model display name '{display_model_name}' is not recognized or supported.")
172
173 actual_model_id = model_info.get("model_id")
174 if not actual_model_id:
175 # Should not happen if map is defined correctly, but good practice to check
176 logger.error(f"Internal configuration error: Missing 'model_id' for display name '{display_model_name}' in model_map.")

Callers

nothing calls this directly

Calls 8

_generate_null_streamMethod · 0.95
ConfigErrorClass · 0.90
get_http_clientFunction · 0.90
BackendAPIErrorClass · 0.90
HandlerErrorClass · 0.90
infoMethod · 0.80
errorMethod · 0.80

Tested by

no test coverage detected