Spaces:
Running
Running
| from langchain_core.messages import HumanMessage, SystemMessage | |
| def route_query(query, llm) -> str: | |
| """ | |
| Analyzes the user query and determines if it requires official documents | |
| or general college/student life advice. | |
| """ | |
| # Keep the system instructions separate to guide the model's behavior explicitly | |
| system_instruction = ( | |
| "You are a strict backend query router for a college chatbot. " | |
| "Classify queries into exactly one of two categories: 'CAMPUS_DOCS' or 'GENERAL_ADVICE'. " | |
| "Output ONLY the category name. Do not include any punctuation, conversational filler, or extra words." | |
| ) | |
| user_prompt = f"""Rules: | |
| - Choose 'CAMPUS_DOCS' if the query asks for specific facts, official rules, dates, ordinances, syllabus details, or event schedules that MUST be looked up in university documents. | |
| - Choose 'GENERAL_ADVICE' if the query asks for subjective opinions, tips, strategies, general student guidance, study habits, motivation, or career paths. | |
| User Query: {query} | |
| Category:""" | |
| # CRITICAL FIX: Pass structured messages, NOT a raw string array | |
| messages = [ | |
| SystemMessage(content=system_instruction), | |
| HumanMessage(content=user_prompt) | |
| ] | |
| try: | |
| response = llm2.invoke(messages) | |
| # Clean the output string | |
| cleaned_route = response.content.strip().upper() | |
| # Defensive check in case the LLM spits out conversational garbage anyway | |
| if "CAMPUS_DOCS" in cleaned_route: | |
| return "CAMPUS_DOCS" | |
| else: | |
| return "GENERAL_ADVICE" | |
| except Exception as e: | |
| print(f"[Router Error] LLM routing failed due to: {e}. Falling back to CAMPUS_DOCS.") | |
| return "CAMPUS_DOCS" |