-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
1799 lines (1476 loc) · 54.3 KB
/
Copy pathserver.py
File metadata and controls
1799 lines (1476 loc) · 54.3 KB
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import contextlib
import inspect
import os
import subprocess
import sys
import tempfile
import time
import uuid
from collections import defaultdict
from pathlib import Path
from typing import Any
# Add parent to path to import intentforge
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from fastapi import FastAPI, HTTPException, Request, WebSocket, WebSocketDisconnect
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from intentforge import Intent, IntentForge, IntentType, TargetPlatform
from intentforge.services import services
# Initialize FastAPI
app = FastAPI(title="IntentForge API Server")
# Add CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# =============================================================================
# Rate Limiting
# =============================================================================
RATE_LIMIT_ENABLED = os.getenv("RATE_LIMIT_ENABLED", "true").lower() == "true"
RATE_LIMIT_REQUESTS = int(os.getenv("RATE_LIMIT_REQUESTS", "60")) # requests per window
RATE_LIMIT_WINDOW = int(os.getenv("RATE_LIMIT_WINDOW", "60")) # window in seconds
# In-memory rate limit storage (use Redis in production)
rate_limit_data: dict[str, list[float]] = defaultdict(list)
def get_client_ip(request: Request) -> str:
"""Get client IP from request, considering proxies"""
forwarded = request.headers.get("X-Forwarded-For")
if forwarded:
return forwarded.split(",")[0].strip()
return request.client.host if request.client else "unknown"
def check_rate_limit(client_ip: str) -> tuple[bool, dict]:
"""Check if client is within rate limit. Returns (allowed, info)"""
now = time.time()
window_start = now - RATE_LIMIT_WINDOW
# Clean old entries
rate_limit_data[client_ip] = [t for t in rate_limit_data[client_ip] if t > window_start]
current_requests = len(rate_limit_data[client_ip])
remaining = max(0, RATE_LIMIT_REQUESTS - current_requests)
reset_time = int(window_start + RATE_LIMIT_WINDOW)
info = {
"X-RateLimit-Limit": str(RATE_LIMIT_REQUESTS),
"X-RateLimit-Remaining": str(remaining),
"X-RateLimit-Reset": str(reset_time),
}
if current_requests >= RATE_LIMIT_REQUESTS:
return False, info
# Record this request
rate_limit_data[client_ip].append(now)
return True, info
@app.middleware("http")
async def rate_limit_middleware(request: Request, call_next):
"""Rate limiting middleware"""
if not RATE_LIMIT_ENABLED:
return await call_next(request)
# Skip rate limiting for static files
if request.url.path.startswith("/examples/") or request.url.path.startswith("/static/"):
return await call_next(request)
client_ip = get_client_ip(request)
allowed, info = check_rate_limit(client_ip)
if not allowed:
return JSONResponse(
status_code=429,
content={
"success": False,
"error": "Rate limit exceeded",
"retry_after": RATE_LIMIT_WINDOW,
},
headers=info,
)
response = await call_next(request)
# Add rate limit headers to response
for key, value in info.items():
response.headers[key] = value
return response
# =============================================================================
# API Key Authentication
# =============================================================================
API_KEYS_ENABLED = os.getenv("API_KEYS_ENABLED", "false").lower() == "true"
API_KEYS = set(filter(None, os.getenv("API_KEYS", "").split(",")))
# Public endpoints that don't require authentication
PUBLIC_ENDPOINTS = {"/health", "/docs", "/openapi.json", "/redoc"}
async def verify_api_key(request: Request) -> bool:
"""Verify API key from header or query parameter"""
if not API_KEYS_ENABLED:
return True
# Check if endpoint is public
if request.url.path in PUBLIC_ENDPOINTS:
return True
# Skip auth for static files
if request.url.path.startswith("/examples/") or request.url.path.startswith("/static/"):
return True
# Get API key from header or query
api_key = request.headers.get("X-API-Key") or request.query_params.get("api_key")
if not api_key:
return False
return api_key in API_KEYS
@app.middleware("http")
async def api_key_middleware(request: Request, call_next):
"""Middleware to check API key authentication"""
if not await verify_api_key(request):
return JSONResponse(
status_code=401,
content={
"success": False,
"error": "Invalid or missing API key",
"hint": "Set X-API-Key header or api_key query parameter",
},
)
return await call_next(request)
# Initialize IntentForge
# We use Ollama by default as per dev workflow
provider = os.getenv("LLM_PROVIDER", "ollama")
model = os.getenv("LLM_MODEL", "llama3.1:8b")
print(f"Initializing IntentForge with Provider: {provider}, Model: {model}")
forge = IntentForge(
enable_auto_deploy=True, # We want to execute the code
sandbox_mode=True, # Safely
provider=provider,
model=model,
)
class IntentRequest(BaseModel):
description: str
intent_type: str = "workflow" # Default to workflow/generic
context: dict[str, Any] = {}
class IntentResponse(BaseModel):
success: bool
message: str
result: Any | None = None
original_intent: str
@app.post("/api/intent", response_model=IntentResponse)
async def process_intent(request: IntentRequest):
"""
Process a natural language intent
"""
print(f"Received intent: {request.description}")
# Map string type to Enum
try:
if request.intent_type == "workflow":
i_type = IntentType.WORKFLOW
elif request.intent_type == "api":
i_type = IntentType.API_ENDPOINT
else:
i_type = IntentType.WORKFLOW
# Create Intent
intent = Intent(
description=request.description,
intent_type=i_type,
target_platform=TargetPlatform.GENERIC_PYTHON,
context=request.context,
)
# Process
result = await forge.process_intent(intent)
if not result.success:
return IntentResponse(
success=False,
message=f"Generation failed: {result.validation_errors}",
original_intent=request.description,
)
# Even if generation succeeded, execution might fail or be empty if auto_deploy is off
# However, we enabled auto_deploy=True.
# The result.execution_result should contain the return value of the executed code
exec_res = result.execution_result
if exec_res and not exec_res.success:
print("❌ Execution Failed")
print("FAILED CODE:")
print("---")
print(result.generated_code)
print("---")
print(f"Error: {exec_res.error}")
return IntentResponse(
success=True,
message="Intent processed successfully",
result=exec_res,
original_intent=request.description,
)
except Exception as e:
import traceback
traceback.print_exc()
raise HTTPException(status_code=500, detail=str(e))
@app.get("/health")
async def health():
return {"status": "ok"}
# =============================================================================
# Streaming Chat Endpoint
# =============================================================================
class ChatRequest(BaseModel):
message: str
model: str | None = None
system: str | None = None
history: list[dict[str, Any]] | None = None
@app.post("/api/chat")
async def chat(request: ChatRequest) -> JSONResponse:
from intentforge.services import ChatService
if not request.message:
return JSONResponse(
status_code=400,
content={"success": False, "error": "Missing 'message' parameter"},
)
chat_service = ChatService()
result = await chat_service.send(
message=request.message,
model=request.model,
system=request.system,
history=request.history,
)
return JSONResponse(content=result)
@app.post("/api/chat/stream")
async def chat_stream(request: Request):
"""
Streaming chat endpoint - returns Server-Sent Events (SSE)
Example:
POST /api/chat/stream {"message": "Hello", "model": "llama3.1:8b"}
"""
from intentforge.llm.providers import LLMConfig, get_llm_provider
body = await request.json()
message = body.get("message", "")
model = body.get("model")
system = body.get("system", "Jesteś pomocnym asystentem AI. Odpowiadaj po polsku.")
async def generate():
import json as json_lib
try:
config = LLMConfig.from_env()
if model:
config.model = model
provider = get_llm_provider(config=config)
async for chunk in provider.generate_stream(message, system=system):
# SSE format
yield f"data: {json_lib.dumps({'chunk': chunk})}\n\n"
yield f"data: {json_lib.dumps({'done': True})}\n\n"
except Exception as e:
yield f"data: {json_lib.dumps({'error': str(e)})}\n\n"
return StreamingResponse(
generate(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"X-Accel-Buffering": "no",
},
)
# =============================================================================
# WebSocket Streaming Endpoint
# =============================================================================
@app.websocket("/ws/chat")
async def websocket_chat(websocket: WebSocket):
"""
WebSocket endpoint for streaming chat responses.
Client sends: {"message": "Hello", "model": "llama3.1:8b", "system": "..."}
Server streams: {"chunk": "..."} or {"done": true} or {"error": "..."}
"""
await websocket.accept()
try:
from intentforge.llm.providers import LLMConfig, get_llm_provider
while True:
# Receive message from client
data = await websocket.receive_json()
message = data.get("message", "")
model = data.get("model")
system = data.get("system", "Jesteś pomocnym asystentem AI. Odpowiadaj po polsku.")
if not message:
await websocket.send_json({"error": "No message provided"})
continue
try:
config = LLMConfig.from_env()
if model:
config.model = model
provider = get_llm_provider(config=config)
# Stream response
async for chunk in provider.generate_stream(message, system=system):
await websocket.send_json({"chunk": chunk})
await websocket.send_json({"done": True})
except Exception as e:
await websocket.send_json({"error": str(e)})
except WebSocketDisconnect:
pass
except Exception as e:
with contextlib.suppress(Exception):
await websocket.send_json({"error": str(e)})
# =============================================================================
# WebSocket: Sandbox Streaming
# =============================================================================
# Active sandbox sessions for streaming
sandbox_sessions: dict[str, list[WebSocket]] = {}
sandbox_tasks: dict[str, asyncio.Task] = {}
@app.websocket("/ws/sandbox/{session_id}")
async def websocket_sandbox(websocket: WebSocket, session_id: str):
"""
WebSocket endpoint for streaming sandbox execution logs.
Client connects to /ws/sandbox/{session_id}
Server streams: {"type": "log|status|result|error", "data": "..."}
"""
await websocket.accept()
# Register this websocket for the session
if session_id not in sandbox_sessions:
sandbox_sessions[session_id] = []
sandbox_sessions[session_id].append(websocket)
try:
# Keep connection alive and handle client messages
while True:
try:
data = await websocket.receive_json()
# Client can send commands like {"action": "stop"}
if data.get("action") == "stop":
await broadcast_sandbox_log(session_id, "🛑 Stop requested by client", "status")
except Exception:
await asyncio.sleep(0.1)
except WebSocketDisconnect:
pass
finally:
# Cleanup
if session_id in sandbox_sessions:
sandbox_sessions[session_id] = [
ws for ws in sandbox_sessions[session_id] if ws != websocket
]
if not sandbox_sessions[session_id]:
del sandbox_sessions[session_id]
async def broadcast_sandbox_log(session_id: str, message: str, msg_type: str = "log"):
"""Broadcast log message to all connected clients for a session"""
if session_id not in sandbox_sessions:
return
dead_sockets = []
for ws in sandbox_sessions[session_id]:
try:
await ws.send_json({"type": msg_type, "data": message, "timestamp": time.time()})
except Exception:
dead_sockets.append(ws)
# Cleanup dead sockets
for ws in dead_sockets:
sandbox_sessions[session_id].remove(ws)
@app.post("/api/agent/run")
async def agent_run_endpoint(request: Request):
"""
Run autonomous agent on a task.
The agent will:
1. Analyze task and context
2. Find/reuse existing modules
3. Generate code if needed
4. Build, test, and register new modules
5. Make autonomous decisions
POST /api/agent/run {
"task": "Create a REST API for users",
"code": "" // optional existing code
}
"""
from intentforge.agent import run_agent
body = await request.json()
task = body.get("task", "")
code = body.get("code", "")
if not task:
return JSONResponse(
status_code=400, content={"success": False, "error": "No task provided"}
)
try:
result = await run_agent(task, code)
return JSONResponse(content=result)
except Exception as e:
return JSONResponse(status_code=500, content={"success": False, "error": str(e)})
@app.get("/api/agent/modules")
async def list_agent_modules():
"""List all modules built by the agent"""
from intentforge.agent import AutonomousAgent
agent = AutonomousAgent()
modules = agent.list_modules()
return JSONResponse(
content={
"success": True,
"modules": [
{
"id": m.id,
"name": m.name,
"description": m.description,
"version": m.version,
"status": m.status.value,
"tests": f"{m.tests_passed}/{m.tests_total}",
"use_count": m.use_count,
"tags": m.tags,
}
for m in modules
],
}
)
@app.post("/api/sandbox/run")
async def sandbox_run_streaming(request: Request):
"""
Run code in sandbox with WebSocket streaming.
POST /api/sandbox/run {
"code": "from flask import Flask...",
"session_id": "abc123", // optional, for WebSocket streaming
"auto_fix": true
}
Returns immediately with session_id, streams logs via WebSocket.
"""
import asyncio
import uuid
body = await request.json()
code = body.get("code", "")
session_id = body.get("session_id") or str(uuid.uuid4())[:8]
auto_fix = body.get("auto_fix", True)
if not code:
return JSONResponse(
status_code=400, content={"success": False, "error": "No code provided"}
)
# Start sandbox execution in background
async def run_sandbox():
from intentforge.service_tester import ServiceDetector, ServiceTester
detector = ServiceDetector()
service_info = detector.detect(code)
if service_info:
await broadcast_sandbox_log(
session_id, f"🔍 Detected {service_info.type} service", "status"
)
await broadcast_sandbox_log(
session_id, f"📍 Found {len(service_info.endpoints)} endpoints", "log"
)
for ep in service_info.endpoints:
await broadcast_sandbox_log(session_id, f" {ep['method']} {ep['path']}", "log")
# Run full service test with streaming
tester = ServiceTester()
result = await tester.test_service(code, auto_fix=auto_fix)
# Stream all logs
for log in result.logs:
await broadcast_sandbox_log(session_id, log, "log")
await asyncio.sleep(0.05) # Small delay for visual effect
# Send final result
await broadcast_sandbox_log(
session_id,
{
"success": result.success,
"service_type": result.service_type,
"endpoints_tested": result.endpoints_tested,
"endpoints_passed": result.endpoints_passed,
"final_code": result.final_code,
},
"result",
)
else:
# Regular code execution
await broadcast_sandbox_log(session_id, "🚀 Running code...", "status")
from intentforge.code_runner import run_with_autofix
result = await run_with_autofix(code, auto_fix=auto_fix)
for log in result.get("logs", []):
await broadcast_sandbox_log(session_id, log, "log")
await asyncio.sleep(0.05)
await broadcast_sandbox_log(
session_id,
{
"success": result.get("success"),
"output": result.get("output"),
"error": result.get("error"),
"final_code": result.get("final_code"),
},
"result",
)
async def run_sandbox_wrapped():
try:
await run_sandbox()
except asyncio.CancelledError:
await broadcast_sandbox_log(session_id, "🛑 Execution cancelled", "status")
await broadcast_sandbox_log(
session_id,
{"success": False, "error": "cancelled"},
"result",
)
raise
except Exception as e:
await broadcast_sandbox_log(session_id, f"❌ Sandbox error: {e}", "error")
await broadcast_sandbox_log(
session_id,
{"success": False, "error": str(e)},
"result",
)
finally:
sandbox_tasks.pop(session_id, None)
# Run in background
task = asyncio.create_task(run_sandbox_wrapped()) # noqa: RUF006
sandbox_tasks[session_id] = task
return JSONResponse(
content={
"success": True,
"session_id": session_id,
"message": "Sandbox started, connect to WebSocket for logs",
"websocket_url": f"/ws/sandbox/{session_id}",
}
)
@app.post("/api/sandbox/stop/{session_id}")
async def sandbox_stop(session_id: str) -> JSONResponse:
task = sandbox_tasks.get(session_id)
if task is None:
return JSONResponse(status_code=404, content={"success": False, "error": "Session not found"})
if task.done():
sandbox_tasks.pop(session_id, None)
return JSONResponse(status_code=400, content={"success": False, "error": "Session already finished"})
task.cancel()
return JSONResponse(content={"success": True})
# =============================================================================
# Proactive Processing Endpoint
# =============================================================================
@app.post("/api/proactive/process")
async def proactive_process(request: Request):
"""
Proactive processing endpoint with intelligent decision-making.
Automatically:
- Detects content type and applies best processing strategy
- Retries with fallback methods if initial processing fails
- Extracts structured data from documents
- Executes and debugs generated code
POST /api/proactive/process {
"content": "...", // base64 image, text, or code
"type": "image|text|code|document",
"options": {"auto_execute": true, "extract_data": true}
}
"""
from intentforge.proactive import ProactiveEngine, ProcessingContext
from intentforge.services import FileService
body = await request.json()
content = body.get("content", "")
content_type = body.get("type", "auto")
options = body.get("options", {})
# Auto-detect content type
if content_type == "auto":
if content.startswith("/9j/") or content.startswith("iVBOR"):
content_type = "image"
elif (
"```" in content
or content.strip().startswith("def ")
or content.strip().startswith("function ")
):
content_type = "code"
else:
content_type = "text"
# Create processing context
context = ProcessingContext(
input_type=content_type,
content=content,
metadata=options,
)
# For images, run initial OCR and Vision analysis
if content_type == "image":
file_service = FileService()
# Run Vision analysis first
vision_result = await file_service._analyze_image_with_vision(
content,
prompt="Przeanalizuj ten obraz. Opisz co widzisz, wykryj obiekty, "
"rozpoznaj tekst (OCR) jeśli jest widoczny. Odpowiedz po polsku.",
)
context.results["vision"] = vision_result
context.metadata["vision_detected_text"] = bool(
vision_result.get("success")
and any(
word in vision_result.get("response", "").lower()
for word in [
"tekst",
"napis",
"słow",
"dokument",
"faktur",
"paragon",
"data",
"numer",
]
)
)
# Run Tesseract OCR
ocr_result = await file_service.ocr(image_base64=content, use_tesseract=True)
context.results["ocr"] = ocr_result
context.metadata["ocr_failed"] = (
not ocr_result.get("success") or not ocr_result.get("text", "").strip()
)
# If OCR failed but Vision detected text, try Vision-based OCR
if context.metadata["ocr_failed"] and context.metadata["vision_detected_text"]:
vision_ocr = await file_service._analyze_image_with_vision(
content,
prompt="Przepisz DOKŁADNIE i KOMPLETNIE cały tekst widoczny na tym obrazie. "
"Zachowaj oryginalny układ tekstu (linie, kolumny). "
"NIE dodawaj żadnych komentarzy ani opisów - TYLKO tekst z obrazu. "
"Jeśli tekst jest w tabeli, zachowaj strukturę tabeli.",
)
if vision_ocr.get("success"):
ocr_text = vision_ocr.get("response", "")
# Filter out "no text" responses
if "brak tekstu" not in ocr_text.lower() and len(ocr_text) > 20:
context.results["ocr"] = {
"success": True,
"text": ocr_text,
"method": "vision_fallback",
"model": file_service.vision_model,
}
context.metadata["ocr_failed"] = False
# Run proactive engine
engine = ProactiveEngine()
result = await engine.process(context)
# Combine all results
return JSONResponse(
content={
"success": True,
"content_type": content_type,
"processing": result,
"ocr": context.results.get("ocr", {}),
"vision": context.results.get("vision", {}),
"extracted_data": context.results.get("extract_data", {}),
}
)
@app.post("/api/proactive/code")
async def proactive_code(request: Request):
"""
Proactive code execution with automatic debugging.
POST /api/proactive/code {
"code": "print('hello')",
"language": "python",
"auto_debug": true
}
"""
from intentforge.proactive import Decision, DecisionType, ProactiveEngine, ProcessingContext
body = await request.json()
code = body.get("code", "")
language = body.get("language", "python")
auto_debug = body.get("auto_debug", True)
engine = ProactiveEngine()
# Execute code
exec_decision = Decision(
type=DecisionType.EXECUTE_CODE,
action="run",
params={"code": code, "language": language},
)
context = ProcessingContext(input_type="code", content=code)
exec_result = await engine._handle_execute_code(exec_decision, context)
result = {
"success": exec_result.get("success", False),
"execution": exec_result,
}
# If execution failed and auto_debug is enabled, debug the code
if not exec_result.get("success") and auto_debug:
debug_decision = Decision(
type=DecisionType.DEBUG_CODE,
action="analyze",
params={
"code": code,
"language": language,
"error": exec_result.get("stderr", "") or exec_result.get("error", ""),
},
)
debug_result = await engine._handle_debug_code(debug_decision, context)
result["debug"] = debug_result
return JSONResponse(content=result)
# =============================================================================
# Service API Endpoints (LLM-powered)
# =============================================================================
def _filter_kwargs(fn, data: dict[str, Any]) -> dict[str, Any]:
"""Filter kwargs to only include parameters accepted by the function"""
sig = inspect.signature(fn)
if any(p.kind == inspect.Parameter.VAR_KEYWORD for p in sig.parameters.values()):
return data
allowed = set(sig.parameters)
return {k: v for k, v in data.items() if k in allowed}
async def _call_service(service: str, action: str, payload: dict[str, Any]) -> dict[str, Any]:
"""Call a service method with the given payload"""
svc = services.get(service)
if svc is None:
raise HTTPException(status_code=404, detail=f"Unknown service: {service}")
method = getattr(svc, action, None)
if method is None:
raise HTTPException(
status_code=404, detail=f"Unknown action '{action}' for service '{service}'"
)
kwargs = payload.copy()
kwargs.pop("action", None)
kwargs.pop("request_id", None)
try:
result = method(**_filter_kwargs(method, kwargs))
if inspect.isawaitable(result):
result = await result
except TypeError as e:
raise HTTPException(status_code=400, detail=str(e))
if isinstance(result, dict):
return result
return {"success": True, "result": result}
@app.post("/api/{service}")
async def api_service(service: str, request: Request) -> JSONResponse:
"""
Generic service endpoint - routes to appropriate service handler.
Services: chat, analytics, voice, file, form, payment, camera, data, email
Example:
POST /api/chat {"action": "send", "message": "Hello"}
POST /api/analytics {"action": "stats", "period": "current_month"}
POST /api/voice {"action": "process", "command": "Turn on lights"}
"""
body = await request.json()
action = body.get("action")
if not action or not isinstance(action, str):
return JSONResponse(
status_code=400, content={"success": False, "error": "Missing 'action' parameter"}
)
request_id = body.get("request_id")
try:
result = await _call_service(service, action, body)
if request_id is not None and isinstance(result, dict):
result = {**result, "request_id": request_id}
return JSONResponse(content=result)
except HTTPException as e:
return JSONResponse(
status_code=e.status_code, content={"success": False, "error": e.detail}
)
except Exception as e:
return JSONResponse(status_code=500, content={"success": False, "error": str(e)})
# =============================================================================
# Code Execution Endpoint
# =============================================================================
# Language execution templates
LANGUAGE_TEMPLATES = {
"python": {
"extension": ".py",
"command": ["python3", "{file}"],
"docker": "python:3.11-slim",
"setup": None,
},
"javascript": {
"extension": ".js",
"command": ["node", "{file}"],
"docker": "node:20-slim",
"setup": None,
},
"typescript": {
"extension": ".ts",
"command": ["npx", "ts-node", "{file}"],
"docker": "node:20-slim",
"setup": "npm install -g ts-node typescript",
},
"bash": {
"extension": ".sh",
"command": ["bash", "{file}"],
"docker": "alpine:latest",
"setup": None,
},
"shell": {
"extension": ".sh",
"command": ["sh", "{file}"],
"docker": "alpine:latest",
"setup": None,
},
"ruby": {
"extension": ".rb",
"command": ["ruby", "{file}"],
"docker": "ruby:3.2-slim",
"setup": None,
},
"php": {
"extension": ".php",
"command": ["php", "{file}"],
"docker": "php:8.2-cli",
"setup": None,
},
"go": {
"extension": ".go",
"command": ["go", "run", "{file}"],
"docker": "golang:1.21-alpine",
"setup": None,
},
"rust": {
"extension": ".rs",
"command": ["rustc", "{file}", "-o", "{output}", "&&", "{output}"],
"docker": "rust:1.74-slim",
"setup": None,
},
"java": {
"extension": ".java",
"command": ["java", "{file}"],
"docker": "openjdk:21-slim",
"setup": None,
},
"c": {
"extension": ".c",
"command": ["gcc", "{file}", "-o", "{output}", "&&", "{output}"],
"docker": "gcc:13",
"setup": None,
},
"cpp": {
"extension": ".cpp",
"command": ["g++", "{file}", "-o", "{output}", "&&", "{output}"],
"docker": "gcc:13",
"setup": None,
},
"sql": {
"extension": ".sql",
"command": ["sqlite3", ":memory:", "-init", "{file}"],
"docker": None,
"setup": None,
},
"html": {
"extension": ".html",
"command": None, # Open in browser
"docker": None,
"setup": None,
"serve": True,
},
}
# Directory for generated code files
CODE_OUTPUT_DIR = Path("/tmp/intentforge_code")
CODE_OUTPUT_DIR.mkdir(exist_ok=True)
@app.post("/api/code/save")