""" app.py — CrewAI 管理層 Space 的 FastAPI 入口 HuggingFace Space 會暴露 port 7860 """ import os import asyncio import traceback from typing import Optional from fastapi import FastAPI, HTTPException, BackgroundTasks from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel from crewai import Crew, Process from agents import make_ceo_agent, make_marketing_agent, make_business_analyst_agent from tasks import ( strategy_task, product_spec_task, marketing_content_task, market_research_task, sales_sequence_task, ) from key_rotator import rotator app = FastAPI( title="AI 公司 — 管理層 & 市場部", description="CrewAI 驅動的管理層 API", version="1.0.0", ) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], ) # ── 任務狀態追蹤 ────────────────────────────────────────────────────────────── job_store: dict[str, dict] = {} # ── 請求模型 ────────────────────────────────────────────────────────────────── class StrategyRequest(BaseModel): objective: str job_id: Optional[str] = None class ProductRequest(BaseModel): feature_request: str context: str = "" job_id: Optional[str] = None class MarketingRequest(BaseModel): topic: str content_type: str = "blog" # blog | twitter | linkedin | email | newsletter job_id: Optional[str] = None class ResearchRequest(BaseModel): query: str job_id: Optional[str] = None class SalesRequest(BaseModel): product: str target_customer: str job_id: Optional[str] = None # ── 工具函數 ────────────────────────────────────────────────────────────────── def _run_crew(task, agents_list, job_id: str): """執行 Crew 任務並更新狀態""" job_store[job_id] = {"status": "running", "result": None, "error": None} try: crew = Crew( agents=agents_list, tasks=[task], process=Process.sequential, verbose=True, memory=False, # 省記憶體(免費 tier) ) result = crew.kickoff() job_store[job_id] = {"status": "done", "result": str(result), "error": None} except Exception as e: job_store[job_id] = { "status": "error", "result": None, "error": traceback.format_exc(), } # ── 端點 ───────────────────────────────────────────────────────────────────── @app.get("/") def root(): return {"service": "CrewAI Management Layer", "status": "online"} @app.get("/health") def health(): return {"status": "ok", "keys_status": rotator.status()} @app.get("/jobs/{job_id}") def get_job(job_id: str): if job_id not in job_store: raise HTTPException(404, f"Job {job_id} not found") return job_store[job_id] @app.post("/strategy") async def create_strategy(req: StrategyRequest, background_tasks: BackgroundTasks): """CEO 制定策略""" job_id = req.job_id or f"strategy_{int(asyncio.get_event_loop().time())}" task, agents_list = strategy_task(req.objective) background_tasks.add_task(_run_crew, task, agents_list, job_id) return {"job_id": job_id, "status": "queued"} @app.post("/product-spec") async def create_product_spec(req: ProductRequest, background_tasks: BackgroundTasks): """PM 撰寫 PRD""" job_id = req.job_id or f"prd_{int(asyncio.get_event_loop().time())}" task, agents_list = product_spec_task(req.feature_request, req.context) background_tasks.add_task(_run_crew, task, agents_list, job_id) return {"job_id": job_id, "status": "queued"} @app.post("/marketing") async def create_marketing_content(req: MarketingRequest, background_tasks: BackgroundTasks): """市場部內容創作""" valid_types = {"blog", "twitter", "linkedin", "email", "newsletter"} if req.content_type not in valid_types: raise HTTPException(400, f"content_type must be one of {valid_types}") job_id = req.job_id or f"mkt_{int(asyncio.get_event_loop().time())}" task, agents_list = marketing_content_task(req.topic, req.content_type) background_tasks.add_task(_run_crew, task, agents_list, job_id) return {"job_id": job_id, "status": "queued"} @app.post("/research") async def market_research(req: ResearchRequest, background_tasks: BackgroundTasks): """商業分析師市場研究""" job_id = req.job_id or f"research_{int(asyncio.get_event_loop().time())}" task, agents_list = market_research_task(req.query) background_tasks.add_task(_run_crew, task, agents_list, job_id) return {"job_id": job_id, "status": "queued"} @app.post("/sales-sequence") async def create_sales_sequence(req: SalesRequest, background_tasks: BackgroundTasks): """SDR 銷售序列生成""" job_id = req.job_id or f"sales_{int(asyncio.get_event_loop().time())}" task, agents_list = sales_sequence_task(req.product, req.target_customer) background_tasks.add_task(_run_crew, task, agents_list, job_id) return {"job_id": job_id, "status": "queued"} if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=7860)