Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
113 lines (91 loc) · 2.8 KB
/
Copy pathapp.py
File metadata and controls
113 lines (91 loc) · 2.8 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
import subprocess
from fastapi import FastAPI
from typing import Optional, Dict, Any
from contextlib import asynccontextmanager
from rl.env import CodeAnalysisEnv
import sys
import os
# Ensure backend modules can be imported
sys.path.append(os.path.abspath("backend"))
from backend.utils.llm import call_structured_llm
from backend.models.llm_schemas import RLActionSchema
# -----------------------------
# LIFESPAN (MODERN REPLACEMENT)
# -----------------------------
@asynccontextmanager
async def lifespan(app: FastAPI):
try:
subprocess.Popen(["python", "inference.py"])
print("Inference process started", flush=True)
except Exception as e:
print(f"Failed to start inference: {e}", flush=True)
yield # app runs here
# (optional cleanup can go here)
# -----------------------------
# APP INIT
# -----------------------------
app = FastAPI(lifespan=lifespan)
env = CodeAnalysisEnv()
# -----------------------------
# SMART DEFAULT AGENT
# -----------------------------
async def generate_default_action(state):
try:
files = str(state.get("files", ""))
prompt = f"""
You are an AI generating dynamic RL environment actions based on the current state.
Analyze the provided files state and intelligently identify issues and suggested fixes.
State files:
{files}
"""
response = await call_structured_llm(prompt, response_model=RLActionSchema)
return response.model_dump()
except Exception as e:
print(f"Error generating action: {e}", flush=True)
return {
"identified_issues": [],
"suggested_fixes": []
}
# -----------------------------
# RESET
# -----------------------------
@app.post("/reset")
def reset():
try:
obs = env.reset()
return {"observation": obs}
except Exception as e:
return {
"observation": {},
"error": str(e)
}
# -----------------------------
# STEP
# -----------------------------
@app.post("/step")
async def step(action: Optional[Dict[str, Any]] = None):
try:
# IMPORTANT: fallback agent
if not action:
state = env.state()
action = await generate_default_action(state)
obs, reward, done, info = env.step(action)
return {
"observation": obs,
"reward": float(reward),
"done": bool(done),
"info": info if info else {}
}
except Exception as e:
return {
"observation": {},
"reward": 0.0,
"done": True,
"info": {"error": str(e)}
}
# -----------------------------
# HEALTH CHECK
# -----------------------------
@app.get("/")
def home():
return {"message": "Code Analysis RL Environment is running"}