|
| 1 | +"""Handler for REST API calls to manage conversation history.""" |
| 2 | + |
| 3 | +import logging |
| 4 | +from typing import Any |
| 5 | + |
| 6 | +from llama_stack_client import APIConnectionError |
| 7 | + |
| 8 | +from fastapi import APIRouter, HTTPException, status, Depends |
| 9 | + |
| 10 | +from client import LlamaStackClientHolder |
| 11 | +from configuration import configuration |
| 12 | +from models.responses import ConversationResponse, ConversationDeleteResponse |
| 13 | +from auth import get_auth_dependency |
| 14 | +from utils.endpoints import check_configuration_loaded |
| 15 | +from utils.suid import check_suid |
| 16 | + |
| 17 | +logger = logging.getLogger("app.endpoints.handlers") |
| 18 | +router = APIRouter(tags=["conversations"]) |
| 19 | +auth_dependency = get_auth_dependency() |
| 20 | + |
| 21 | +conversation_id_to_agent_id: dict[str, str] = {} |
| 22 | + |
| 23 | +conversation_responses: dict[int | str, dict[str, Any]] = { |
| 24 | + 200: { |
| 25 | + "conversation_id": "123e4567-e89b-12d3-a456-426614174000", |
| 26 | + "session_data": { |
| 27 | + "session_id": "123e4567-e89b-12d3-a456-426614174000", |
| 28 | + "turns": [], |
| 29 | + "started_at": "2024-01-01T00:00:00Z", |
| 30 | + }, |
| 31 | + }, |
| 32 | + 404: { |
| 33 | + "detail": { |
| 34 | + "response": "Conversation not found", |
| 35 | + "cause": "The specified conversation ID does not exist.", |
| 36 | + } |
| 37 | + }, |
| 38 | + 503: { |
| 39 | + "detail": { |
| 40 | + "response": "Unable to connect to Llama Stack", |
| 41 | + "cause": "Connection error.", |
| 42 | + } |
| 43 | + }, |
| 44 | +} |
| 45 | + |
| 46 | +conversation_delete_responses: dict[int | str, dict[str, Any]] = { |
| 47 | + 200: { |
| 48 | + "conversation_id": "123e4567-e89b-12d3-a456-426614174000", |
| 49 | + "success": True, |
| 50 | + "message": "Conversation deleted successfully", |
| 51 | + }, |
| 52 | + 404: { |
| 53 | + "detail": { |
| 54 | + "response": "Conversation not found", |
| 55 | + "cause": "The specified conversation ID does not exist.", |
| 56 | + } |
| 57 | + }, |
| 58 | + 503: { |
| 59 | + "detail": { |
| 60 | + "response": "Unable to connect to Llama Stack", |
| 61 | + "cause": "Connection error.", |
| 62 | + } |
| 63 | + }, |
| 64 | +} |
| 65 | + |
| 66 | + |
| 67 | +@router.get("/conversations/{conversation_id}", responses=conversation_responses) |
| 68 | +def get_conversation_endpoint_handler( |
| 69 | + conversation_id: str, |
| 70 | + _auth: Any = Depends(auth_dependency), |
| 71 | +) -> ConversationResponse: |
| 72 | + """Handle request to retrieve a conversation by ID.""" |
| 73 | + check_configuration_loaded(configuration) |
| 74 | + |
| 75 | + # Validate conversation ID format |
| 76 | + if not check_suid(conversation_id): |
| 77 | + logger.error("Invalid conversation ID format: %s", conversation_id) |
| 78 | + raise HTTPException( |
| 79 | + status_code=status.HTTP_400_BAD_REQUEST, |
| 80 | + detail={ |
| 81 | + "response": "Invalid conversation ID format", |
| 82 | + "cause": f"Conversation ID {conversation_id} is not a valid UUID", |
| 83 | + }, |
| 84 | + ) |
| 85 | + |
| 86 | + agent_id = conversation_id_to_agent_id.get(conversation_id) |
| 87 | + if not agent_id: |
| 88 | + logger.error("Agent ID not found for conversation %s", conversation_id) |
| 89 | + raise HTTPException( |
| 90 | + status_code=status.HTTP_404_NOT_FOUND, |
| 91 | + detail={ |
| 92 | + "response": "conversation ID not found", |
| 93 | + "cause": f"conversation ID {conversation_id} not found!", |
| 94 | + }, |
| 95 | + ) |
| 96 | + |
| 97 | + logger.info("Retrieving conversation %s", conversation_id) |
| 98 | + |
| 99 | + try: |
| 100 | + client = LlamaStackClientHolder().get_client() |
| 101 | + |
| 102 | + session_data = client.agents.session.retrieve( |
| 103 | + agent_id=agent_id, session_id=conversation_id |
| 104 | + ) |
| 105 | + |
| 106 | + logger.info("Successfully retrieved conversation %s", conversation_id) |
| 107 | + |
| 108 | + return ConversationResponse( |
| 109 | + conversation_id=conversation_id, |
| 110 | + session_data=( |
| 111 | + session_data.model_dump() |
| 112 | + if hasattr(session_data, "model_dump") |
| 113 | + else dict(session_data) |
| 114 | + ), |
| 115 | + ) |
| 116 | + |
| 117 | + except APIConnectionError as e: |
| 118 | + logger.error("Unable to connect to Llama Stack: %s", e) |
| 119 | + raise HTTPException( |
| 120 | + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, |
| 121 | + detail={ |
| 122 | + "response": "Unable to connect to Llama Stack", |
| 123 | + "cause": str(e), |
| 124 | + }, |
| 125 | + ) from e |
| 126 | + except Exception as e: |
| 127 | + # Handle case where session doesn't exist or other errors |
| 128 | + logger.error("Error retrieving conversation %s: %s", conversation_id, e) |
| 129 | + raise HTTPException( |
| 130 | + status_code=status.HTTP_404_NOT_FOUND, |
| 131 | + detail={ |
| 132 | + "response": "Conversation not found", |
| 133 | + "cause": f"Conversation {conversation_id} could not be retrieved: {str(e)}", |
| 134 | + }, |
| 135 | + ) from e |
| 136 | + |
| 137 | + |
| 138 | +@router.delete( |
| 139 | + "/conversations/{conversation_id}", responses=conversation_delete_responses |
| 140 | +) |
| 141 | +def delete_conversation_endpoint_handler( |
| 142 | + conversation_id: str, |
| 143 | + _auth: Any = Depends(auth_dependency), |
| 144 | +) -> ConversationDeleteResponse: |
| 145 | + """Handle request to delete a conversation by ID.""" |
| 146 | + check_configuration_loaded(configuration) |
| 147 | + |
| 148 | + # Validate conversation ID format |
| 149 | + if not check_suid(conversation_id): |
| 150 | + logger.error("Invalid conversation ID format: %s", conversation_id) |
| 151 | + raise HTTPException( |
| 152 | + status_code=status.HTTP_400_BAD_REQUEST, |
| 153 | + detail={ |
| 154 | + "response": "Invalid conversation ID format", |
| 155 | + "cause": f"Conversation ID {conversation_id} is not a valid UUID", |
| 156 | + }, |
| 157 | + ) |
| 158 | + agent_id = conversation_id_to_agent_id.get(conversation_id) |
| 159 | + if not agent_id: |
| 160 | + logger.error("Agent ID not found for conversation %s", conversation_id) |
| 161 | + raise HTTPException( |
| 162 | + status_code=status.HTTP_404_NOT_FOUND, |
| 163 | + detail={ |
| 164 | + "response": "conversation ID not found", |
| 165 | + "cause": f"conversation ID {conversation_id} not found!", |
| 166 | + }, |
| 167 | + ) |
| 168 | + logger.info("Deleting conversation %s", conversation_id) |
| 169 | + |
| 170 | + try: |
| 171 | + # Get Llama Stack client |
| 172 | + client = LlamaStackClientHolder().get_client() |
| 173 | + # Delete session using the conversation_id as session_id |
| 174 | + # In this implementation, conversation_id and session_id are the same |
| 175 | + client.agents.session.delete(agent_id=agent_id, session_id=conversation_id) |
| 176 | + |
| 177 | + logger.info("Successfully deleted conversation %s", conversation_id) |
| 178 | + |
| 179 | + return ConversationDeleteResponse( |
| 180 | + conversation_id=conversation_id, |
| 181 | + success=True, |
| 182 | + message="Conversation deleted successfully", |
| 183 | + ) |
| 184 | + |
| 185 | + except APIConnectionError as e: |
| 186 | + logger.error("Unable to connect to Llama Stack: %s", e) |
| 187 | + raise HTTPException( |
| 188 | + status_code=status.HTTP_503_SERVICE_UNAVAILABLE, |
| 189 | + detail={ |
| 190 | + "response": "Unable to connect to Llama Stack", |
| 191 | + "cause": str(e), |
| 192 | + }, |
| 193 | + ) from e |
| 194 | + except Exception as e: |
| 195 | + # Handle case where session doesn't exist or other errors |
| 196 | + logger.error("Error deleting conversation %s: %s", conversation_id, e) |
| 197 | + raise HTTPException( |
| 198 | + status_code=status.HTTP_404_NOT_FOUND, |
| 199 | + detail={ |
| 200 | + "response": "Conversation not found", |
| 201 | + "cause": f"Conversation {conversation_id} could not be deleted: {str(e)}", |
| 202 | + }, |
| 203 | + ) from e |
0 commit comments