Fix permissions issue for config files by using direct /tmp path
Browse files- api_wrapper.py +66 -11
- app.py +50 -11
api_wrapper.py
CHANGED
@@ -22,8 +22,9 @@ USE_WRAPPER = os.environ.get("USE_WRAPPER", "false").lower() in ("true", "1", "y
|
|
22 |
|
23 |
# Путь к директории с агентами
|
24 |
if IS_HF_SPACE or USE_WRAPPER:
|
25 |
-
|
26 |
-
|
|
|
27 |
else:
|
28 |
AGENT_DIR = os.environ.get("TEN_AGENT_DIR", "/tmp/ten_user/agents")
|
29 |
|
@@ -31,6 +32,16 @@ logger.info(f"Using agent directory: {AGENT_DIR}")
|
|
31 |
logger.info(f"Running in HuggingFace Space: {IS_HF_SPACE}")
|
32 |
logger.info(f"Using Wrapper: {USE_WRAPPER}")
|
33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
class TENAgentHandler(http.server.BaseHTTPRequestHandler):
|
35 |
def log_message(self, format, *args):
|
36 |
"""Переопределение логирования для вывода в stdout"""
|
@@ -78,15 +89,38 @@ class TENAgentHandler(http.server.BaseHTTPRequestHandler):
|
|
78 |
"""Обработка запроса на получение списка графов"""
|
79 |
try:
|
80 |
property_file = Path(AGENT_DIR) / "property.json"
|
|
|
|
|
81 |
if not property_file.exists():
|
82 |
logger.error(f"Property file not found at {property_file}")
|
83 |
-
|
84 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
85 |
|
86 |
with open(property_file, "r") as f:
|
87 |
property_data = json.load(f)
|
88 |
|
89 |
graphs = property_data.get("graphs", [])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
90 |
self._set_headers()
|
91 |
self.wfile.write(json.dumps(graphs).encode())
|
92 |
logger.info(f"Returned {len(graphs)} graphs")
|
@@ -101,7 +135,8 @@ class TENAgentHandler(http.server.BaseHTTPRequestHandler):
|
|
101 |
"status": "ok",
|
102 |
"time": time.time(),
|
103 |
"is_hf_space": IS_HF_SPACE,
|
104 |
-
"using_wrapper": True
|
|
|
105 |
}).encode())
|
106 |
|
107 |
def _handle_list(self):
|
@@ -125,9 +160,14 @@ class TENAgentHandler(http.server.BaseHTTPRequestHandler):
|
|
125 |
try:
|
126 |
property_file = Path(AGENT_DIR) / "property.json"
|
127 |
if not property_file.exists():
|
128 |
-
|
129 |
-
|
130 |
-
|
|
|
|
|
|
|
|
|
|
|
131 |
|
132 |
with open(property_file, "r") as f:
|
133 |
property_data = json.load(f)
|
@@ -183,7 +223,8 @@ class TENAgentHandler(http.server.BaseHTTPRequestHandler):
|
|
183 |
"status": "ok",
|
184 |
"timestamp": time.time(),
|
185 |
"server": "ten-agent-api-wrapper",
|
186 |
-
"in_hf_space": IS_HF_SPACE
|
|
|
187 |
}).encode())
|
188 |
|
189 |
def _handle_token_generate(self, request_data):
|
@@ -200,16 +241,30 @@ class TENAgentHandler(http.server.BaseHTTPRequestHandler):
|
|
200 |
|
201 |
def _handle_start(self, request_data):
|
202 |
"""Обработка запроса на запуск сессии"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
203 |
self._set_headers()
|
204 |
# Возвращаем успешный статус и ID сессии
|
205 |
response = {
|
206 |
"status": "ok",
|
207 |
"session_id": f"dummy_session_{int(time.time())}",
|
208 |
"message": "Session started successfully",
|
209 |
-
"graph_file":
|
210 |
}
|
211 |
self.wfile.write(json.dumps(response).encode())
|
212 |
-
logger.info(f"Started session with graph: {
|
213 |
|
214 |
def _handle_stop(self, request_data):
|
215 |
"""Обработка запроса на остановку сессии"""
|
|
|
22 |
|
23 |
# Путь к директории с агентами
|
24 |
if IS_HF_SPACE or USE_WRAPPER:
|
25 |
+
# В HuggingFace используем корневую директорию /tmp
|
26 |
+
TMP_DIR = os.environ.get("TMP_DIR", "/tmp")
|
27 |
+
AGENT_DIR = os.environ.get("TEN_AGENT_DIR", TMP_DIR)
|
28 |
else:
|
29 |
AGENT_DIR = os.environ.get("TEN_AGENT_DIR", "/tmp/ten_user/agents")
|
30 |
|
|
|
32 |
logger.info(f"Running in HuggingFace Space: {IS_HF_SPACE}")
|
33 |
logger.info(f"Using Wrapper: {USE_WRAPPER}")
|
34 |
|
35 |
+
# Проверяем наличие файлов конфигурации
|
36 |
+
agent_dir_path = Path(AGENT_DIR)
|
37 |
+
if agent_dir_path.exists():
|
38 |
+
logger.info(f"Checking files in agent directory {AGENT_DIR}:")
|
39 |
+
for file in agent_dir_path.iterdir():
|
40 |
+
if file.name.endswith('.json'):
|
41 |
+
logger.info(f" - {file.name} ({os.path.getsize(file)}b)")
|
42 |
+
else:
|
43 |
+
logger.warning(f"Agent directory {AGENT_DIR} does not exist!")
|
44 |
+
|
45 |
class TENAgentHandler(http.server.BaseHTTPRequestHandler):
|
46 |
def log_message(self, format, *args):
|
47 |
"""Переопределение логирования для вывода в stdout"""
|
|
|
89 |
"""Обработка запроса на получение списка графов"""
|
90 |
try:
|
91 |
property_file = Path(AGENT_DIR) / "property.json"
|
92 |
+
logger.info(f"Looking for property file at {property_file}")
|
93 |
+
|
94 |
if not property_file.exists():
|
95 |
logger.error(f"Property file not found at {property_file}")
|
96 |
+
|
97 |
+
# Проверяем, возможно файл находится в другой директории
|
98 |
+
alt_property_file = Path("/tmp/property.json")
|
99 |
+
if alt_property_file.exists():
|
100 |
+
logger.info(f"Found property file at alternative location: {alt_property_file}")
|
101 |
+
property_file = alt_property_file
|
102 |
+
else:
|
103 |
+
self.send_error(404, "Property file not found")
|
104 |
+
return
|
105 |
|
106 |
with open(property_file, "r") as f:
|
107 |
property_data = json.load(f)
|
108 |
|
109 |
graphs = property_data.get("graphs", [])
|
110 |
+
|
111 |
+
# Для каждого графа проверяем наличие файла
|
112 |
+
for graph in graphs:
|
113 |
+
file_name = graph.get("file", "")
|
114 |
+
file_path = Path(AGENT_DIR) / file_name
|
115 |
+
alt_file_path = Path("/tmp") / file_name
|
116 |
+
|
117 |
+
if file_path.exists():
|
118 |
+
logger.info(f"Graph file exists: {file_path}")
|
119 |
+
elif alt_file_path.exists():
|
120 |
+
logger.info(f"Graph file exists at alternative location: {alt_file_path}")
|
121 |
+
else:
|
122 |
+
logger.warning(f"Graph file not found: {file_name}")
|
123 |
+
|
124 |
self._set_headers()
|
125 |
self.wfile.write(json.dumps(graphs).encode())
|
126 |
logger.info(f"Returned {len(graphs)} graphs")
|
|
|
135 |
"status": "ok",
|
136 |
"time": time.time(),
|
137 |
"is_hf_space": IS_HF_SPACE,
|
138 |
+
"using_wrapper": True,
|
139 |
+
"agent_dir": AGENT_DIR
|
140 |
}).encode())
|
141 |
|
142 |
def _handle_list(self):
|
|
|
160 |
try:
|
161 |
property_file = Path(AGENT_DIR) / "property.json"
|
162 |
if not property_file.exists():
|
163 |
+
# Проверяем альтернативную директорию
|
164 |
+
alt_property_file = Path("/tmp/property.json")
|
165 |
+
if alt_property_file.exists():
|
166 |
+
property_file = alt_property_file
|
167 |
+
else:
|
168 |
+
logger.error(f"Property file not found at {property_file}")
|
169 |
+
self.send_error(404, "Property file not found")
|
170 |
+
return
|
171 |
|
172 |
with open(property_file, "r") as f:
|
173 |
property_data = json.load(f)
|
|
|
223 |
"status": "ok",
|
224 |
"timestamp": time.time(),
|
225 |
"server": "ten-agent-api-wrapper",
|
226 |
+
"in_hf_space": IS_HF_SPACE,
|
227 |
+
"agent_dir": AGENT_DIR
|
228 |
}).encode())
|
229 |
|
230 |
def _handle_token_generate(self, request_data):
|
|
|
241 |
|
242 |
def _handle_start(self, request_data):
|
243 |
"""Обработка запроса на запуск сессии"""
|
244 |
+
graph_file = request_data.get("graph_file", "")
|
245 |
+
logger.info(f"Starting session with graph file: {graph_file}")
|
246 |
+
|
247 |
+
# Проверяем наличие файла графа
|
248 |
+
graph_path = Path(AGENT_DIR) / graph_file
|
249 |
+
alt_graph_path = Path("/tmp") / graph_file
|
250 |
+
|
251 |
+
if graph_path.exists():
|
252 |
+
logger.info(f"Found graph file at: {graph_path}")
|
253 |
+
elif alt_graph_path.exists():
|
254 |
+
logger.info(f"Found graph file at alternative location: {alt_graph_path}")
|
255 |
+
else:
|
256 |
+
logger.warning(f"Graph file not found: {graph_file}")
|
257 |
+
|
258 |
self._set_headers()
|
259 |
# Возвращаем успешный статус и ID сессии
|
260 |
response = {
|
261 |
"status": "ok",
|
262 |
"session_id": f"dummy_session_{int(time.time())}",
|
263 |
"message": "Session started successfully",
|
264 |
+
"graph_file": graph_file
|
265 |
}
|
266 |
self.wfile.write(json.dumps(response).encode())
|
267 |
+
logger.info(f"Started session with graph: {graph_file}")
|
268 |
|
269 |
def _handle_stop(self, request_data):
|
270 |
"""Обработка запроса на остановку сессии"""
|
app.py
CHANGED
@@ -71,6 +71,12 @@ def create_config_files():
|
|
71 |
"""Создает базовые файлы конфигурации"""
|
72 |
print("Создание конфигурационных файлов...")
|
73 |
|
|
|
|
|
|
|
|
|
|
|
|
|
74 |
# Создаем property.json с графами
|
75 |
property_data = {
|
76 |
"name": "TEN Agent Demo",
|
@@ -91,8 +97,13 @@ def create_config_files():
|
|
91 |
]
|
92 |
}
|
93 |
|
94 |
-
|
95 |
-
|
|
|
|
|
|
|
|
|
|
|
96 |
|
97 |
# Создаем voice_agent.json
|
98 |
voice_agent = {
|
@@ -155,8 +166,13 @@ def create_config_files():
|
|
155 |
"root": "start"
|
156 |
}
|
157 |
|
158 |
-
|
159 |
-
|
|
|
|
|
|
|
|
|
|
|
160 |
|
161 |
# Создаем chat_agent.json (упрощенная версия)
|
162 |
chat_agent = {
|
@@ -195,10 +211,19 @@ def create_config_files():
|
|
195 |
"root": "start"
|
196 |
}
|
197 |
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
202 |
|
203 |
def start_api_server():
|
204 |
"""Запускает API сервер"""
|
@@ -209,6 +234,14 @@ def start_api_server():
|
|
209 |
api_env["TEN_AGENT_DIR"] = str(AGENTS_DIR)
|
210 |
api_env["API_PORT"] = str(API_PORT)
|
211 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
212 |
# В HuggingFace Space нужны дополнительные настройки
|
213 |
if IS_HF_SPACE:
|
214 |
print("Configuring API server for HuggingFace Space environment...")
|
@@ -217,7 +250,7 @@ def start_api_server():
|
|
217 |
# Отключаем логирование в файл
|
218 |
api_env["TEN_LOG_DISABLE_FILE"] = "true"
|
219 |
# Указываем путь для временных файлов
|
220 |
-
api_env["TMP_DIR"] =
|
221 |
|
222 |
# Запускаем Python API wrapper
|
223 |
api_cmd = ["python", "api_wrapper.py"]
|
@@ -638,13 +671,17 @@ def start_simple_ui():
|
|
638 |
def main():
|
639 |
# Создаем директории и файлы конфигурации
|
640 |
create_directories()
|
641 |
-
|
|
|
|
|
|
|
|
|
642 |
|
643 |
# Запускаем API сервер
|
644 |
api_process = start_api_server()
|
645 |
if not api_process:
|
646 |
print("Не удалось запустить API сервер")
|
647 |
-
return
|
648 |
|
649 |
# Пробуем запустить Playground UI через Next.js
|
650 |
ui_process = start_playground()
|
@@ -683,6 +720,8 @@ def main():
|
|
683 |
api_process.terminate()
|
684 |
if ui_process:
|
685 |
ui_process.terminate()
|
|
|
|
|
686 |
|
687 |
if __name__ == "__main__":
|
688 |
# Корректная обработка сигналов
|
|
|
71 |
"""Создает базовые файлы конфигурации"""
|
72 |
print("Создание конфигурационных файлов...")
|
73 |
|
74 |
+
# Используем директорию в /tmp напрямую, без вложенных директорий
|
75 |
+
config_dir = Path("/tmp")
|
76 |
+
property_file_path = config_dir / "property.json"
|
77 |
+
voice_agent_path = config_dir / "voice_agent.json"
|
78 |
+
chat_agent_path = config_dir / "chat_agent.json"
|
79 |
+
|
80 |
# Создаем property.json с графами
|
81 |
property_data = {
|
82 |
"name": "TEN Agent Demo",
|
|
|
97 |
]
|
98 |
}
|
99 |
|
100 |
+
try:
|
101 |
+
with open(property_file_path, "w") as f:
|
102 |
+
json.dump(property_data, f, indent=2)
|
103 |
+
print(f"Файл {property_file_path} создан успешно")
|
104 |
+
except Exception as e:
|
105 |
+
print(f"Ошибка при создании {property_file_path}: {e}")
|
106 |
+
return False
|
107 |
|
108 |
# Создаем voice_agent.json
|
109 |
voice_agent = {
|
|
|
166 |
"root": "start"
|
167 |
}
|
168 |
|
169 |
+
try:
|
170 |
+
with open(voice_agent_path, "w") as f:
|
171 |
+
json.dump(voice_agent, f, indent=2)
|
172 |
+
print(f"Файл {voice_agent_path} создан успешно")
|
173 |
+
except Exception as e:
|
174 |
+
print(f"Ошибка при создании {voice_agent_path}: {e}")
|
175 |
+
return False
|
176 |
|
177 |
# Создаем chat_agent.json (упрощенная версия)
|
178 |
chat_agent = {
|
|
|
211 |
"root": "start"
|
212 |
}
|
213 |
|
214 |
+
try:
|
215 |
+
with open(chat_agent_path, "w") as f:
|
216 |
+
json.dump(chat_agent, f, indent=2)
|
217 |
+
print(f"Файл {chat_agent_path} создан успешно")
|
218 |
+
except Exception as e:
|
219 |
+
print(f"Ошибка при создании {chat_agent_path}: {e}")
|
220 |
+
return False
|
221 |
+
|
222 |
+
# Обновляем глобальную переменную AGENTS_DIR для использования нового пути
|
223 |
+
global AGENTS_DIR
|
224 |
+
AGENTS_DIR = config_dir
|
225 |
+
print(f"Конфигурационные файлы созданы успешно в директории {config_dir}")
|
226 |
+
return True
|
227 |
|
228 |
def start_api_server():
|
229 |
"""Запускает API сервер"""
|
|
|
234 |
api_env["TEN_AGENT_DIR"] = str(AGENTS_DIR)
|
235 |
api_env["API_PORT"] = str(API_PORT)
|
236 |
|
237 |
+
# Выводим информацию о директории с агентами для отладки
|
238 |
+
print(f"Директория с агентами: {AGENTS_DIR}")
|
239 |
+
print(f"Файлы в директории агентов:")
|
240 |
+
if AGENTS_DIR.exists():
|
241 |
+
for file in AGENTS_DIR.iterdir():
|
242 |
+
if file.name.endswith('.json'):
|
243 |
+
print(f" - {file.name} ({os.path.getsize(file)}b)")
|
244 |
+
|
245 |
# В HuggingFace Space нужны дополнительные настройки
|
246 |
if IS_HF_SPACE:
|
247 |
print("Configuring API server for HuggingFace Space environment...")
|
|
|
250 |
# Отключаем логирование в файл
|
251 |
api_env["TEN_LOG_DISABLE_FILE"] = "true"
|
252 |
# Указываем путь для временных файлов
|
253 |
+
api_env["TMP_DIR"] = "/tmp"
|
254 |
|
255 |
# Запускаем Python API wrapper
|
256 |
api_cmd = ["python", "api_wrapper.py"]
|
|
|
671 |
def main():
|
672 |
# Создаем директории и файлы конфигурации
|
673 |
create_directories()
|
674 |
+
|
675 |
+
# Пытаемся создать конфигурационные файлы
|
676 |
+
if not create_config_files():
|
677 |
+
print("ОШИБКА: Не удалось создать конфигурационные файлы!")
|
678 |
+
return 1
|
679 |
|
680 |
# Запускаем API сервер
|
681 |
api_process = start_api_server()
|
682 |
if not api_process:
|
683 |
print("Не удалось запустить API сервер")
|
684 |
+
return 1
|
685 |
|
686 |
# Пробуем запустить Playground UI через Next.js
|
687 |
ui_process = start_playground()
|
|
|
720 |
api_process.terminate()
|
721 |
if ui_process:
|
722 |
ui_process.terminate()
|
723 |
+
|
724 |
+
return 0
|
725 |
|
726 |
if __name__ == "__main__":
|
727 |
# Корректная обработка сигналов
|