File size: 2,591 Bytes
e61d441 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
#
# SPDX-FileCopyrightText: Hadad <hadad@linuxmail.org>
# SPDX-License-Identifier: Apache-2.0
#
# Import APIRouter and HTTPException classes from FastAPI framework
# APIRouter is used to create modular route handlers
# HTTPException is used to generate HTTP error responses with specific status codes and details
from fastapi import APIRouter, HTTPException
# Import Optional type hint from typing module
# Optional is used to indicate that a function parameter can be of a specified type or None
from typing import Optional
# Import session_store dictionary from the sessions module located in src.cores package
# session_store holds active session data keyed by session identifiers
from src.cores.sessions import session_store
# Create an instance of APIRouter to define routes related to session history
router = APIRouter()
# Define an asynchronous GET endpoint at path "/history" to retrieve chat history for a session
@router.get("/history")
async def get_history(session_id: Optional[str] = None):
"""
This function handles GET requests to fetch the chat history for a specific session.
Parameters:
- session_id (Optional[str]): A string representing the unique identifier of the session.
This parameter is optional in the function signature but required for successful retrieval.
Returns:
- A JSON object containing:
- "session_id": The provided session identifier string.
- "history": A list of past input-response pairs stored in the session.
Raises:
- HTTPException with status code 404 and a descriptive message if:
- The session_id is not provided (None or empty).
- The session_id does not exist in the session_store dictionary, indicating no active session.
"""
# Check if session_id is missing or does not exist in the session_store dictionary
if not session_id or session_id not in session_store:
# Raise an HTTP 404 Not Found error with a clear message indicating the issue
raise HTTPException(status_code=404, detail="Session not found or session_id missing.")
# Retrieve the session data tuple from session_store using the session_id key
# The tuple contains two elements; the first is ignored here, the second is the session data dictionary
_, session_data = session_store[session_id]
# Return a dictionary with the session_id and the chat history extracted from the session data
# This dictionary will be automatically converted to JSON by FastAPI when sending the response
return {"session_id": session_id, "history": session_data["history"]}
|