File size: 9,409 Bytes
588adc0 cc37d72 588adc0 cc37d72 2e3dab3 588adc0 cc37d72 588adc0 cc37d72 588adc0 cc37d72 588adc0 cc37d72 2e3dab3 cc37d72 588adc0 cc37d72 2e3dab3 cc37d72 2e3dab3 cc37d72 588adc0 cc37d72 588adc0 cc37d72 588adc0 cc37d72 588adc0 cc37d72 588adc0 cc37d72 588adc0 cc37d72 588adc0 cc37d72 588adc0 cc37d72 2e3dab3 cc37d72 588adc0 cc37d72 588adc0 cc37d72 588adc0 cc37d72 588adc0 cc37d72 |
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 |
#!/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) |