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

Method handle_request

api/openrouter_handler.py:109–237  ·  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

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