|
1 | 1 | """ |
2 | 2 | API entrypoint for backend API. |
3 | 3 | """ |
4 | | -from fastapi import FastAPI |
| 4 | +from fastapi import FastAPI, HTTPException |
5 | 5 | from fastapi.middleware.cors import CORSMiddleware |
6 | 6 |
|
7 | 7 | import uuid |
@@ -53,3 +53,43 @@ def run_cosmic_works_ai_agent(request: AIRequest): |
53 | 53 |
|
54 | 54 | # Run the agent with the provided prompt. |
55 | 55 | return { "message": agent_pool[session_id].run(prompt), "session_id": session_id } |
| 56 | + |
| 57 | + |
| 58 | +# ======================== |
| 59 | +import os |
| 60 | +from dotenv import load_dotenv |
| 61 | +from azure.cosmos import CosmosClient |
| 62 | +from pydantic import BaseModel |
| 63 | +from typing import List |
| 64 | + |
| 65 | +load_dotenv() |
| 66 | + |
| 67 | +# Your existing Cosmos DB client and container setup |
| 68 | +CONNECTION_STRING = os.environ.get("COSMOS_DB_CONNECTION_STRING") |
| 69 | +client = CosmosClient.from_connection_string(CONNECTION_STRING) |
| 70 | +db = client.get_database_client("cosmic_works") |
| 71 | +chat_session_container = db.get_container_client("chat_session") |
| 72 | + |
| 73 | +# Define the model for a Chat Session response |
| 74 | +class ChatSessionResponse(BaseModel): |
| 75 | + session_id: str |
| 76 | + title: str |
| 77 | + |
| 78 | +@app.get("/sessions") #, response_model=List[ChatSessionResponse]) |
| 79 | +def list_sessions(): |
| 80 | + """ |
| 81 | + Endpoint to list all chat sessions. |
| 82 | + """ |
| 83 | + try: |
| 84 | + # Query to get all sessions in the chat_session_container |
| 85 | + query = "SELECT c.session_id, c.title FROM c" |
| 86 | + sessions = list(chat_session_container.query_items( |
| 87 | + query=query, |
| 88 | + enable_cross_partition_query=True |
| 89 | + )) |
| 90 | + |
| 91 | + # Convert the sessions into a list of ChatSessionResponse objects |
| 92 | + session_responses = [ChatSessionResponse(session_id=session['session_id'], title=session['title']) for session in sessions] |
| 93 | + return session_responses |
| 94 | + except Exception as e: |
| 95 | + raise HTTPException(status_code=500, detail=f"Failed to retrieve sessions: {str(e)}") |
0 commit comments