import aiohttp from typing import Optional, List, Dict, Any from app.core.config import settings class AIAgentClient: """ Клиент для взаимодействия с внешним AI-agent сервисом. Сервис должен быть доступен в Docker сети и предоставлять следующие endpoints: - POST /api/v1/chat - для чата с ИИ - POST /api/v1/schedule/generate - для генерации расписаний Примечание: Структура API endpoints может отличаться в зависимости от реализации внешнего сервиса. При необходимости измените пути в методах этого класса. """ def __init__(self, base_url: Optional[str] = None): self.base_url = base_url or settings.AI_AGENT_BASE_URL if not self.base_url.endswith('/'): self.base_url = self.base_url.rstrip('/') async def chat( self, message: str, conversation_id: Optional[str] = None, context: Optional[List[Dict[str, Any]]] = None ) -> Dict[str, Any]: """ Отправить сообщение в чат через AI-agent сервис. Ожидаемый формат ответа от сервиса: { "response": "текст ответа", "conversation_id": "id беседы", "tokens_used": 100, "model": "модель" } или формат GigaChat API (с полем choices). """ url = f"{self.base_url}/api/v1/chat" payload = { "message": message, } if conversation_id: payload["conversation_id"] = conversation_id if context: payload["context"] = context async with aiohttp.ClientSession() as session: async with session.post(url, json=payload, timeout=aiohttp.ClientTimeout(total=120)) as response: if response.status != 200: error_text = await response.text() raise Exception( f"AI-agent service error: HTTP {response.status} - {error_text}" ) result = await response.json() return result async def generate_schedule( self, child_age: int, preferences: List[str], date: str, description: Optional[str] = None ) -> Dict[str, Any]: """Сгенерировать расписание через AI-agent сервис""" url = f"{self.base_url}/api/v1/schedule/generate" payload = { "child_age": child_age, "preferences": preferences, "date": date } if description: payload["description"] = description async with aiohttp.ClientSession() as session: async with session.post(url, json=payload, timeout=aiohttp.ClientTimeout(total=120)) as response: if response.status != 200: error_text = await response.text() raise Exception( f"AI-agent service error: HTTP {response.status} - {error_text}" ) result = await response.json() return result async def generate_text( self, prompt: str, model: Optional[str] = None ) -> str: """Генерация текста по промпту через AI-agent сервис""" # Для совместимости с текущим интерфейсом используем chat endpoint result = await self.chat(message=prompt) # Извлекаем текст ответа # Предполагаем, что ответ имеет структуру ChatResponse response_text = result.get("response", "") if not response_text: # Если структура другая, пытаемся извлечь из choices (как в GigaChat формате) choices = result.get("choices", []) if choices: response_text = choices[0].get("message", {}).get("content", "") return response_text # Создаем экземпляр клиента ai_agent_client = AIAgentClient()