Spaces:
Sleeping
Sleeping
File size: 7,062 Bytes
09da05c | 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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 | """API client for backend communication."""
import base64
import requests
from pathlib import Path
from typing import Dict, List, Optional, Any, Union
from dataclasses import dataclass
@dataclass
class APIClient:
"""Client for interacting with the backend API."""
base_url: str
username: Optional[str] = None
token: Optional[str] = None
def _get_headers(self) -> Dict[str, str]:
"""Get request headers with authentication."""
headers = {"Content-Type": "application/json"}
if self.username and self.token:
headers["X-User"] = self.username
headers["X-Token"] = self.token
return headers
def health_check(self) -> bool:
"""Check if the API server is healthy."""
try:
response = requests.get(f"{self.base_url}/health", timeout=5)
return response.status_code == 200
except Exception:
return False
def register_user(self, username: str, token: str) -> bool:
"""Register a new user with the authentication service."""
try:
response = requests.post(
f"{self.base_url}/v1/auth/register",
json={"user": username, "token": token},
timeout=5,
)
return response.status_code == 200
except Exception:
return False
def validate_auth(self, username: str, token: str) -> bool:
"""Validate user credentials."""
try:
response = requests.post(
f"{self.base_url}/v1/auth/validate",
json={"user": username, "token": token},
timeout=5,
)
if response.status_code == 200:
data = response.json()
return data.get("authorized", False)
return False
except Exception:
return False
def list_personas(self) -> List[Dict[str, Any]]:
"""Get list of available personas."""
try:
response = requests.get(
f"{self.base_url}/v1/personas",
headers=self._get_headers(),
timeout=10,
)
if response.status_code == 200:
data = response.json()
return data.get("personas", [])
return []
except Exception:
return []
def get_persona_profile(self, persona_id: str) -> Optional[Dict[str, Any]]:
"""Get detailed profile for a specific persona."""
try:
response = requests.get(
f"{self.base_url}/v1/personas/{persona_id}/profile",
headers=self._get_headers(),
timeout=10,
)
if response.status_code == 200:
return response.json()
return None
except Exception:
return None
def get_system_prompt(self, persona_id: str) -> Optional[str]:
"""Get system prompt for a persona."""
try:
response = requests.get(
f"{self.base_url}/v1/personas/{persona_id}/system-prompt",
headers=self._get_headers(),
timeout=10,
)
if response.status_code == 200:
data = response.json()
return data.get("system_prompt")
return None
except Exception:
return None
def send_chat_message(
self,
persona_id: str,
query: str,
session_id: Optional[str] = None,
top_k: int = 5,
persona_display_name: Optional[str] = None,
) -> Optional[Dict[str, Any]]:
"""Send a chat message and get response."""
try:
payload = {
"persona_id": persona_id,
"query": query,
"top_k": top_k,
}
if session_id:
payload["session_id"] = session_id
if persona_display_name:
payload["persona_display_name"] = persona_display_name
response = requests.post(
f"{self.base_url}/v1/chat",
json=payload,
headers=self._get_headers(),
timeout=(5, 120), # (connect, read)
)
if response.status_code == 200:
data = response.json()
return data.get("response")
return None
except Exception as e:
print(f"Error sending chat message: {e}")
return None
def upload_file(
self,
filename: str,
content: Union[bytes, str, Path],
bucket: Optional[str] = None,
) -> Optional[Dict[str, Any]]:
"""Upload a file to the ingestion service.
Args:
filename: Name of the file
content: File content as bytes, string path, or Path object
bucket: Optional bucket name (uses default if not specified)
Returns:
Upload response with bucket, key, and size_bytes, or None on error
"""
try:
# Handle different content types
if isinstance(content, (str, Path)):
with open(content, "rb") as f:
file_bytes = f.read()
else:
file_bytes = content
# Encode to base64
content_base64 = base64.b64encode(file_bytes).decode("utf-8")
payload = {
"filename": filename,
"content_base64": content_base64,
}
if bucket:
payload["bucket"] = bucket
response = requests.post(
f"{self.base_url}/v1/ingestion/upload",
json=payload,
headers=self._get_headers(),
timeout=60,
)
if response.status_code == 200:
return response.json()
return None
except Exception as e:
print(f"Error uploading file: {e}")
return None
def generate_report(
self,
persona_id: str,
insights: List[str],
) -> Optional[Dict[str, Any]]:
"""Generate a report for a persona.
Args:
persona_id: ID of the persona
insights: List of insights to include in the report
Returns:
Report response with path to generated report, or None on error
"""
try:
payload = {"insights": insights}
response = requests.post(
f"{self.base_url}/v1/reports/{persona_id}",
json=payload,
headers=self._get_headers(),
timeout=60,
)
if response.status_code == 200:
return response.json()
return None
except Exception as e:
print(f"Error generating report: {e}")
return None
|