fix multiline string SyntaxError

This commit is contained in:
rxdaozhang 2025-03-11 02:07:04 +08:00
parent 34ede1c082
commit f67af3580a

87
app.py
View File

@ -23,6 +23,7 @@ app.add_middleware(
allow_headers=["*"], allow_headers=["*"],
) )
class Task(BaseModel): class Task(BaseModel):
id: str id: str
prompt: str prompt: str
@ -32,9 +33,10 @@ class Task(BaseModel):
def model_dump(self, *args, **kwargs): def model_dump(self, *args, **kwargs):
data = super().model_dump(*args, **kwargs) data = super().model_dump(*args, **kwargs)
data['created_at'] = self.created_at.isoformat() data["created_at"] = self.created_at.isoformat()
return data return data
class TaskManager: class TaskManager:
def __init__(self): def __init__(self):
self.tasks = {} self.tasks = {}
@ -43,61 +45,55 @@ class TaskManager:
def create_task(self, prompt: str) -> Task: def create_task(self, prompt: str) -> Task:
task_id = str(uuid.uuid4()) task_id = str(uuid.uuid4())
task = Task( task = Task(
id=task_id, id=task_id, prompt=prompt, created_at=datetime.now(), status="pending"
prompt=prompt,
created_at=datetime.now(),
status="pending"
) )
self.tasks[task_id] = task self.tasks[task_id] = task
self.queues[task_id] = asyncio.Queue() self.queues[task_id] = asyncio.Queue()
return task return task
async def update_task_step(self, task_id: str, step: int, result: str, step_type: str = "step"): async def update_task_step(
self, task_id: str, step: int, result: str, step_type: str = "step"
):
if task_id in self.tasks: if task_id in self.tasks:
task = self.tasks[task_id] task = self.tasks[task_id]
task.steps.append({"step": step, "result": result, "type": step_type}) task.steps.append({"step": step, "result": result, "type": step_type})
await self.queues[task_id].put({ await self.queues[task_id].put(
"type": step_type, {"type": step_type, "step": step, "result": result}
"step": step, )
"result": result await self.queues[task_id].put(
}) {"type": "status", "status": task.status, "steps": task.steps}
await self.queues[task_id].put({ )
"type": "status",
"status": task.status,
"steps": task.steps
})
async def complete_task(self, task_id: str): async def complete_task(self, task_id: str):
if task_id in self.tasks: if task_id in self.tasks:
task = self.tasks[task_id] task = self.tasks[task_id]
task.status = "completed" task.status = "completed"
await self.queues[task_id].put({ await self.queues[task_id].put(
"type": "status", {"type": "status", "status": task.status, "steps": task.steps}
"status": task.status, )
"steps": task.steps
})
await self.queues[task_id].put({"type": "complete"}) await self.queues[task_id].put({"type": "complete"})
async def fail_task(self, task_id: str, error: str): async def fail_task(self, task_id: str, error: str):
if task_id in self.tasks: if task_id in self.tasks:
self.tasks[task_id].status = f"failed: {error}" self.tasks[task_id].status = f"failed: {error}"
await self.queues[task_id].put({ await self.queues[task_id].put({"type": "error", "message": error})
"type": "error",
"message": error
})
task_manager = TaskManager() task_manager = TaskManager()
@app.get("/", response_class=HTMLResponse) @app.get("/", response_class=HTMLResponse)
async def index(request: Request): async def index(request: Request):
return templates.TemplateResponse("index.html", {"request": request}) return templates.TemplateResponse("index.html", {"request": request})
@app.post("/tasks") @app.post("/tasks")
async def create_task(prompt: str = Body(..., embed=True)): async def create_task(prompt: str = Body(..., embed=True)):
task = task_manager.create_task(prompt) task = task_manager.create_task(prompt)
asyncio.create_task(run_task(task.id, prompt)) asyncio.create_task(run_task(task.id, prompt))
return {"task_id": task.id} return {"task_id": task.id}
from app.agent.manus import Manus from app.agent.manus import Manus
@ -108,17 +104,21 @@ async def run_task(task_id: str, prompt: str):
agent = Manus( agent = Manus(
name="Manus", name="Manus",
description="A versatile agent that can solve various tasks using multiple tools", description="A versatile agent that can solve various tasks using multiple tools",
max_steps=30 max_steps=30,
) )
async def on_think(thought): async def on_think(thought):
await task_manager.update_task_step(task_id, 0, thought, "think") await task_manager.update_task_step(task_id, 0, thought, "think")
async def on_tool_execute(tool, input): async def on_tool_execute(tool, input):
await task_manager.update_task_step(task_id, 0, f"Executing tool: {tool}\nInput: {input}", "tool") await task_manager.update_task_step(
task_id, 0, f"Executing tool: {tool}\nInput: {input}", "tool"
)
async def on_action(action): async def on_action(action):
await task_manager.update_task_step(task_id, 0, f"Executing action: {action}", "act") await task_manager.update_task_step(
task_id, 0, f"Executing action: {action}", "act"
)
async def on_run(step, result): async def on_run(step, result):
await task_manager.update_task_step(task_id, step, result, "run") await task_manager.update_task_step(task_id, step, result, "run")
@ -133,7 +133,7 @@ async def run_task(task_id: str, prompt: str):
import re import re
# 提取 - 后面的内容 # 提取 - 后面的内容
cleaned_message = re.sub(r'^.*? - ', '', message) cleaned_message = re.sub(r"^.*? - ", "", message)
event_type = "log" event_type = "log"
if "✨ Manus's thoughts:" in cleaned_message: if "✨ Manus's thoughts:" in cleaned_message:
@ -147,7 +147,9 @@ async def run_task(task_id: str, prompt: str):
elif "🏁 Special tool" in cleaned_message: elif "🏁 Special tool" in cleaned_message:
event_type = "complete" event_type = "complete"
await task_manager.update_task_step(self.task_id, 0, cleaned_message, event_type) await task_manager.update_task_step(
self.task_id, 0, cleaned_message, event_type
)
sse_handler = SSELogHandler(task_id) sse_handler = SSELogHandler(task_id)
logger.add(sse_handler) logger.add(sse_handler)
@ -158,6 +160,7 @@ async def run_task(task_id: str, prompt: str):
except Exception as e: except Exception as e:
await task_manager.fail_task(task_id, str(e)) await task_manager.fail_task(task_id, str(e))
@app.get("/tasks/{task_id}/events") @app.get("/tasks/{task_id}/events")
async def task_events(task_id: str): async def task_events(task_id: str):
async def event_generator(): async def event_generator():
@ -169,11 +172,7 @@ async def task_events(task_id: str):
task = task_manager.tasks.get(task_id) task = task_manager.tasks.get(task_id)
if task: if task:
yield f"event: status\ndata: {dumps({ yield f"event: status\ndata: {dumps({'type': 'status','status': task.status, 'steps': task.steps})}\n\n"
'type': 'status',
'status': task.status,
'steps': task.steps
})}\n\n"
while True: while True:
try: try:
@ -216,35 +215,37 @@ async def task_events(task_id: str):
headers={ headers={
"Cache-Control": "no-cache", "Cache-Control": "no-cache",
"Connection": "keep-alive", "Connection": "keep-alive",
"X-Accel-Buffering": "no" "X-Accel-Buffering": "no",
} },
) )
@app.get("/tasks") @app.get("/tasks")
async def get_tasks(): async def get_tasks():
sorted_tasks = sorted( sorted_tasks = sorted(
task_manager.tasks.values(), task_manager.tasks.values(), key=lambda task: task.created_at, reverse=True
key=lambda task: task.created_at,
reverse=True
) )
return JSONResponse( return JSONResponse(
content=[task.model_dump() for task in sorted_tasks], content=[task.model_dump() for task in sorted_tasks],
headers={"Content-Type": "application/json"} headers={"Content-Type": "application/json"},
) )
@app.get("/tasks/{task_id}") @app.get("/tasks/{task_id}")
async def get_task(task_id: str): async def get_task(task_id: str):
if task_id not in task_manager.tasks: if task_id not in task_manager.tasks:
raise HTTPException(status_code=404, detail="Task not found") raise HTTPException(status_code=404, detail="Task not found")
return task_manager.tasks[task_id] return task_manager.tasks[task_id]
@app.exception_handler(Exception) @app.exception_handler(Exception)
async def generic_exception_handler(request: Request, exc: Exception): async def generic_exception_handler(request: Request, exc: Exception):
return JSONResponse( return JSONResponse(
status_code=500, status_code=500, content={"message": f"Server error: {str(exc)}"}
content={"message": f"Server error: {str(exc)}"}
) )
if __name__ == "__main__": if __name__ == "__main__":
import uvicorn import uvicorn
uvicorn.run(app, host="localhost", port=5172) uvicorn.run(app, host="localhost", port=5172)