#!/usr/bin/env python3 import http.server import json import os import sys import datetime import traceback from pathlib import Path # Путь к директории с агентами AGENT_DIR = os.environ.get("TEN_AGENT_DIR", "/tmp/ten_user/agents") class TENAgentHandler(http.server.BaseHTTPRequestHandler): def _set_headers(self, content_type="application/json"): self.send_response(200) self.send_header('Content-type', content_type) self.send_header('Access-Control-Allow-Origin', '*') self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS') self.send_header('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With') self.end_headers() def do_OPTIONS(self): self._set_headers() def log_request(self, code='-', size='-'): # Переопределяем, чтобы не логировать каждый запрос в stderr # особенно health checks, которые могут забивать логи if self.path != '/health': super().log_request(code, size) def do_GET(self): try: print(f"GET request: {self.path}") # Базовые API эндпоинты if self.path in ["/graphs", "/api/graphs"]: # Чтение property.json для получения списка графов try: property_file = Path(AGENT_DIR) / "property.json" if not property_file.exists(): self.send_error(404, "Property file not found") return with open(property_file, "r") as f: property_data = json.load(f) graphs = property_data.get("graphs", []) self._set_headers() self.wfile.write(json.dumps(graphs).encode()) except Exception as e: print(f"Error reading property.json: {e}") self.send_error(500, f"Internal error: {e}") elif self.path in ["/health", "/"]: # Просто возвращаем, что API сервер работает self._set_headers() self.wfile.write(json.dumps({ "status": "ok", "time": str(datetime.datetime.now()), "message": "TEN Agent API wrapper is running" }).encode()) elif self.path == "/list": # Возвращаем пустой список сессий self._set_headers() self.wfile.write(json.dumps([]).encode()) elif self.path.startswith("/dev-tmp/"): # Обработка всех запросов к /dev-tmp/ self._set_headers() self.wfile.write(json.dumps({}).encode()) elif self.path == "/vector/document/preset/list": # Возвращаем пустой список предустановок векторов self._set_headers() self.wfile.write(json.dumps([]).encode()) # Обработка запросов к API TEN Graph Designer elif self.path.startswith("/api/designer/") or self.path.startswith("/api/dev/"): self._set_headers() self.wfile.write(json.dumps({"data": [], "status": 200, "message": "Success"}).encode()) else: # Для всех остальных запросов возвращаем 404 self.send_error(404, "Not found") except Exception as e: print(f"Error handling GET request: {e}") traceback.print_exc() self.send_error(500, f"Internal server error: {e}") def do_POST(self): try: print(f"POST request: {self.path}") # Читаем тело запроса content_length = int(self.headers['Content-Length']) if 'Content-Length' in self.headers else 0 post_data = self.rfile.read(content_length) try: request_data = json.loads(post_data) if content_length > 0 else {} except json.JSONDecodeError: request_data = {} print(f"Request data: {request_data}") if self.path == "/ping": # Для ping запросов просто возвращаем успешный статус self._set_headers() self.wfile.write(json.dumps({"status": "ok"}).encode()) elif self.path == "/token/generate": # Для запросов на генерацию токена возвращаем простой токен # Это нужно для Agora SDK self._set_headers() response = { "token": "dummy_token_for_agora", "request_id": request_data.get("RequestId", ""), "channel_name": request_data.get("ChannelName", ""), "uid": request_data.get("Uid", 0) } self.wfile.write(json.dumps(response).encode()) elif self.path == "/start": # Для запросов на запуск сессии возвращаем успешный статус self._set_headers() # Возвращаем идентификатор сессии для совместимости session_id = "fallback-session-" + datetime.datetime.now().strftime("%Y%m%d%H%M%S") self.wfile.write(json.dumps({ "status": "ok", "session_id": session_id }).encode()) elif self.path == "/stop": # Для запросов на остановку сессии возвращаем успешный статус self._set_headers() self.wfile.write(json.dumps({"status": "ok"}).encode()) elif self.path.startswith("/vector/document/"): # Для запросов на обновление или загрузку документов возвращаем успешный статус self._set_headers() self.wfile.write(json.dumps({"status": "ok", "message": "Operation completed"}).encode()) # API для TEN Graph Designer elif self.path.startswith("/api/designer/") or self.path.startswith("/api/dev/"): self._set_headers() self.wfile.write(json.dumps({"data": {}, "status": 200, "message": "Success"}).encode()) else: # Для всех остальных запросов возвращаем 404 self.send_error(404, "Not found") except Exception as e: print(f"Error handling POST request: {e}") traceback.print_exc() self.send_error(500, f"Internal server error: {e}") def run(server_class=http.server.HTTPServer, handler_class=TENAgentHandler, port=8080): server_address = ('', port) httpd = server_class(server_address, handler_class) print(f"Starting API server on port {port}...") print(f"Using agent directory: {AGENT_DIR}") # Проверяем, что директория с агентами существует agent_dir_path = Path(AGENT_DIR) if not agent_dir_path.exists(): print(f"WARNING: Agent directory {AGENT_DIR} does not exist, creating it...") agent_dir_path.mkdir(exist_ok=True, parents=True) # Проверка наличия необходимых файлов property_file = agent_dir_path / "property.json" if not property_file.exists(): print(f"WARNING: property.json not found in {AGENT_DIR}") print("Creating minimal property.json...") # Создаем базовый property.json property_data = { "name": "TEN Agent Example", "version": "0.0.1", "extensions": ["openai_chatgpt"], "description": "A basic voice agent with OpenAI", "graphs": [ { "name": "Voice Agent", "description": "Basic voice agent with OpenAI", "file": "voice_agent.json" } ] } try: with open(property_file, "w") as f: json.dump(property_data, f, indent=2) print(f"Created {property_file}") except Exception as e: print(f"ERROR: Could not create property.json: {e}") try: httpd.serve_forever() except KeyboardInterrupt: print("Shutting down API server...") except Exception as e: print(f"Error in API server: {e}") traceback.print_exc() if __name__ == "__main__": port = int(os.environ.get("API_PORT", 8080)) run(port=port)