-
Notifications
You must be signed in to change notification settings - Fork 233
Expand file tree
/
Copy pathmain.py
More file actions
228 lines (181 loc) · 6.96 KB
/
main.py
File metadata and controls
228 lines (181 loc) · 6.96 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
import os
import uuid
import json
import threading
from datetime import datetime
from typing import Optional, Literal
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from sqlalchemy import create_engine, Column, Text, DateTime, String
from sqlalchemy.orm import sessionmaker, declarative_base
from dotenv import load_dotenv
from src.planning_agent import planner_agent, executor_agent_step
import html, textwrap
# === Load env vars ===
load_dotenv()
DATABASE_URL = os.getenv("DATABASE_URL")
# Fix for Heroku's postgres:// URL format
if DATABASE_URL.startswith("postgres://"):
DATABASE_URL = DATABASE_URL.replace("postgres://", "postgresql://", 1)
if not DATABASE_URL:
raise RuntimeError("DATABASE_URL not set")
# === DB setup ===
Base = declarative_base()
engine = create_engine(DATABASE_URL, echo=False, future=True)
SessionLocal = sessionmaker(bind=engine)
class Task(Base):
__tablename__ = "tasks"
id = Column(String, primary_key=True, index=True)
prompt = Column(Text)
status = Column(String)
created_at = Column(DateTime, default=datetime.utcnow)
updated_at = Column(DateTime, default=datetime.utcnow)
result = Column(Text)
try:
Base.metadata.drop_all(bind=engine)
except Exception as e:
print(f"\u274c DB creation failed: {e}")
try:
Base.metadata.create_all(bind=engine)
except Exception as e:
print(f"\u274c DB creation failed: {e}")
# === FastAPI ===
app = FastAPI()
app.add_middleware(
CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"]
)
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
task_progress = {}
class PromptRequest(BaseModel):
prompt: str
@app.get("/", response_class=HTMLResponse)
def read_index(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
@app.get("/api", response_class=JSONResponse)
def health_check(request: Request):
return {"status": "ok"}
@app.post("/generate_report")
def generate_report(req: PromptRequest):
task_id = str(uuid.uuid4())
db = SessionLocal()
db.add(Task(id=task_id, prompt=req.prompt, status="running"))
db.commit()
db.close()
task_progress[task_id] = {"steps": []}
initial_plan_steps = planner_agent(req.prompt)
for step_title in initial_plan_steps:
task_progress[task_id]["steps"].append(
{
"title": step_title,
"status": "pending",
"description": "Awaiting execution",
"substeps": [],
}
)
thread = threading.Thread(
target=run_agent_workflow, args=(task_id, req.prompt, initial_plan_steps)
)
thread.start()
return {"task_id": task_id}
@app.get("/task_progress/{task_id}")
def get_task_progress(task_id: str):
return task_progress.get(task_id, {"steps": []})
@app.get("/task_status/{task_id}")
def get_task_status(task_id: str):
db = SessionLocal()
task = db.query(Task).filter(Task.id == task_id).first()
db.close()
if not task:
raise HTTPException(status_code=404, detail="Task not found")
return {
"status": task.status,
"result": json.loads(task.result) if task.result else None,
}
def format_history(history):
return "\n\n".join(
f"🔹 {title}\n{desc}\n\n📝 Output:\n{output}" for title, desc, output in history
)
def run_agent_workflow(task_id: str, prompt: str, initial_plan_steps: list):
steps_data = task_progress[task_id]["steps"]
execution_history = []
def update_step_status(index, status, description="", substep=None):
if index < len(steps_data):
steps_data[index]["status"] = status
if description:
steps_data[index]["description"] = description
if substep:
steps_data[index]["substeps"].append(substep)
steps_data[index]["updated_at"] = datetime.utcnow().isoformat()
try:
for i, plan_step_title in enumerate(initial_plan_steps):
update_step_status(i, "running", f"Executing: {plan_step_title}")
actual_step_description, agent_name, output = executor_agent_step(
plan_step_title, execution_history, prompt
)
execution_history.append([plan_step_title, actual_step_description, output])
def esc(s: str) -> str:
return html.escape(s or "")
def nl2br(s: str) -> str:
return esc(s).replace("\n", "<br>")
# ...
update_step_status(
i,
"done",
f"Completed: {plan_step_title}",
{
"title": f"Called {agent_name}",
"content": f"""
<div style='border:1px solid #ccc; border-radius:8px; padding:10px; margin:8px 0; background:#fff;'>
<div style='font-weight:bold; color:#2563eb;'>📘 User Prompt</div>
<div style='white-space:pre-wrap;'>{prompt}</div>
<div style='font-weight:bold; color:#16a34a; margin-top:8px;'>📜 Previous Step</div>
<pre style='white-space:pre-wrap; background:#f9fafb; padding:6px; border-radius:6px; margin:0;'>
{format_history(execution_history[-2:-1])}
</pre>
<div style='font-weight:bold; color:#f59e0b; margin-top:8px;'>🧹 Your next task</div>
<div style='white-space:pre-wrap;'>{actual_step_description}</div>
<div style='font-weight:bold; color:#10b981; margin-top:8px;'>✅ Output</div>
<!-- ⚠️ NO <pre> AQUÍ -->
<div style='white-space:pre-wrap;'>
{output}
</div>
</div>
""".strip(),
},
)
final_report_markdown = (
execution_history[-1][-1] if execution_history else "No report generated."
)
result = {"html_report": final_report_markdown, "history": steps_data}
db = SessionLocal()
task = db.query(Task).filter(Task.id == task_id).first()
task.status = "done"
task.result = json.dumps(result)
task.updated_at = datetime.utcnow()
db.commit()
db.close()
except Exception as e:
print(f"Workflow error for task {task_id}: {e}")
if steps_data:
error_step_index = next(
(i for i, s in enumerate(steps_data) if s["status"] == "running"),
len(steps_data) - 1,
)
if error_step_index >= 0:
update_step_status(
error_step_index,
"error",
f"Error during execution: {e}",
{"title": "Error", "content": str(e)},
)
db = SessionLocal()
task = db.query(Task).filter(Task.id == task_id).first()
task.status = "error"
task.updated_at = datetime.utcnow()
db.commit()
db.close()