Spaces:
Running
Running
Download core/graph.py from rvdbra/EinbuergDemoforTesting: direct link, hf CLI and curl.
- Browser
- Download file 6.77 kB
-
https://huggingface.co/spaces/rvdbra/EinbuergDemoforTesting/resolve/main/core/graph.py
- Command line
-
hf download hf://spaces/rvdbra/EinbuergDemoforTesting/core/graph.py
-
curl -L -o graph.py https://huggingface.co/spaces/rvdbra/EinbuergDemoforTesting/resolve/main/core/graph.py
6.77 kB
| from langgraph.graph import StateGraph, END | |
| from core.state import CustomState | |
| from core.router import route_or_reply | |
| from core.llm import llm | |
| from memory.supabase_memory import MemoryStore | |
| from core.retrieval import retrieve | |
| from .config import SUPABASE_CLIENT | |
| from data.prompts import SYSTEM_MESSAGE_TEXT | |
| from langchain_core.messages import HumanMessage, AIMessage | |
| from .services.web_search import WebSearch, filter_blocked_links, ensure_einbuergerung_reference | |
| from datetime import datetime | |
| import re | |
| from utils.logging import log | |
| store = MemoryStore() | |
| web_search = WebSearch() | |
| supabase = SUPABASE_CLIENT | |
| def log_interaction_cloud(user_id: str, question: str, answer: str): | |
| payload = {"user_id": user_id, "question": question, "answer": answer, "timestamp": datetime.utcnow().isoformat()} | |
| try: | |
| supabase.table("logs").insert(payload).execute() | |
| except Exception as e: | |
| print("[Supabase Log Error]:", e) | |
| def generate_user_id(): | |
| import uuid | |
| return "user_" + uuid.uuid4().hex[:6] | |
| def extract_location_from_decision(decision: dict, current_location: str = None) -> str: | |
| """Extract location from router decision or use stored location.""" | |
| if decision.get("location") and decision.get("location").strip(): | |
| return decision.get("location").strip() | |
| return current_location or "" | |
| def extract_location_from_history(messages) -> str: | |
| for msg in reversed(messages): | |
| content = msg.content if hasattr(msg, 'content') else str(msg) | |
| match = re.search(r'\[Location:\s*([^\]]+)\]', content) | |
| if match: | |
| return match.group(1).strip() | |
| return "" | |
| def query_or_respond(state: CustomState): | |
| user_id = state.get("user_id") or generate_user_id() | |
| human_messages = [m for m in state["messages"] if m.type == "human"] | |
| latest_user_msg = human_messages[-1] | |
| memory = store.get_memory(user_id) | |
| history = memory.messages | |
| current_location = extract_location_from_history(history) or state.get("current_location") or "" | |
| decision = route_or_reply(latest_user_msg.content, history) | |
| history_tail = history[-5:] | |
| new_location = extract_location_from_decision(decision, current_location) | |
| if decision.get("action") in ["web_search", "hybrid_search"]: | |
| if decision.get("needs_location") and not decision.get("location_provided"): | |
| router_text = decision.get("text", "") or "" | |
| is_asking_for_new_location = bool(router_text.strip()) | |
| if is_asking_for_new_location: | |
| log.info(f"New location mentioned needs clarification, not using stored location") | |
| new_location = "" | |
| elif new_location: | |
| decision["location"] = new_location | |
| decision["location_provided"] = True | |
| log.info(f"Using stored location: {new_location}") | |
| user_msg_content = latest_user_msg.content | |
| if new_location: | |
| user_msg_content = f"{latest_user_msg.content} [Location: {new_location}]" | |
| if decision.get("action"): | |
| if decision.get("action") == "reply": | |
| response = AIMessage(content=decision.get("text", "")) | |
| memory.add_user_message(user_msg_content) | |
| memory.add_ai_message(response.content) | |
| log_interaction_cloud(user_id, latest_user_msg.content, response.content) | |
| return {**state, "messages": [response], "user_id": user_id, "current_location": new_location} | |
| elif decision.get("action") == "retrieve": | |
| normalized_query = decision.get("normalized_query") or latest_user_msg.content | |
| retrieved_text, _ = retrieve(normalized_query) | |
| system_msg = HumanMessage(SYSTEM_MESSAGE_TEXT + "\n\n" + retrieved_text) | |
| prompt = [system_msg] + history_tail + [latest_user_msg] | |
| response = llm.invoke(prompt) | |
| language = decision.get("language", "de") | |
| response_text = filter_blocked_links(response.content) | |
| response_text = ensure_einbuergerung_reference(response_text, is_general_query=True, language=language) | |
| response = AIMessage(content=response_text) | |
| memory.add_user_message(user_msg_content) | |
| memory.add_ai_message(response.content) | |
| log_interaction_cloud(user_id, latest_user_msg.content, response.content) | |
| return {**state, "messages": [response], "user_id": user_id, "current_location": new_location} | |
| elif decision.get("action") == "web_search": | |
| if decision.get("needs_location") and not decision.get("location_provided") and decision.get("text"): | |
| full_text = decision.get("text") | |
| else: | |
| full_text = web_search.query_api(decision, history_tail) | |
| language = decision.get("language", "de") | |
| full_text = filter_blocked_links(full_text) | |
| full_text = ensure_einbuergerung_reference(full_text, is_general_query=True, language=language) | |
| response = AIMessage(content=full_text) | |
| memory.add_user_message(user_msg_content) | |
| memory.add_ai_message(response.content) | |
| log_interaction_cloud(user_id, latest_user_msg.content, response.content) | |
| return {**state, "messages": [response], "user_id": user_id, "current_location": new_location} | |
| elif decision.get("action") == "hybrid_search": | |
| if decision.get("needs_location") and not decision.get("location_provided") and decision.get("text"): | |
| full_text = decision.get("text") | |
| else: | |
| log.info(f"Invoking hybrid search api") | |
| normalized_retrieval_query = decision.get("normalized_retrieval_query") | |
| retrieved_text, _ = retrieve(normalized_retrieval_query) | |
| full_text = web_search.query_api(decision, history_tail, retrieved_text) | |
| # Apply filters | |
| language = decision.get("language", "de") | |
| full_text = filter_blocked_links(full_text) | |
| full_text = ensure_einbuergerung_reference(full_text, is_general_query=True, language=language) | |
| response = AIMessage(content=full_text) | |
| memory.add_user_message(user_msg_content) | |
| memory.add_ai_message(response.content) | |
| log_interaction_cloud(user_id, latest_user_msg.content, response.content) | |
| return {**state, "messages": [response], "user_id": user_id, "current_location": new_location} | |
| graph_builder = StateGraph(CustomState) | |
| graph_builder.add_node("query_or_respond", query_or_respond) | |
| graph_builder.set_entry_point("query_or_respond") | |
| graph_builder.add_edge("query_or_respond", END) | |
| graph = graph_builder.compile() | |