Skip to content

Commit 2fcad5f

Browse files
committed
try fix pre commit hook bug in app.py
1 parent 41308f3 commit 2fcad5f

File tree

1 file changed

+48
-61
lines changed

1 file changed

+48
-61
lines changed

app.py

+48-61
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
import asyncio
2-
import threading
32
import uuid
4-
import webbrowser
53
from datetime import datetime
64
from json import dumps
75

@@ -12,7 +10,6 @@
1210
from fastapi.templating import Jinja2Templates
1311
from pydantic import BaseModel
1412

15-
1613
app = FastAPI()
1714

1815
app.mount("/static", StaticFiles(directory="static"), name="static")
@@ -26,7 +23,6 @@
2623
allow_headers=["*"],
2724
)
2825

29-
3026
class Task(BaseModel):
3127
id: str
3228
prompt: str
@@ -36,10 +32,9 @@ class Task(BaseModel):
3632

3733
def model_dump(self, *args, **kwargs):
3834
data = super().model_dump(*args, **kwargs)
39-
data["created_at"] = self.created_at.isoformat()
35+
data['created_at'] = self.created_at.isoformat()
4036
return data
4137

42-
4338
class TaskManager:
4439
def __init__(self):
4540
self.tasks = {}
@@ -48,55 +43,61 @@ def __init__(self):
4843
def create_task(self, prompt: str) -> Task:
4944
task_id = str(uuid.uuid4())
5045
task = Task(
51-
id=task_id, prompt=prompt, created_at=datetime.now(), status="pending"
46+
id=task_id,
47+
prompt=prompt,
48+
created_at=datetime.now(),
49+
status="pending"
5250
)
5351
self.tasks[task_id] = task
5452
self.queues[task_id] = asyncio.Queue()
5553
return task
5654

57-
async def update_task_step(
58-
self, task_id: str, step: int, result: str, step_type: str = "step"
59-
):
55+
async def update_task_step(self, task_id: str, step: int, result: str, step_type: str = "step"):
6056
if task_id in self.tasks:
6157
task = self.tasks[task_id]
6258
task.steps.append({"step": step, "result": result, "type": step_type})
63-
await self.queues[task_id].put(
64-
{"type": step_type, "step": step, "result": result}
65-
)
66-
await self.queues[task_id].put(
67-
{"type": "status", "status": task.status, "steps": task.steps}
68-
)
59+
await self.queues[task_id].put({
60+
"type": step_type,
61+
"step": step,
62+
"result": result
63+
})
64+
await self.queues[task_id].put({
65+
"type": "status",
66+
"status": task.status,
67+
"steps": task.steps
68+
})
6969

7070
async def complete_task(self, task_id: str):
7171
if task_id in self.tasks:
7272
task = self.tasks[task_id]
7373
task.status = "completed"
74-
await self.queues[task_id].put(
75-
{"type": "status", "status": task.status, "steps": task.steps}
76-
)
74+
await self.queues[task_id].put({
75+
"type": "status",
76+
"status": task.status,
77+
"steps": task.steps
78+
})
7779
await self.queues[task_id].put({"type": "complete"})
7880

7981
async def fail_task(self, task_id: str, error: str):
8082
if task_id in self.tasks:
8183
self.tasks[task_id].status = f"failed: {error}"
82-
await self.queues[task_id].put({"type": "error", "message": error})
83-
84+
await self.queues[task_id].put({
85+
"type": "error",
86+
"message": error
87+
})
8488

8589
task_manager = TaskManager()
8690

87-
8891
@app.get("/", response_class=HTMLResponse)
8992
async def index(request: Request):
9093
return templates.TemplateResponse("index.html", {"request": request})
9194

92-
9395
@app.post("/tasks")
9496
async def create_task(prompt: str = Body(..., embed=True)):
9597
task = task_manager.create_task(prompt)
9698
asyncio.create_task(run_task(task.id, prompt))
9799
return {"task_id": task.id}
98100

99-
100101
from app.agent.manus import Manus
101102

102103

@@ -107,21 +108,17 @@ async def run_task(task_id: str, prompt: str):
107108
agent = Manus(
108109
name="Manus",
109110
description="A versatile agent that can solve various tasks using multiple tools",
110-
max_steps=30,
111+
max_steps=30
111112
)
112113

113114
async def on_think(thought):
114115
await task_manager.update_task_step(task_id, 0, thought, "think")
115116

116117
async def on_tool_execute(tool, input):
117-
await task_manager.update_task_step(
118-
task_id, 0, f"Executing tool: {tool}\nInput: {input}", "tool"
119-
)
118+
await task_manager.update_task_step(task_id, 0, f"Executing tool: {tool}\nInput: {input}", "tool")
120119

121120
async def on_action(action):
122-
await task_manager.update_task_step(
123-
task_id, 0, f"Executing action: {action}", "act"
124-
)
121+
await task_manager.update_task_step(task_id, 0, f"Executing action: {action}", "act")
125122

126123
async def on_run(step, result):
127124
await task_manager.update_task_step(task_id, step, result, "run")
@@ -136,7 +133,7 @@ async def __call__(self, message):
136133
import re
137134

138135
# 提取 - 后面的内容
139-
cleaned_message = re.sub(r"^.*? - ", "", message)
136+
cleaned_message = re.sub(r'^.*? - ', '', message)
140137

141138
event_type = "log"
142139
if "✨ Manus's thoughts:" in cleaned_message:
@@ -150,9 +147,7 @@ async def __call__(self, message):
150147
elif "🏁 Special tool" in cleaned_message:
151148
event_type = "complete"
152149

153-
await task_manager.update_task_step(
154-
self.task_id, 0, cleaned_message, event_type
155-
)
150+
await task_manager.update_task_step(self.task_id, 0, cleaned_message, event_type)
156151

157152
sse_handler = SSELogHandler(task_id)
158153
logger.add(sse_handler)
@@ -163,7 +158,6 @@ async def __call__(self, message):
163158
except Exception as e:
164159
await task_manager.fail_task(task_id, str(e))
165160

166-
167161
@app.get("/tasks/{task_id}/events")
168162
async def task_events(task_id: str):
169163
async def event_generator():
@@ -175,9 +169,11 @@ async def event_generator():
175169

176170
task = task_manager.tasks.get(task_id)
177171
if task:
178-
message = {"type": "status", "status": task.status, "steps": task.steps}
179-
json_message = dumps(message)
180-
yield f"event: status\ndata: {json_message}\n\n"
172+
yield f"event: status\ndata: {dumps({
173+
'type': 'status',
174+
'status': task.status,
175+
'steps': task.steps
176+
})}\n\n"
181177

182178
while True:
183179
try:
@@ -195,13 +191,11 @@ async def event_generator():
195191
elif event["type"] == "step":
196192
task = task_manager.tasks.get(task_id)
197193
if task:
198-
message = {
199-
"type": "status",
200-
"status": task.status,
201-
"steps": task.steps,
202-
}
203-
json_message = dumps(message)
204-
yield f"event: status\ndata: {json_message}\n\n"
194+
yield f"event: status\ndata: {dumps({
195+
'type': 'status',
196+
'status': task.status,
197+
'steps': task.steps
198+
})}\n\n"
205199
yield f"event: {event['type']}\ndata: {formatted_event}\n\n"
206200
elif event["type"] in ["think", "tool", "act", "run"]:
207201
yield f"event: {event['type']}\ndata: {formatted_event}\n\n"
@@ -222,42 +216,35 @@ async def event_generator():
222216
headers={
223217
"Cache-Control": "no-cache",
224218
"Connection": "keep-alive",
225-
"X-Accel-Buffering": "no",
226-
},
219+
"X-Accel-Buffering": "no"
220+
}
227221
)
228222

229-
230223
@app.get("/tasks")
231224
async def get_tasks():
232225
sorted_tasks = sorted(
233-
task_manager.tasks.values(), key=lambda task: task.created_at, reverse=True
226+
task_manager.tasks.values(),
227+
key=lambda task: task.created_at,
228+
reverse=True
234229
)
235230
return JSONResponse(
236231
content=[task.model_dump() for task in sorted_tasks],
237-
headers={"Content-Type": "application/json"},
232+
headers={"Content-Type": "application/json"}
238233
)
239234

240-
241235
@app.get("/tasks/{task_id}")
242236
async def get_task(task_id: str):
243237
if task_id not in task_manager.tasks:
244238
raise HTTPException(status_code=404, detail="Task not found")
245239
return task_manager.tasks[task_id]
246240

247-
248241
@app.exception_handler(Exception)
249242
async def generic_exception_handler(request: Request, exc: Exception):
250243
return JSONResponse(
251-
status_code=500, content={"message": f"Server error: {str(exc)}"}
244+
status_code=500,
245+
content={"message": f"Server error: {str(exc)}"}
252246
)
253247

254-
255-
def open_local_browser():
256-
webbrowser.open_new_tab("http://localhost:5172")
257-
258-
259248
if __name__ == "__main__":
260-
threading.Timer(3, open_local_browser).start()
261249
import uvicorn
262-
263250
uvicorn.run(app, host="localhost", port=5172)

0 commit comments

Comments
 (0)