-
Notifications
You must be signed in to change notification settings - Fork 49
[WIP] Add OpenAI Responses API endpoint with MVP functionality #749
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
thoraxe
wants to merge
1
commit into
lightspeed-core:main
Choose a base branch
from
thoraxe:openai-responses
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,192 @@ | ||
| """Handler for REST API call to provide OpenAI-compatible responses endpoint.""" | ||
|
|
||
| import logging | ||
| from typing import Annotated, Any | ||
|
|
||
| from fastapi import APIRouter, Depends, HTTPException, Request, status | ||
| from llama_stack_client import APIConnectionError | ||
|
|
||
| import constants | ||
| import metrics | ||
| from authentication import get_auth_dependency | ||
| from authentication.interface import AuthTuple | ||
| from authorization.middleware import authorize | ||
| from client import AsyncLlamaStackClientHolder | ||
| from configuration import configuration | ||
| from models.config import Action | ||
| from models.requests import CreateResponseRequest | ||
| from models.responses import ( | ||
| OpenAIResponse, | ||
| ForbiddenResponse, | ||
| UnauthorizedResponse, | ||
| QueryResponse, | ||
| ) | ||
| from utils.endpoints import check_configuration_loaded | ||
| from utils.openai_mapping import ( | ||
| map_openai_to_query_request, | ||
| map_query_to_openai_response, | ||
| ) | ||
| from app.endpoints.query import retrieve_response | ||
|
|
||
| logger = logging.getLogger("app.endpoints.handlers") | ||
| router = APIRouter(tags=["responses"]) | ||
|
|
||
| # Response definitions for OpenAPI documentation | ||
| responses_response_definitions: dict[int | str, dict[str, Any]] = { | ||
| 200: { | ||
| "description": "OpenAI-compatible response generated successfully", | ||
| "model": OpenAIResponse, | ||
| }, | ||
| 400: { | ||
| "description": "Missing or invalid credentials provided by client", | ||
| "model": UnauthorizedResponse, | ||
| }, | ||
| 403: { | ||
| "description": "User is not authorized", | ||
| "model": ForbiddenResponse, | ||
| }, | ||
| 422: { | ||
| "description": "Request validation failed", | ||
| "content": { | ||
| "application/json": { | ||
| "example": { | ||
| "response": constants.UNABLE_TO_PROCESS_RESPONSE, | ||
| "cause": "Invalid input parameters or request format", | ||
| } | ||
| } | ||
| }, | ||
| }, | ||
| 500: { | ||
| "description": "Internal server error", | ||
| "content": { | ||
| "application/json": { | ||
| "example": { | ||
| "response": "Unable to connect to Llama Stack", | ||
| "cause": "Connection error.", | ||
| } | ||
| } | ||
| }, | ||
| }, | ||
| } | ||
|
|
||
|
|
||
| @router.post("/responses", responses=responses_response_definitions) | ||
| @authorize(Action.RESPONSES) | ||
| async def responses_endpoint_handler( | ||
| request: Request, # pylint: disable=unused-argument | ||
| responses_request: CreateResponseRequest, | ||
| auth: Annotated[AuthTuple, Depends(get_auth_dependency())], | ||
| ) -> OpenAIResponse: | ||
| """ | ||
| Handle request to the /responses endpoint. | ||
|
|
||
| Processes a POST request to the /responses endpoint, providing OpenAI-compatible | ||
| API responses while using Lightspeed's internal RAG and LLM integration. | ||
| Converts OpenAI request format to internal QueryRequest, processes it through | ||
| existing Lightspeed logic, and converts the response back to OpenAI format. | ||
|
|
||
| This endpoint maintains full compatibility with the OpenAI Responses API | ||
| specification while leveraging all existing Lightspeed functionality including | ||
| authentication, authorization, RAG database queries, and LLM integration. | ||
|
|
||
| Args: | ||
| request: FastAPI Request object containing HTTP request details. | ||
| responses_request: OpenAI-compatible request containing model, input, and options. | ||
| auth: Authentication tuple containing user information and token. | ||
|
|
||
| Returns: | ||
| OpenAIResponse: OpenAI-compatible response with generated content and metadata. | ||
|
|
||
| Raises: | ||
| HTTPException: For connection errors (500) or other processing failures. | ||
|
|
||
| Example: | ||
| ```python | ||
| # Request | ||
| { | ||
| "model": "gpt-4", | ||
| "input": "What is Kubernetes?", | ||
| "instructions": "You are a helpful DevOps assistant" | ||
| } | ||
|
|
||
| # Response | ||
| { | ||
| "id": "resp_67ccd2bed1ec8190b14f964abc0542670bb6a6b452d3795b", | ||
| "object": "response", | ||
| "created_at": 1640995200, | ||
| "status": "completed", | ||
| "model": "gpt-4", | ||
| "output": [...], | ||
| "usage": {...}, | ||
| "metadata": {"referenced_documents": [...]} | ||
| } | ||
| ``` | ||
| """ | ||
| check_configuration_loaded(configuration) | ||
|
|
||
| # Extract authentication details | ||
| user_id, _, _skip_userid_check, token = auth # pylint: disable=unused-variable | ||
|
|
||
| try: | ||
| # Convert OpenAI request to internal QueryRequest format | ||
| query_request = map_openai_to_query_request(responses_request) | ||
|
|
||
| # Get Llama Stack client and retrieve response using existing logic | ||
| client = AsyncLlamaStackClientHolder().get_client() | ||
|
|
||
| # For MVP simplicity, use default model/provider selection logic from query.py | ||
| # This will be enhanced in Phase 2 to support explicit model mapping | ||
| summary, conversation_id, referenced_documents, token_usage = ( | ||
| await retrieve_response( | ||
| client, | ||
| responses_request.model, # Pass model directly for now | ||
| query_request, | ||
| token, | ||
| mcp_headers={}, # Empty for MVP | ||
| provider_id="", # Will be determined by existing logic | ||
| ) | ||
| ) | ||
|
|
||
| # Create QueryResponse structure from TurnSummary for mapping | ||
|
|
||
| internal_query_response = QueryResponse( | ||
| conversation_id=conversation_id, | ||
| response=summary.llm_response, | ||
| rag_chunks=[], # MVP: use empty list (summary.rag_chunks if available) | ||
| tool_calls=None, # MVP: simplified (summary.tool_calls if available) | ||
| referenced_documents=referenced_documents, | ||
| truncated=False, # MVP: default to False | ||
| input_tokens=token_usage.input_tokens, | ||
| output_tokens=token_usage.output_tokens, | ||
| available_quotas={}, # MVP: empty quotas | ||
| ) | ||
|
|
||
| # Convert internal response to OpenAI format | ||
| openai_response = map_query_to_openai_response( | ||
| query_response=internal_query_response, | ||
| openai_request=responses_request, | ||
| ) | ||
|
|
||
| return openai_response | ||
|
|
||
| except APIConnectionError as e: | ||
| # Update metrics for the LLM call failure | ||
| metrics.llm_calls_failures_total.inc() | ||
| logger.error("Unable to connect to Llama Stack: %s", e) | ||
| raise HTTPException( | ||
| status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, | ||
| detail={ | ||
| "response": "Unable to connect to Llama Stack", | ||
| "cause": str(e), | ||
| }, | ||
| ) from e | ||
| except (ValueError, AttributeError, TypeError) as e: | ||
| # Handle validation and mapping errors | ||
| logger.error("Request validation or processing error: %s", e) | ||
| raise HTTPException( | ||
| status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, | ||
| detail={ | ||
| "response": constants.UNABLE_TO_PROCESS_RESPONSE, | ||
| "cause": f"Invalid input parameters or request format: {str(e)}", | ||
| }, | ||
| ) from e | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
note this is not using the responses API from llamastack
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Wouldnt this PR require moving Llama Stack to 0.3.x to use the new Llama Stack Responses API https://llamastack.github.io/docs/api/agents? As the previous Llama Stack Agent APIs are deprecated https://llamastack.github.io/docs/api-deprecated/agents ... i.e.; do we need an explicit LCORE /responses endpoint if we switch to Llama Stack 0.3.x?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
depends on what level of completeness LCORE is willing to live with @maysunfaisal .... the responses API was introduced a few months ago in 0.2.x but was labeled work in progress, with some known bugs and missing pieces
so there could be some staging in play
but charting a roadmap that after some intermediate stages ends up having LCORE leverage the llama stack openai api compatible endpoint, vs. the deprecated agent apis or some other responses api endpoint, should be the end goal