3v324v23 commited on
Commit
2d96520
·
1 Parent(s): cc37d72

Улучшение API wrapper для HuggingFace Space: добавлена надежная инициализация графов

Browse files
Files changed (1) hide show
  1. api_wrapper.py +183 -26
api_wrapper.py CHANGED
@@ -38,18 +38,33 @@ class TENAgentHandler(http.server.BaseHTTPRequestHandler):
38
  try:
39
  property_file = Path(AGENT_DIR) / "property.json"
40
  if not property_file.exists():
41
- self.send_error(404, "Property file not found")
42
- return
 
43
 
44
  with open(property_file, "r") as f:
45
  property_data = json.load(f)
46
 
47
  graphs = property_data.get("graphs", [])
 
 
 
48
  self._set_headers()
49
  self.wfile.write(json.dumps(graphs).encode())
50
  except Exception as e:
51
  print(f"Error reading property.json: {e}")
52
- self.send_error(500, f"Internal error: {e}")
 
 
 
 
 
 
 
 
 
 
 
53
 
54
  elif self.path in ["/health", "/"]:
55
  # Просто возвращаем, что API сервер работает
@@ -77,8 +92,31 @@ class TENAgentHandler(http.server.BaseHTTPRequestHandler):
77
 
78
  # Обработка запросов к API TEN Graph Designer
79
  elif self.path.startswith("/api/designer/") or self.path.startswith("/api/dev/"):
80
- self._set_headers()
81
- self.wfile.write(json.dumps({"data": [], "status": 200, "message": "Success"}).encode())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
  else:
84
  # Для всех остальных запросов возвращаем 404
@@ -153,6 +191,137 @@ class TENAgentHandler(http.server.BaseHTTPRequestHandler):
153
  traceback.print_exc()
154
  self.send_error(500, f"Internal server error: {e}")
155
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  def run(server_class=http.server.HTTPServer, handler_class=TENAgentHandler, port=8080):
157
  server_address = ('', port)
158
  httpd = server_class(server_address, handler_class)
@@ -169,31 +338,19 @@ def run(server_class=http.server.HTTPServer, handler_class=TENAgentHandler, port
169
  property_file = agent_dir_path / "property.json"
170
  if not property_file.exists():
171
  print(f"WARNING: property.json not found in {AGENT_DIR}")
172
- print("Creating minimal property.json...")
173
-
174
- # Создаем базовый property.json
175
- property_data = {
176
- "name": "TEN Agent Example",
177
- "version": "0.0.1",
178
- "extensions": ["openai_chatgpt"],
179
- "description": "A basic voice agent with OpenAI",
180
- "graphs": [
181
- {
182
- "name": "Voice Agent",
183
- "description": "Basic voice agent with OpenAI",
184
- "file": "voice_agent.json"
185
- }
186
- ]
187
- }
188
-
189
  try:
190
- with open(property_file, "w") as f:
191
- json.dump(property_data, f, indent=2)
192
- print(f"Created {property_file}")
193
  except Exception as e:
194
- print(f"ERROR: Could not create property.json: {e}")
195
 
196
  try:
 
197
  httpd.serve_forever()
198
  except KeyboardInterrupt:
199
  print("Shutting down API server...")
 
38
  try:
39
  property_file = Path(AGENT_DIR) / "property.json"
40
  if not property_file.exists():
41
+ print("⚠️ Property file not found at", property_file)
42
+ # Создаем базовый файл свойств на месте
43
+ create_basic_property_file(property_file)
44
 
45
  with open(property_file, "r") as f:
46
  property_data = json.load(f)
47
 
48
  graphs = property_data.get("graphs", [])
49
+ print(f"✅ Returning {len(graphs)} graphs from property.json")
50
+ print(f"Graphs: {json.dumps(graphs, indent=2)}")
51
+
52
  self._set_headers()
53
  self.wfile.write(json.dumps(graphs).encode())
54
  except Exception as e:
55
  print(f"Error reading property.json: {e}")
56
+ traceback.print_exc()
57
+
58
+ # Возвращаем резервный список графов
59
+ fallback_graphs = [
60
+ {
61
+ "name": "Voice Agent (Fallback)",
62
+ "description": "Basic voice agent with OpenAI",
63
+ "file": "voice_agent.json"
64
+ }
65
+ ]
66
+ self._set_headers()
67
+ self.wfile.write(json.dumps(fallback_graphs).encode())
68
 
69
  elif self.path in ["/health", "/"]:
70
  # Просто возвращаем, что API сервер работает
 
92
 
93
  # Обработка запросов к API TEN Graph Designer
94
  elif self.path.startswith("/api/designer/") or self.path.startswith("/api/dev/"):
95
+ if "/packages/reload" in self.path:
96
+ # Возвращаем структурированный ответ с графами
97
+ property_file = Path(AGENT_DIR) / "property.json"
98
+ if property_file.exists():
99
+ with open(property_file, "r") as f:
100
+ property_data = json.load(f)
101
+
102
+ graphs = property_data.get("graphs", [])
103
+ response_data = {
104
+ "data": graphs,
105
+ "status": 200,
106
+ "message": "Success"
107
+ }
108
+ else:
109
+ response_data = {
110
+ "data": [],
111
+ "status": 200,
112
+ "message": "Success"
113
+ }
114
+
115
+ self._set_headers()
116
+ self.wfile.write(json.dumps(response_data).encode())
117
+ else:
118
+ self._set_headers()
119
+ self.wfile.write(json.dumps({"data": [], "status": 200, "message": "Success"}).encode())
120
 
121
  else:
122
  # Для всех остальных запросов возвращаем 404
 
191
  traceback.print_exc()
192
  self.send_error(500, f"Internal server error: {e}")
193
 
194
+ def create_basic_property_file(filepath):
195
+ """Создает базовый property.json файл"""
196
+ print(f"Creating basic property.json file at {filepath}")
197
+
198
+ # Создаем базовый property.json
199
+ property_data = {
200
+ "name": "TEN Agent Example",
201
+ "version": "0.0.1",
202
+ "extensions": ["openai_chatgpt"],
203
+ "description": "A basic voice agent with OpenAI",
204
+ "graphs": [
205
+ {
206
+ "name": "Voice Agent",
207
+ "description": "Basic voice agent with OpenAI",
208
+ "file": "voice_agent.json"
209
+ },
210
+ {
211
+ "name": "Chat Agent",
212
+ "description": "Simple chat agent",
213
+ "file": "chat_agent.json"
214
+ }
215
+ ]
216
+ }
217
+
218
+ try:
219
+ # Убедимся, что директория существует
220
+ filepath.parent.mkdir(exist_ok=True, parents=True)
221
+
222
+ with open(filepath, "w") as f:
223
+ json.dump(property_data, f, indent=2)
224
+ print(f"✅ Created property.json at {filepath}")
225
+
226
+ # Также создаем базовые файлы графов
227
+ create_basic_graph_files(filepath.parent)
228
+
229
+ return True
230
+ except Exception as e:
231
+ print(f"❌ Error creating property.json: {e}")
232
+ traceback.print_exc()
233
+ return False
234
+
235
+ def create_basic_graph_files(dir_path):
236
+ """Создает базовые файлы графов"""
237
+ print(f"Creating basic graph files in {dir_path}")
238
+
239
+ # Создаем voice_agent.json
240
+ voice_agent = {
241
+ "_ten": {"version": "0.0.1"},
242
+ "nodes": [
243
+ {
244
+ "id": "start",
245
+ "type": "start",
246
+ "data": {"x": 100, "y": 100}
247
+ },
248
+ {
249
+ "id": "openai_chatgpt",
250
+ "type": "openai_chatgpt",
251
+ "data": {
252
+ "x": 300,
253
+ "y": 200,
254
+ "properties": {
255
+ "model": "gpt-3.5-turbo",
256
+ "temperature": 0.7,
257
+ "system_prompt": "You are a helpful assistant."
258
+ }
259
+ }
260
+ },
261
+ {
262
+ "id": "end",
263
+ "type": "end",
264
+ "data": {"x": 500, "y": 100}
265
+ }
266
+ ],
267
+ "edges": [
268
+ {
269
+ "id": "start_to_chatgpt",
270
+ "source": "start",
271
+ "target": "openai_chatgpt"
272
+ },
273
+ {
274
+ "id": "chatgpt_to_end",
275
+ "source": "openai_chatgpt",
276
+ "target": "end"
277
+ }
278
+ ],
279
+ "groups": [],
280
+ "templates": [],
281
+ "root": "start"
282
+ }
283
+
284
+ try:
285
+ with open(dir_path / "voice_agent.json", "w") as f:
286
+ json.dump(voice_agent, f, indent=2)
287
+ print(f"✅ Created voice_agent.json")
288
+
289
+ # Создаем chat_agent.json (аналогичный voice_agent.json)
290
+ chat_agent = dict(voice_agent)
291
+ chat_agent["nodes"][1]["data"]["properties"]["system_prompt"] = "You are a helpful chat assistant."
292
+
293
+ with open(dir_path / "chat_agent.json", "w") as f:
294
+ json.dump(chat_agent, f, indent=2)
295
+ print(f"✅ Created chat_agent.json")
296
+
297
+ # Создаем manifest.json
298
+ manifest = {
299
+ "_ten": {"version": "0.0.1"},
300
+ "name": "default",
301
+ "agents": [
302
+ {
303
+ "name": "voice_agent",
304
+ "description": "A simple voice agent",
305
+ "type": "voice"
306
+ },
307
+ {
308
+ "name": "chat_agent",
309
+ "description": "A text chat agent",
310
+ "type": "chat"
311
+ }
312
+ ]
313
+ }
314
+
315
+ with open(dir_path / "manifest.json", "w") as f:
316
+ json.dump(manifest, f, indent=2)
317
+ print(f"✅ Created manifest.json")
318
+
319
+ return True
320
+ except Exception as e:
321
+ print(f"❌ Error creating graph files: {e}")
322
+ traceback.print_exc()
323
+ return False
324
+
325
  def run(server_class=http.server.HTTPServer, handler_class=TENAgentHandler, port=8080):
326
  server_address = ('', port)
327
  httpd = server_class(server_address, handler_class)
 
338
  property_file = agent_dir_path / "property.json"
339
  if not property_file.exists():
340
  print(f"WARNING: property.json not found in {AGENT_DIR}")
341
+ create_basic_property_file(property_file)
342
+ else:
343
+ print(f"✅ Using existing property.json at {property_file}")
344
+ # Выводим содержимое
 
 
 
 
 
 
 
 
 
 
 
 
 
345
  try:
346
+ with open(property_file, "r") as f:
347
+ property_data = json.load(f)
348
+ print(f"Property.json content: {json.dumps(property_data, indent=2)}")
349
  except Exception as e:
350
+ print(f"Error reading property.json: {e}")
351
 
352
  try:
353
+ print(f"✅ API server is ready to receive requests!")
354
  httpd.serve_forever()
355
  except KeyboardInterrupt:
356
  print("Shutting down API server...")