virgil-ai/src/services/session_service.py
2025-07-28 17:14:16 +03:00

97 lines
No EOL
3.5 KiB
Python

import httpx
import uuid
from typing import Optional, Dict, Any, List
from ..config import settings
class SessionService:
"""Service for managing chat sessions with talestorm-ai"""
def __init__(self):
self.base_url = settings.TALESTORM_API_BASE_URL
self.api_key = settings.TALESTORM_API_KEY
self.agent_id = settings.TALESTORM_AGENT_ID
async def get_client(self) -> httpx.AsyncClient:
"""Get HTTP client for talestorm-ai API"""
headers = {}
if self.api_key:
headers["X-API-Key"] = self.api_key
return httpx.AsyncClient(
base_url=self.base_url,
headers=headers
)
async def list_agents(self) -> List[Dict[str, Any]]:
"""List available agents from talestorm-ai"""
async with await self.get_client() as client:
try:
response = await client.get("/agents/")
if response.status_code == 200:
return response.json()
else:
return []
except Exception:
return []
async def get_default_agent(self) -> Optional[Dict[str, Any]]:
"""Get the configured agent or the first available agent"""
# First try to get the configured agent
if self.agent_id:
async with await self.get_client() as client:
try:
response = await client.get(f"/agents/{self.agent_id}")
if response.status_code == 200:
return response.json()
except Exception:
pass
# Fallback to first available agent
agents = await self.list_agents()
if agents:
return agents[0]
return None
async def create_session(self, agent_id: Optional[str] = None) -> Optional[str]:
"""Create a new chat session in talestorm-ai"""
async with await self.get_client() as client:
if not agent_id:
# Use the default agent ID for backward compatibility
agent_id = self.agent_id or settings.TALESTORM_AGENT_ID
response = await client.post("/sessions/", params={"agent_id": agent_id})
print(response.request.url)
session_data = response.json()
return str(session_data["id"])
async def get_session(self, session_id: str) -> Optional[Dict[str, Any]]:
"""Get session details from talestorm-ai"""
async with await self.get_client() as client:
try:
response = await client.get(f"/sessions/{session_id}")
if response.status_code == 200:
return response.json()
return None
except Exception:
return None
async def list_sessions(self) -> List[Dict[str, Any]]:
"""List all sessions from talestorm-ai"""
async with await self.get_client() as client:
try:
response = await client.get("/sessions/")
if response.status_code == 200:
return response.json()
return []
except Exception:
return []
async def validate_session(self, session_id: str) -> bool:
"""Validate if a session exists and is accessible"""
session = await self.get_session(session_id)
return session is not None
# Global session service instance
session_service = SessionService()