Files
goal-planner/backend/routes/generate.py
T
2026-11-02 15:45:49 +08:00

289 lines
12 KiB
Python

import httpx
import json
import uuid
from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import StreamingResponse
from sqlalchemy.orm import Session
from database import get_db
from models.models import Plan, Task
from config import OPENAI_API_KEY, OPENAI_API_URL, OPENAI_MODEL, ENABLE_SEARCH, LLM_PROVIDER
from routes.deps import get_current_user_id
from utils import build_task_tree
router = APIRouter(prefix="/api/generate", tags=["generate"])
def flatten_tasks(tasks_data: list, plan_id: int, parent_id=None, level=0) -> list[dict]:
"""Flatten nested task data from AI into a flat list with parent_id references."""
result = []
for task_data in tasks_data:
if not isinstance(task_data, dict):
continue
result.append({
"plan_id": plan_id,
"parent_id": parent_id,
"task_id": task_data.get("id", ""),
"title": task_data.get("title", ""),
"description": task_data.get("description", ""),
"dependencies": task_data.get("dependencies", []),
"duration_in_hours": task_data.get("durationInHours", 0),
"status": "todo",
"_children": task_data.get("children", []),
"_level": level,
})
return result
def build_llm_payload(system_prompt: str, prompt: str) -> dict:
"""Build the API request payload based on the LLM provider."""
payload = {
"model": OPENAI_MODEL,
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": prompt}
],
"temperature": 0.7,
}
provider = LLM_PROVIDER
# response_format: only providers that support json_object mode
if provider in ("dashscope", "openai", "deepseek", "moonshot"):
payload["response_format"] = {"type": "json_object"}
# For gemini and others: rely on prompt instruction for JSON output
# Web search integration by provider
if ENABLE_SEARCH:
if provider == "dashscope":
# 阿里千问: top-level enable_search param
payload["enable_search"] = True
elif provider == "openai":
# OpenAI: use web_search tool (requires supported model like gpt-4o)
payload["tools"] = [{"type": "web_search_preview"}]
elif provider == "gemini":
# Gemini: use google_search_retrieval tool
payload["tools"] = [{"google_search_retrieval": {}}]
# deepseek / moonshot: no web search support, skip
return payload
def build_llm_headers() -> dict:
"""Build HTTP headers based on the LLM provider."""
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {OPENAI_API_KEY}",
}
print(headers)
# Gemini uses a different auth header via OpenAI-compatible endpoint
# The OpenAI-compatible endpoint still uses Bearer token, so no change needed
return headers
from pydantic import BaseModel
class GeneratePlanRequest(BaseModel):
goal: str
additional_info: str = ""
@router.post("/")
async def generate_plan(req: GeneratePlanRequest, user_id: int = Depends(get_current_user_id)):
if not OPENAI_API_KEY:
raise HTTPException(status_code=500, detail="OPENAI_API_KEY not configured")
goal = req.goal
additional_info = req.additional_info
has_additional = additional_info.strip() != ""
if has_additional:
prompt = f'''You are an expert project manager. The user has provided a goal AND a detailed reference plan (in Markdown format). Your task is to convert this reference plan into a structured, multi-level task plan.
RULES:
1. Carefully parse the user's reference plan. Preserve the original structure, task names, and descriptions as much as possible.
2. Organize the content into top-level tasks (level 1) as the main phases, subtasks (level 2), and sub-subtasks (level 3) based on the Markdown headings and list hierarchy.
3. Do NOT go deeper than 3 levels total.
4. Each task needs: "id" (short URL-friendly slug, unique across the entire plan), "title", "description" (summarize the task based on the reference content), "durationInHours" (estimate based on the task complexity), "dependencies" (list of other task IDs that must complete first - only reference IDs at the SAME level), and optionally "children" (array of subtasks with the same structure).
5. Ensure tasks are in a logical order consistent with the reference plan.
6. The output MUST be valid JSON with a top-level "tasks" key containing the array.
EXAMPLE STRUCTURE:
{{
"tasks": [
{{
"id": "phase-1",
"title": "Phase 1: Research & Planning",
"description": "...",
"durationInHours": 10,
"dependencies": [],
"children": [
{{
"id": "phase-1-research",
"title": "Market Research",
"description": "...",
"durationInHours": 5,
"dependencies": [],
"children": [
{{"id": "phase-1-research-survey", "title": "Create Survey", "description": "...", "durationInHours": 2, "dependencies": []}},
{{"id": "phase-1-research-analyze", "title": "Analyze Results", "description": "...", "durationInHours": 3, "dependencies": ["phase-1-research-survey"]}}
]
}},
{{"id": "phase-1-competitor", "title": "Competitor Analysis", "description": "...", "durationInHours": 5, "dependencies": []}}
]
}},
{{"id": "phase-2", "title": "Phase 2: Development", "description": "...", "durationInHours": 20, "dependencies": ["phase-1"]}}
]
}}
Goal: "{goal}"
Reference Plan (Markdown):
{additional_info.strip()}'''
else:
prompt = f'''You are an expert project manager. Break down the following goal into a structured, multi-level task plan.
RULES:
1. Create top-level tasks (level 1) as the main phases of the project.
2. For each top-level task that needs more detail, add subtasks (level 2) as "children".
3. If a level 2 subtask still needs more detail, add level 3 sub-subtasks as "children" of that subtask.
4. Do NOT go deeper than 3 levels total.
5. Only add children when a task genuinely benefits from being broken down further. Simple tasks can be left without children.
6. Each task needs: "id" (short URL-friendly slug, unique across the entire plan), "title", "description", "durationInHours" (estimated hours), "dependencies" (list of other task IDs that must complete first - only reference IDs at the SAME level), and optionally "children" (array of subtasks with the same structure).
7. Ensure tasks are in a logical order.
8. The output MUST be valid JSON with a top-level "tasks" key containing the array.
EXAMPLE STRUCTURE:
{{
"tasks": [
{{
"id": "phase-1",
"title": "Phase 1: Research & Planning",
"description": "...",
"durationInHours": 10,
"dependencies": [],
"children": [
{{
"id": "phase-1-research",
"title": "Market Research",
"description": "...",
"durationInHours": 5,
"dependencies": [],
"children": [
{{"id": "phase-1-research-survey", "title": "Create Survey", "description": "...", "durationInHours": 2, "dependencies": []}},
{{"id": "phase-1-research-analyze", "title": "Analyze Results", "description": "...", "durationInHours": 3, "dependencies": ["phase-1-research-survey"]}}
]
}},
{{"id": "phase-1-competitor", "title": "Competitor Analysis", "description": "...", "durationInHours": 5, "dependencies": []}}
]
}},
{{"id": "phase-2", "title": "Phase 2: Development", "description": "...", "durationInHours": 20, "dependencies": ["phase-1"]}}
]
}}
Goal: "{goal}"'''
system_prompt = """You are an expert project manager. You always respond with valid JSON only, no additional text. Structure tasks with up to 3 levels of subtasks when it makes sense."""
async def event_stream():
yield f"data: {json.dumps({'type': 'progress', 'step': 'analyzing', 'progress': 10, 'message': '正在分析你的目标...'})}\n\n"
openai_url = f"{OPENAI_API_URL}/chat/completions"
openai_payload = build_llm_payload(system_prompt, prompt)
headers = build_llm_headers()
yield f"data: {json.dumps({'type': 'progress', 'step': 'connecting', 'progress': 20, 'message': '正在连接 AI 模型...'})}\n\n"
async with httpx.AsyncClient() as client:
try:
yield f"data: {json.dumps({'type': 'progress', 'step': 'generating', 'progress': 35, 'message': 'AI 正在生成计划...'})}\n\n"
response = await client.post(openai_url, json=openai_payload, headers=headers, timeout=180.0)
except httpx.ReadTimeout:
yield f"data: {json.dumps({'type': 'error', 'message': 'AI API 请求超时,请重试'})}\n\n"
return
except httpx.RequestError as e:
yield f"data: {json.dumps({'type': 'error', 'message': f'AI API 请求失败: {str(e)}'})}\n\n"
return
yield f"data: {json.dumps({'type': 'progress', 'step': 'parsing', 'progress': 65, 'message': '正在解析 AI 响应...'})}\n\n"
if response.status_code != 200:
yield f"data: {json.dumps({'type': 'error', 'message': f'AI API 错误: {response.text}'})}\n\n"
return
data = response.json()
content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
if not content:
yield f"data: {json.dumps({'type': 'error', 'message': '无法解析 AI 响应'})}\n\n"
return
try:
tasks_data = json.loads(content)
if isinstance(tasks_data, dict) and "tasks" in tasks_data:
tasks_data = tasks_data["tasks"]
if not isinstance(tasks_data, list):
yield f"data: {json.dumps({'type': 'error', 'message': 'AI 返回了意外的 JSON 结构'})}\n\n"
return
except json.JSONDecodeError:
yield f"data: {json.dumps({'type': 'error', 'message': 'AI 返回了无效的 JSON'})}\n\n"
return
yield f"data: {json.dumps({'type': 'progress', 'step': 'saving', 'progress': 80, 'message': '正在保存计划...'})}\n\n"
from database import SessionLocal
stream_db = SessionLocal()
try:
new_plan = Plan(user_id=user_id, goal=goal)
stream_db.add(new_plan)
stream_db.commit()
stream_db.refresh(new_plan)
all_flat = flatten_tasks(tasks_data, new_plan.id)
sort_idx = 0
def process_level(items: list[dict], parent_db_id=None):
nonlocal sort_idx
for item in items:
children_data = item.pop("_children", [])
item.pop("_level", None)
item["parent_id"] = parent_db_id
task = Task(
plan_id=item["plan_id"],
parent_id=item["parent_id"],
task_id=item["task_id"],
title=item["title"],
description=item["description"],
dependencies=item.get("dependencies", []),
duration_in_hours=item.get("durationInHours", 0),
status="todo",
sort_order=sort_idx,
)
sort_idx += 1
stream_db.add(task)
stream_db.flush()
if children_data:
child_flat = flatten_tasks(children_data, new_plan.id, parent_id=task.id, level=0)
process_level(child_flat, parent_db_id=task.id)
process_level(all_flat)
stream_db.commit()
yield f"data: {json.dumps({'type': 'progress', 'step': 'building', 'progress': 95, 'message': '正在构建任务树...'})}\n\n"
all_tasks = stream_db.query(Task).filter(Task.plan_id == new_plan.id).all()
result_tree = build_task_tree(all_tasks)
yield f"data: {json.dumps({'type': 'complete', 'progress': 100, 'message': '计划生成完成!', 'data': {'plan_id': new_plan.id, 'goal': new_plan.goal, 'created_at': new_plan.created_at.isoformat(), 'tasks': result_tree}})}\n\n"
except Exception as e:
stream_db.rollback()
yield f"data: {json.dumps({'type': 'error', 'message': f'保存计划失败: {str(e)}'})}\n\n"
finally:
stream_db.close()
return StreamingResponse(event_stream(), media_type="text/event-stream")