File size: 5,853 Bytes
b8f3d48
0d2526a
b8f3d48
0d2526a
 
 
 
 
 
 
 
b8f3d48
 
 
 
 
 
0d2526a
b8f3d48
 
0d2526a
 
 
b8f3d48
0d2526a
 
b8f3d48
 
0d2526a
b8f3d48
 
 
0d2526a
b8f3d48
0d2526a
 
b8f3d48
0d2526a
b8f3d48
 
 
0d2526a
 
b8f3d48
 
 
 
0d2526a
b8f3d48
0d2526a
 
 
b8f3d48
0d2526a
 
 
 
 
 
b8f3d48
 
 
0d2526a
 
 
 
b8f3d48
 
0d2526a
b8f3d48
0d2526a
 
 
 
 
 
 
 
b8f3d48
0d2526a
 
 
 
 
b8f3d48
0d2526a
 
 
 
 
 
 
 
 
b8f3d48
 
 
 
0d2526a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b8f3d48
 
 
 
0d2526a
b8f3d48
 
 
 
 
0d2526a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b8f3d48
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
"""
Shami's Multi-Agent System β€” FastAPI server for HuggingFace Spaces.

5 purpose-built agents, each with custom tools:
  - Job Search: find, evaluate, draft cover letters
  - Research: multi-source research with structured reports
  - Code Review: GitHub PR analysis
  - Upwork Proposals: tailored proposal drafting
  - n8n Handler: freelance message analysis + reply drafting

All powered by Groq (free, fast) with Tavily web search.
"""

import os
import json
from datetime import datetime
from contextlib import asynccontextmanager
from pathlib import Path

from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse, FileResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field

from agents.engine import run_agent
from agents.definitions import AGENTS


# ── App setup ────────────────────────────────────────────────────────────────

@asynccontextmanager
async def lifespan(app: FastAPI):
    print(f"[{datetime.now().isoformat()}] Starting Shami's Agent System")
    print(f"  GROQ_API_KEY: {'SET' if os.environ.get('GROQ_API_KEY') else 'MISSING'}")
    print(f"  TAVILY_API_KEY: {'SET' if os.environ.get('TAVILY_API_KEY') else 'MISSING'}")
    print(f"  Agents: {', '.join(AGENTS.keys())}")
    yield
    print("Shutting down.")


app = FastAPI(
    title="Shami's Agent System",
    description="Multi-agent AI system β€” job search, research, code review, proposals, freelance messaging",
    lifespan=lifespan,
)


# ── Request/Response models ──────────────────────────────────────────────────

class AgentRequest(BaseModel):
    message: str = Field(..., description="The goal or task for the agent")
    conversation_id: str = Field(default="default", description="Conversation ID for context")

class AgentResponse(BaseModel):
    agent: str
    result: str
    tool_calls_made: int
    tools_used: list[str]
    iterations: int
    conversation_id: str
    timestamp: str

class N8nWebhookRequest(BaseModel):
    message: str = Field(..., description="The incoming freelance message")
    platform: str = Field(default="unknown", description="Source platform (upwork/fiverr/email)")
    sender: str = Field(default="", description="Sender name or username")


# ── Agent endpoints ──────────────────────────────────────────────────────────

@app.post("/agent/{agent_type}", response_model=AgentResponse)
async def run_agent_endpoint(agent_type: str, req: AgentRequest):
    """Run a specific agent with a goal."""
    if agent_type not in AGENTS:
        raise HTTPException(
            status_code=404,
            detail=f"Unknown agent: {agent_type}. Available: {list(AGENTS.keys())}",
        )

    agent_def = AGENTS[agent_type]
    result = await run_agent(
        goal=req.message,
        system_prompt=agent_def["prompt"],
        tools=agent_def["tools"],
        conversation_id=req.conversation_id,
    )

    return AgentResponse(
        agent=agent_def["name"],
        result=result["result"],
        tool_calls_made=result["tool_calls_made"],
        tools_used=result["tools_used"],
        iterations=result["iterations"],
        conversation_id=result["conversation_id"],
        timestamp=datetime.now().isoformat(),
    )


@app.post("/agent/n8n", response_model=AgentResponse)
async def n8n_webhook(req: N8nWebhookRequest):
    """n8n webhook endpoint β€” receives freelance messages, returns analysis + draft reply."""
    agent_def = AGENTS["n8n"]
    goal = f"Platform: {req.platform}\nSender: {req.sender}\n\nMessage:\n{req.message}"

    result = await run_agent(
        goal=goal,
        system_prompt=agent_def["prompt"],
        tools=agent_def["tools"],
        conversation_id=f"n8n-{datetime.now().strftime('%Y%m%d-%H%M')}",
    )

    return AgentResponse(
        agent=agent_def["name"],
        result=result["result"],
        tool_calls_made=result["tool_calls_made"],
        tools_used=result["tools_used"],
        iterations=result["iterations"],
        conversation_id=result["conversation_id"],
        timestamp=datetime.now().isoformat(),
    )


# ── Utility endpoints ────────────────────────────────────────────────────────

@app.get("/health")
async def health():
    return {
        "status": "ok",
        "agents": {k: {"name": v["name"], "tools": [t.__name__ for t in v["tools"]]} for k, v in AGENTS.items()},
        "model": "groq/llama-3.3-70b-versatile",
        "timestamp": datetime.now().isoformat(),
    }


@app.get("/agents")
async def list_agents():
    """List all available agents with their descriptions."""
    return {
        "agents": [
            {
                "id": k,
                "name": v["name"],
                "description": v["description"],
                "icon": v["icon"],
                "tools": [t.__name__ for t in v["tools"]],
                "endpoint": f"/agent/{k}",
            }
            for k, v in AGENTS.items()
        ]
    }


# ── Web UI ───────────────────────────────────────────────────────────────────

@app.get("/", response_class=HTMLResponse)
async def home():
    return (Path(__file__).parent / "static" / "index.html").read_text()


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)