crew / app.py
arnekm's picture
Create app.py
4a5a949 verified
Raw History Blame Contribute Delete
5.71 kB
"""
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)