Benny-Tang commited on
Commit
660ad8c
·
verified ·
1 Parent(s): 57235b5

Create api.py

Browse files
Files changed (1) hide show
  1. api.py +119 -0
api.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # api.py
2
+ from typing import Dict, Optional
3
+ import os
4
+ import asyncio
5
+ import json
6
+ from fastapi import FastAPI, APIRouter
7
+ from pydantic import BaseModel
8
+
9
+ # --------------------------
10
+ # Config
11
+ # --------------------------
12
+ AGENT_NAMES = {
13
+ 1: "Agent 1 (GLM 4.5)",
14
+ 2: "Agent 2 (GLM 4.5)",
15
+ 3: "Agent 3 (GLM 4.5)",
16
+ 4: "Agent 4 (GLM 4.5)",
17
+ }
18
+
19
+ ZHIPUAI_API_KEY = os.getenv("ZHIPUAI_API_KEY") # Optional; if missing, we fallback to echo mode.
20
+ GLM_MODEL = os.getenv("GLM_MODEL", "glm-4-5") # Placeholder name; adjust if needed.
21
+
22
+ # --------------------------
23
+ # Schemas
24
+ # --------------------------
25
+ class MessageRequest(BaseModel):
26
+ message: str
27
+
28
+ class AgentResponse(BaseModel):
29
+ agent: str
30
+ response: str
31
+
32
+ # --------------------------
33
+ # Core agent call
34
+ # --------------------------
35
+ async def call_glm_45(agent_label: str, message: str) -> str:
36
+ """
37
+ Calls GLM 4.5 (or returns a graceful echo if API key isn't set).
38
+ This function is isolated so both FastAPI and Gradio can reuse it.
39
+ """
40
+ if not ZHIPUAI_API_KEY:
41
+ # Safe fallback when no API key is present.
42
+ await asyncio.sleep(0) # yield control
43
+ return f"[{agent_label}] Echo: {message}"
44
+
45
+ # If you have ZHIPUAI_API_KEY set, implement the real API call here.
46
+ # This is a stub to avoid runtime errors if the SDK/endpoint changes.
47
+ # Replace this section with the ZhipuAI client code you use in production.
48
+ try:
49
+ import httpx
50
+ # Example placeholder POST; adjust to the actual ZhipuAI API.
51
+ # If you know the official SDK, swap this for that instead.
52
+ url = "https://open.bigmodel.cn/api/paas/v4/chat/completions"
53
+ headers = {
54
+ "Authorization": f"Bearer {ZHIPUAI_API_KEY}",
55
+ "Content-Type": "application/json",
56
+ }
57
+ payload = {
58
+ "model": GLM_MODEL,
59
+ "messages": [
60
+ {"role": "system", "content": f"You are {agent_label}."},
61
+ {"role": "user", "content": message},
62
+ ],
63
+ "temperature": 0.7,
64
+ }
65
+ async with httpx.AsyncClient(timeout=60) as client:
66
+ r = await client.post(url, headers=headers, data=json.dumps(payload))
67
+ r.raise_for_status()
68
+ data = r.json()
69
+ # Adapt this extraction to the API's actual response schema:
70
+ content = (
71
+ data.get("choices", [{}])[0]
72
+ .get("message", {})
73
+ .get("content", "")
74
+ ) or json.dumps(data) # fallback to raw
75
+ return content.strip()
76
+ except Exception as e:
77
+ # Never crash the app — degrade gracefully.
78
+ return f"[{agent_label}] GLM call failed ({type(e).__name__}): {e}. Fallback: {message}"
79
+
80
+ async def run_agent(agent_id: int, message: str) -> str:
81
+ agent_label = AGENT_NAMES.get(agent_id, f"Agent {agent_id} (GLM 4.5)")
82
+ return await call_glm_45(agent_label, message)
83
+
84
+ async def run_all_agents(message: str) -> Dict[str, str]:
85
+ tasks = [run_agent(i, message) for i in sorted(AGENT_NAMES.keys())]
86
+ results = await asyncio.gather(*tasks)
87
+ return {f"agent{i}": resp for i, resp in zip(sorted(AGENT_NAMES.keys()), results)}
88
+
89
+ # --------------------------
90
+ # FastAPI App + Routes
91
+ # --------------------------
92
+ api = FastAPI(title="Multi-Agent Control Panel API", version="1.0.0")
93
+ router = APIRouter(prefix="/api")
94
+
95
+ @router.post("/agent1", response_model=AgentResponse)
96
+ async def agent1(req: MessageRequest):
97
+ resp = await run_agent(1, req.message)
98
+ return AgentResponse(agent=AGENT_NAMES[1], response=resp)
99
+
100
+ @router.post("/agent2", response_model=AgentResponse)
101
+ async def agent2(req: MessageRequest):
102
+ resp = await run_agent(2, req.message)
103
+ return AgentResponse(agent=AGENT_NAMES[2], response=resp)
104
+
105
+ @router.post("/agent3", response_model=AgentResponse)
106
+ async def agent3(req: MessageRequest):
107
+ resp = await run_agent(3, req.message)
108
+ return AgentResponse(agent=AGENT_NAMES[3], response=resp)
109
+
110
+ @router.post("/agent4", response_model=AgentResponse)
111
+ async def agent4(req: MessageRequest):
112
+ resp = await run_agent(4, req.message)
113
+ return AgentResponse(agent=AGENT_NAMES[4], response=resp)
114
+
115
+ @router.post("/run_all")
116
+ async def run_all(req: MessageRequest):
117
+ return await run_all_agents(req.message)
118
+
119
+ api.include_router(router)