MCPcopy Create free account
hub / github.com/abetlen/llama-cpp-python / get_route_handler

Method get_route_handler

llama_cpp/server/errors.py:162–212  ·  view source on GitHub ↗

Defines custom route handler that catches exceptions and formats in OpenAI style error response

(
        self,
    )

Source from the content-addressed store, hash-verified

160 )
161
162 def get_route_handler(
163 self,
164 ) -> Callable[[Request], Coroutine[None, None, Response]]:
165 """Defines custom route handler that catches exceptions and formats
166 in OpenAI style error response"""
167
168 original_route_handler = super().get_route_handler()
169
170 async def custom_route_handler(request: Request) -> Response:
171 try:
172 start_sec = time.perf_counter()
173 response = await original_route_handler(request)
174 elapsed_time_ms = int((time.perf_counter() - start_sec) * 1000)
175 response.headers["openai-processing-ms"] = f"{elapsed_time_ms}"
176 return response
177 except HTTPException as unauthorized:
178 # api key check failed
179 raise unauthorized
180 except Exception as exc:
181 json_body = await request.json()
182 try:
183 if "messages" in json_body:
184 # Chat completion
185 body: Optional[
186 Union[
187 CreateChatCompletionRequest,
188 CreateCompletionRequest,
189 CreateEmbeddingRequest,
190 ]
191 ] = CreateChatCompletionRequest(**json_body)
192 elif "prompt" in json_body:
193 # Text completion
194 body = CreateCompletionRequest(**json_body)
195 else:
196 # Embedding
197 body = CreateEmbeddingRequest(**json_body)
198 except Exception:
199 # Invalid request body
200 body = None
201
202 # Get proper error message from the exception
203 (
204 status_code,
205 error_message,
206 ) = self.error_message_wrapper(error=exc, body=body)
207 return JSONResponse(
208 {"error": error_message},
209 status_code=status_code,
210 )
211
212 return custom_route_handler

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected