-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcivicalexai.py
More file actions
91 lines (70 loc) · 2.49 KB
/
Copy pathcivicalexai.py
File metadata and controls
91 lines (70 loc) · 2.49 KB
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
# civicalex ai bot
import os
import json
from fastapi import FastAPI, WebSocket
import traceback
try:
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
os.environ["GOOGLE_API_KEY"] = GOOGLE_API_KEY
print("✅ Google Gemini API key loaded.")
except Exception as e:
print(f"❌ API Key Error: {e}")
try:
from google.adk.agents import Agent
from google.adk.models.google_llm import Gemini
from google.adk.runners import InMemoryRunner
from google.adk.tools import AgentTool, google_search
from google.genai import types
print("✅ ADK modules imported.")
except Exception as e:
print("❌ Failed importing Google ADK:", e)
traceback.print_exc()
app = FastAPI()
retry_config = types.HttpRetryOptions(
attempts=5,
exp_base=7,
initial_delay=1,
http_status_codes=[429, 500, 503, 504],
)
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
print(" Client connected")
try:
while True:
# RECEIVE MESSAGE
data = await websocket.receive_text()
print(" Received:", data)
# Parse JSON safely
try:
msg = json.loads(data)
user_msg = msg.get("message", "")
except:
user_msg = data
root_agent = Agent(
name="ResearchCoordinator",
model=Gemini(
model="gemini-2.5-flash-lite",
retry_options=retry_config
),
instruction=f"Provide a clear, short, and concise answer to {user_msg}.",
tools=[google_search],
)
runner = InMemoryRunner(agent=root_agent )
# RUN WORKFLOW
ai_response = await runner.run_debug(f"answer for {user_msg} ")
# SEND BACK RESPONSE
reply = {
"reply": str(ai_response),
"length": len(str(ai_response)),
}
clean_text = ""
for ev in ai_response:
if hasattr(ev, "content") and ev.content and ev.content.parts:
for part in ev.content.parts:
if hasattr(part, "text") and part.text:
clean_text += part.text + "\n"
await websocket.send_text(clean_text.strip())
except Exception as e:
print(" WebSocket disconnected:", e)
traceback.print_exc()