Spaces:
Running
Running
n0v33n
commited on
Commit
·
d6b66d7
1
Parent(s):
aed7136
async changes
Browse files
app.py
CHANGED
@@ -6,10 +6,8 @@ os.environ['HF_HOME'] = '/tmp/huggingface_cache'
|
|
6 |
os.environ['TRANSFORMERS_CACHE'] = '/tmp/transformers_cache'
|
7 |
os.environ['HF_DATASETS_CACHE'] = '/tmp/datasets_cache'
|
8 |
|
9 |
-
# Suppress warnings
|
10 |
warnings.filterwarnings("ignore")
|
11 |
|
12 |
-
# Now import everything else
|
13 |
import json
|
14 |
from fastapi import FastAPI, HTTPException
|
15 |
from pydantic import BaseModel
|
@@ -19,6 +17,7 @@ from google.adk.sessions import InMemorySessionService
|
|
19 |
from google.adk.runners import Runner
|
20 |
from google.genai import types
|
21 |
import re
|
|
|
22 |
from tools import (
|
23 |
db_tool,
|
24 |
tavily_tool,
|
@@ -163,6 +162,7 @@ INSTITUTE_MAPPING = {
|
|
163 |
"gkv": ["gurukula kangri vishwavidyalaya"],
|
164 |
"GKV": ["gurukula kangri vishwavidyalaya"]
|
165 |
}
|
|
|
166 |
BRANCH_MAPPING = {
|
167 |
"cse": "computer science and engineering",
|
168 |
"CSE": "computer science and engineering",
|
@@ -178,8 +178,6 @@ BRANCH_MAPPING = {
|
|
178 |
"CE": "civil engineering",
|
179 |
"che": "chemical engineering",
|
180 |
"CHE": "chemical engineering",
|
181 |
-
# "it": "information technology",
|
182 |
-
# "IT": "information technology",
|
183 |
"aero": "aerospace engineering",
|
184 |
"AERO": "aerospace engineering",
|
185 |
"bio": "biotechnology",
|
@@ -198,8 +196,9 @@ def preprocess_query(query: str) -> str:
|
|
198 |
query = re.sub(pattern, full_name, query, flags=re.IGNORECASE)
|
199 |
|
200 |
return query
|
|
|
201 |
# === AGENT SETUP ===
|
202 |
-
def create_agent_runner(user_id: str, session_id: str):
|
203 |
instruction_text="""
|
204 |
You are a highly experienced college counselor specializing in helping high school students choose the right engineering colleges. You have access to several tools to help answer student queries.
|
205 |
|
@@ -270,12 +269,36 @@ IMPORTANT RULES:
|
|
270 |
temperature=0.1,
|
271 |
),
|
272 |
)
|
|
|
273 |
session_svc = InMemorySessionService()
|
274 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
275 |
runner = Runner(agent=agent, app_name="college_agent_app", session_service=session_svc)
|
276 |
return runner, session
|
|
|
277 |
# === FASTAPI SETUP ===
|
278 |
-
app = FastAPI(
|
|
|
|
|
|
|
|
|
279 |
|
280 |
class ChatRequest(BaseModel):
|
281 |
user_id: str
|
@@ -285,42 +308,88 @@ class ChatRequest(BaseModel):
|
|
285 |
class ChatResponse(BaseModel):
|
286 |
session_id: str
|
287 |
answer: str
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
288 |
@app.post("/chat", response_model=ChatResponse)
|
289 |
async def chat_endpoint(req: ChatRequest):
|
290 |
try:
|
291 |
-
runner, session = create_agent_runner(req.user_id, req.session_id)
|
292 |
processed_query = preprocess_query(req.question)
|
293 |
-
|
294 |
user_msg = types.Content(role="user", parts=[types.Part(text=processed_query)])
|
295 |
reply_text = ""
|
296 |
|
297 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
298 |
|
299 |
-
|
300 |
-
|
301 |
-
|
302 |
-
|
303 |
-
if part.text:
|
304 |
-
reply_text = part.text
|
305 |
-
break
|
306 |
-
except Exception:
|
307 |
try:
|
308 |
-
|
|
|
|
|
|
|
309 |
except Exception:
|
310 |
try:
|
311 |
-
reply_text =
|
312 |
except Exception:
|
313 |
-
|
314 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
315 |
|
316 |
-
add_query_to_sheet(req.user_id, processed_query, reply_text)
|
317 |
return ChatResponse(session_id=session.id, answer=reply_text)
|
318 |
|
319 |
except Exception as e:
|
|
|
320 |
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
|
|
|
321 |
@app.get("/healthz")
|
322 |
def health_check():
|
323 |
-
return {"status": "ok"}
|
324 |
-
|
325 |
-
|
326 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
os.environ['TRANSFORMERS_CACHE'] = '/tmp/transformers_cache'
|
7 |
os.environ['HF_DATASETS_CACHE'] = '/tmp/datasets_cache'
|
8 |
|
|
|
9 |
warnings.filterwarnings("ignore")
|
10 |
|
|
|
11 |
import json
|
12 |
from fastapi import FastAPI, HTTPException
|
13 |
from pydantic import BaseModel
|
|
|
17 |
from google.adk.runners import Runner
|
18 |
from google.genai import types
|
19 |
import re
|
20 |
+
import asyncio
|
21 |
from tools import (
|
22 |
db_tool,
|
23 |
tavily_tool,
|
|
|
162 |
"gkv": ["gurukula kangri vishwavidyalaya"],
|
163 |
"GKV": ["gurukula kangri vishwavidyalaya"]
|
164 |
}
|
165 |
+
|
166 |
BRANCH_MAPPING = {
|
167 |
"cse": "computer science and engineering",
|
168 |
"CSE": "computer science and engineering",
|
|
|
178 |
"CE": "civil engineering",
|
179 |
"che": "chemical engineering",
|
180 |
"CHE": "chemical engineering",
|
|
|
|
|
181 |
"aero": "aerospace engineering",
|
182 |
"AERO": "aerospace engineering",
|
183 |
"bio": "biotechnology",
|
|
|
196 |
query = re.sub(pattern, full_name, query, flags=re.IGNORECASE)
|
197 |
|
198 |
return query
|
199 |
+
|
200 |
# === AGENT SETUP ===
|
201 |
+
async def create_agent_runner(user_id: str, session_id: str):
|
202 |
instruction_text="""
|
203 |
You are a highly experienced college counselor specializing in helping high school students choose the right engineering colleges. You have access to several tools to help answer student queries.
|
204 |
|
|
|
269 |
temperature=0.1,
|
270 |
),
|
271 |
)
|
272 |
+
|
273 |
session_svc = InMemorySessionService()
|
274 |
+
|
275 |
+
# Handle potential async session creation
|
276 |
+
try:
|
277 |
+
session = session_svc.create_session(
|
278 |
+
app_name="college_agent_app",
|
279 |
+
user_id=user_id,
|
280 |
+
session_id=session_id
|
281 |
+
)
|
282 |
+
# If it's a coroutine, await it
|
283 |
+
if asyncio.iscoroutine(session):
|
284 |
+
session = await session
|
285 |
+
except Exception as e:
|
286 |
+
print(f"Session creation error: {e}")
|
287 |
+
# Fallback: create a simple session object
|
288 |
+
class SimpleSession:
|
289 |
+
def __init__(self, session_id):
|
290 |
+
self.id = session_id
|
291 |
+
session = SimpleSession(session_id)
|
292 |
+
|
293 |
runner = Runner(agent=agent, app_name="college_agent_app", session_service=session_svc)
|
294 |
return runner, session
|
295 |
+
|
296 |
# === FASTAPI SETUP ===
|
297 |
+
app = FastAPI(
|
298 |
+
title="College Counselor Agent",
|
299 |
+
description="AI Agent for college counseling and selection",
|
300 |
+
version="1.0.0"
|
301 |
+
)
|
302 |
|
303 |
class ChatRequest(BaseModel):
|
304 |
user_id: str
|
|
|
308 |
class ChatResponse(BaseModel):
|
309 |
session_id: str
|
310 |
answer: str
|
311 |
+
|
312 |
+
@app.get("/")
|
313 |
+
async def root():
|
314 |
+
return {
|
315 |
+
"message": "College Counselor Agent is running!",
|
316 |
+
"docs": "/docs",
|
317 |
+
"health": "/healthz"
|
318 |
+
}
|
319 |
+
|
320 |
@app.post("/chat", response_model=ChatResponse)
|
321 |
async def chat_endpoint(req: ChatRequest):
|
322 |
try:
|
323 |
+
runner, session = await create_agent_runner(req.user_id, req.session_id)
|
324 |
processed_query = preprocess_query(req.question)
|
325 |
+
|
326 |
user_msg = types.Content(role="user", parts=[types.Part(text=processed_query)])
|
327 |
reply_text = ""
|
328 |
|
329 |
+
# Handle potential async runner execution
|
330 |
+
try:
|
331 |
+
events = runner.run(user_id=req.user_id, session_id=session.id, new_message=user_msg)
|
332 |
+
|
333 |
+
# If events is a coroutine, await it
|
334 |
+
if asyncio.iscoroutine(events):
|
335 |
+
events = await events
|
336 |
+
except Exception as runner_error:
|
337 |
+
print(f"Runner error: {runner_error}")
|
338 |
+
return ChatResponse(
|
339 |
+
session_id=session.id,
|
340 |
+
answer="Sorry, I encountered an error processing your request. Please try again."
|
341 |
+
)
|
342 |
|
343 |
+
# Process events
|
344 |
+
try:
|
345 |
+
for ev in events:
|
346 |
+
if hasattr(ev, 'is_final_response') and ev.is_final_response():
|
|
|
|
|
|
|
|
|
347 |
try:
|
348 |
+
for part in ev.content.parts:
|
349 |
+
if hasattr(part, 'text') and part.text:
|
350 |
+
reply_text = part.text
|
351 |
+
break
|
352 |
except Exception:
|
353 |
try:
|
354 |
+
reply_text = getattr(ev, 'text', '')
|
355 |
except Exception:
|
356 |
+
try:
|
357 |
+
reply_text = str(getattr(ev, 'message', ''))
|
358 |
+
except Exception:
|
359 |
+
reply_text = "Sorry, I couldn't process the response properly."
|
360 |
+
break
|
361 |
+
except Exception as event_error:
|
362 |
+
print(f"Event processing error: {event_error}")
|
363 |
+
reply_text = "Sorry, I encountered an error while processing the response."
|
364 |
+
|
365 |
+
# Fallback if no reply_text
|
366 |
+
if not reply_text:
|
367 |
+
reply_text = "I'm sorry, I couldn't generate a proper response. Please try rephrasing your question."
|
368 |
+
|
369 |
+
# Log to sheet (handle potential errors)
|
370 |
+
try:
|
371 |
+
add_query_to_sheet(req.user_id, processed_query, reply_text)
|
372 |
+
except Exception as sheet_error:
|
373 |
+
print(f"Sheet logging error: {sheet_error}")
|
374 |
+
# Don't fail the request if logging fails
|
375 |
|
|
|
376 |
return ChatResponse(session_id=session.id, answer=reply_text)
|
377 |
|
378 |
except Exception as e:
|
379 |
+
print(f"Chat endpoint error: {str(e)}")
|
380 |
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
|
381 |
+
|
382 |
@app.get("/healthz")
|
383 |
def health_check():
|
384 |
+
return {"status": "ok", "service": "college-counselor-agent"}
|
385 |
+
|
386 |
+
# Add a simple test endpoint
|
387 |
+
@app.get("/test")
|
388 |
+
async def test_endpoint():
|
389 |
+
return {
|
390 |
+
"message": "Test endpoint working",
|
391 |
+
"env_vars": {
|
392 |
+
"HF_HOME": os.environ.get('HF_HOME'),
|
393 |
+
"TRANSFORMERS_CACHE": os.environ.get('TRANSFORMERS_CACHE')
|
394 |
+
}
|
395 |
+
}
|