|
| 1 | +"""Handler for REST API call to provide OpenAI-compatible responses endpoint.""" |
| 2 | + |
| 3 | +import logging |
| 4 | +from typing import Annotated, Any |
| 5 | + |
| 6 | +from fastapi import APIRouter, Depends, HTTPException, Request, status |
| 7 | +from llama_stack_client import APIConnectionError |
| 8 | + |
| 9 | +import constants |
| 10 | +import metrics |
| 11 | +from authentication import get_auth_dependency |
| 12 | +from authentication.interface import AuthTuple |
| 13 | +from authorization.middleware import authorize |
| 14 | +from client import AsyncLlamaStackClientHolder |
| 15 | +from configuration import configuration |
| 16 | +from models.config import Action |
| 17 | +from models.requests import CreateResponseRequest |
| 18 | +from models.responses import ( |
| 19 | + OpenAIResponse, |
| 20 | + ForbiddenResponse, |
| 21 | + UnauthorizedResponse, |
| 22 | + QueryResponse, |
| 23 | +) |
| 24 | +from utils.endpoints import check_configuration_loaded |
| 25 | +from utils.openai_mapping import ( |
| 26 | + map_openai_to_query_request, |
| 27 | + map_query_to_openai_response, |
| 28 | +) |
| 29 | +from app.endpoints.query import retrieve_response |
| 30 | + |
| 31 | +logger = logging.getLogger("app.endpoints.handlers") |
| 32 | +router = APIRouter(tags=["responses"]) |
| 33 | + |
| 34 | +# Response definitions for OpenAPI documentation |
| 35 | +responses_response_definitions: dict[int | str, dict[str, Any]] = { |
| 36 | + 200: { |
| 37 | + "description": "OpenAI-compatible response generated successfully", |
| 38 | + "model": OpenAIResponse, |
| 39 | + }, |
| 40 | + 400: { |
| 41 | + "description": "Missing or invalid credentials provided by client", |
| 42 | + "model": UnauthorizedResponse, |
| 43 | + }, |
| 44 | + 403: { |
| 45 | + "description": "User is not authorized", |
| 46 | + "model": ForbiddenResponse, |
| 47 | + }, |
| 48 | + 422: { |
| 49 | + "description": "Request validation failed", |
| 50 | + "content": { |
| 51 | + "application/json": { |
| 52 | + "example": { |
| 53 | + "response": constants.UNABLE_TO_PROCESS_RESPONSE, |
| 54 | + "cause": "Invalid input parameters or request format", |
| 55 | + } |
| 56 | + } |
| 57 | + }, |
| 58 | + }, |
| 59 | + 500: { |
| 60 | + "description": "Internal server error", |
| 61 | + "content": { |
| 62 | + "application/json": { |
| 63 | + "example": { |
| 64 | + "response": "Unable to connect to Llama Stack", |
| 65 | + "cause": "Connection error.", |
| 66 | + } |
| 67 | + } |
| 68 | + }, |
| 69 | + }, |
| 70 | +} |
| 71 | + |
| 72 | + |
| 73 | +@router.post("/responses", responses=responses_response_definitions) |
| 74 | +@authorize(Action.RESPONSES) |
| 75 | +async def responses_endpoint_handler( |
| 76 | + request: Request, # pylint: disable=unused-argument |
| 77 | + responses_request: CreateResponseRequest, |
| 78 | + auth: Annotated[AuthTuple, Depends(get_auth_dependency())], |
| 79 | +) -> OpenAIResponse: |
| 80 | + """ |
| 81 | + Handle request to the /responses endpoint. |
| 82 | +
|
| 83 | + Processes a POST request to the /responses endpoint, providing OpenAI-compatible |
| 84 | + API responses while using Lightspeed's internal RAG and LLM integration. |
| 85 | + Converts OpenAI request format to internal QueryRequest, processes it through |
| 86 | + existing Lightspeed logic, and converts the response back to OpenAI format. |
| 87 | +
|
| 88 | + This endpoint maintains full compatibility with the OpenAI Responses API |
| 89 | + specification while leveraging all existing Lightspeed functionality including |
| 90 | + authentication, authorization, RAG database queries, and LLM integration. |
| 91 | +
|
| 92 | + Args: |
| 93 | + request: FastAPI Request object containing HTTP request details. |
| 94 | + responses_request: OpenAI-compatible request containing model, input, and options. |
| 95 | + auth: Authentication tuple containing user information and token. |
| 96 | +
|
| 97 | + Returns: |
| 98 | + OpenAIResponse: OpenAI-compatible response with generated content and metadata. |
| 99 | +
|
| 100 | + Raises: |
| 101 | + HTTPException: For connection errors (500) or other processing failures. |
| 102 | +
|
| 103 | + Example: |
| 104 | + ```python |
| 105 | + # Request |
| 106 | + { |
| 107 | + "model": "gpt-4", |
| 108 | + "input": "What is Kubernetes?", |
| 109 | + "instructions": "You are a helpful DevOps assistant" |
| 110 | + } |
| 111 | +
|
| 112 | + # Response |
| 113 | + { |
| 114 | + "id": "resp_67ccd2bed1ec8190b14f964abc0542670bb6a6b452d3795b", |
| 115 | + "object": "response", |
| 116 | + "created_at": 1640995200, |
| 117 | + "status": "completed", |
| 118 | + "model": "gpt-4", |
| 119 | + "output": [...], |
| 120 | + "usage": {...}, |
| 121 | + "metadata": {"referenced_documents": [...]} |
| 122 | + } |
| 123 | + ``` |
| 124 | + """ |
| 125 | + check_configuration_loaded(configuration) |
| 126 | + |
| 127 | + # Extract authentication details |
| 128 | + user_id, _, _skip_userid_check, token = auth # pylint: disable=unused-variable |
| 129 | + |
| 130 | + try: |
| 131 | + # Convert OpenAI request to internal QueryRequest format |
| 132 | + query_request = map_openai_to_query_request(responses_request) |
| 133 | + |
| 134 | + # Get Llama Stack client and retrieve response using existing logic |
| 135 | + client = AsyncLlamaStackClientHolder().get_client() |
| 136 | + |
| 137 | + # For MVP simplicity, use default model/provider selection logic from query.py |
| 138 | + # This will be enhanced in Phase 2 to support explicit model mapping |
| 139 | + summary, conversation_id, referenced_documents, token_usage = ( |
| 140 | + await retrieve_response( |
| 141 | + client, |
| 142 | + responses_request.model, # Pass model directly for now |
| 143 | + query_request, |
| 144 | + token, |
| 145 | + mcp_headers={}, # Empty for MVP |
| 146 | + provider_id="", # Will be determined by existing logic |
| 147 | + ) |
| 148 | + ) |
| 149 | + |
| 150 | + # Create QueryResponse structure from TurnSummary for mapping |
| 151 | + |
| 152 | + internal_query_response = QueryResponse( |
| 153 | + conversation_id=conversation_id, |
| 154 | + response=summary.llm_response, |
| 155 | + rag_chunks=[], # MVP: use empty list (summary.rag_chunks if available) |
| 156 | + tool_calls=None, # MVP: simplified (summary.tool_calls if available) |
| 157 | + referenced_documents=referenced_documents, |
| 158 | + truncated=False, # MVP: default to False |
| 159 | + input_tokens=token_usage.input_tokens, |
| 160 | + output_tokens=token_usage.output_tokens, |
| 161 | + available_quotas={}, # MVP: empty quotas |
| 162 | + ) |
| 163 | + |
| 164 | + # Convert internal response to OpenAI format |
| 165 | + openai_response = map_query_to_openai_response( |
| 166 | + query_response=internal_query_response, |
| 167 | + openai_request=responses_request, |
| 168 | + ) |
| 169 | + |
| 170 | + return openai_response |
| 171 | + |
| 172 | + except APIConnectionError as e: |
| 173 | + # Update metrics for the LLM call failure |
| 174 | + metrics.llm_calls_failures_total.inc() |
| 175 | + logger.error("Unable to connect to Llama Stack: %s", e) |
| 176 | + raise HTTPException( |
| 177 | + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, |
| 178 | + detail={ |
| 179 | + "response": "Unable to connect to Llama Stack", |
| 180 | + "cause": str(e), |
| 181 | + }, |
| 182 | + ) from e |
| 183 | + except (ValueError, AttributeError, TypeError) as e: |
| 184 | + # Handle validation and mapping errors |
| 185 | + logger.error("Request validation or processing error: %s", e) |
| 186 | + raise HTTPException( |
| 187 | + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, |
| 188 | + detail={ |
| 189 | + "response": constants.UNABLE_TO_PROCESS_RESPONSE, |
| 190 | + "cause": f"Invalid input parameters or request format: {str(e)}", |
| 191 | + }, |
| 192 | + ) from e |
0 commit comments