|
| 1 | +import traceback |
| 2 | +import uuid |
| 3 | + |
| 4 | +from crewai import Agent, Crew, Process, Task |
| 5 | +from dotenv import load_dotenv |
| 6 | +from fastapi import FastAPI |
| 7 | +from pydantic import BaseModel |
| 8 | + |
| 9 | +load_dotenv() |
| 10 | + |
| 11 | +app = FastAPI() |
| 12 | + |
| 13 | +@app.get("/health") |
| 14 | +def health(): |
| 15 | + return {"ok": True} |
| 16 | + |
| 17 | + |
| 18 | +class ChatCompletionRequest(BaseModel): |
| 19 | + model: str | None = None |
| 20 | + messages: list[dict] # [{"role":"user","content":"hello"}] |
| 21 | + temperature: float | None = None |
| 22 | + stream: bool | None = False |
| 23 | + |
| 24 | + |
| 25 | +def run_crewai(user_text: str) -> str: |
| 26 | + # Minimal CrewAI example: 1 agent, 1 task |
| 27 | + agent = Agent( |
| 28 | + role="Assistant", |
| 29 | + goal="Reply helpfully and concisely.", |
| 30 | + backstory="You are a helpful AI agent hosted for ADP integration.", |
| 31 | + verbose=True, |
| 32 | + allow_delegation=False, |
| 33 | + ) |
| 34 | + |
| 35 | + task = Task( |
| 36 | + description=f"User said: {user_text}\nReply to the user.", |
| 37 | + expected_output="A helpful natural-language reply to the user.", |
| 38 | + agent=agent, |
| 39 | + ) |
| 40 | + |
| 41 | + crew = Crew( |
| 42 | + agents=[agent], |
| 43 | + tasks=[task], |
| 44 | + process=Process.sequential, |
| 45 | + verbose=1, |
| 46 | + ) |
| 47 | + |
| 48 | + result = crew.kickoff() |
| 49 | + return str(result) |
| 50 | + |
| 51 | + |
| 52 | +@app.post("/v1/chat/completions") |
| 53 | +async def chat_completions(req: ChatCompletionRequest): |
| 54 | + try: |
| 55 | + user_text = "" |
| 56 | + for m in reversed(req.messages): |
| 57 | + if m.get("role") == "user": |
| 58 | + user_text = (m.get("content") or "").strip() |
| 59 | + break |
| 60 | + |
| 61 | + if not user_text: |
| 62 | + return { |
| 63 | + "error": { |
| 64 | + "message": "No user message provided.", |
| 65 | + "type": "invalid_request_error", |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + answer = run_crewai(user_text) |
| 70 | + |
| 71 | + return { |
| 72 | + "id": f"chatcmpl-{uuid.uuid4().hex}", |
| 73 | + "object": "chat.completion", |
| 74 | + "choices": [ |
| 75 | + { |
| 76 | + "index": 0, |
| 77 | + "message": {"role": "assistant", "content": answer}, |
| 78 | + "finish_reason": "stop", |
| 79 | + } |
| 80 | + ], |
| 81 | + } |
| 82 | + except Exception: |
| 83 | + traceback.print_exc() |
| 84 | + return { |
| 85 | + "error": { |
| 86 | + "message": "An internal error occurred.", |
| 87 | + "type": "internal_error", |
| 88 | + } |
| 89 | + } |
0 commit comments