# agent_runner.py import json import logging from typing import Any, Dict, List, Optional, Union from pydantic import BaseModel, Field from langchain_core.messages import SystemMessage, HumanMessage, AIMessage, BaseMessage from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder from .llm import get_llm from .maptool import search_places_tool # Tool object (LangChain) logging.basicConfig(level=logging.INFO) log = logging.getLogger("agent.runner") SYSTEM_PROMPT = """You are Talk2Map — a concise trip & local-search assistant. THINK PRIVATELY: - First, silently decide whether a places search is truly needed. - Normalize the query (strip proximity phrases like "near me/nearby/around here/close by/in my area"). - If user provided a bounding box via the API, prefer using it as a hard filter. Never alter or invent coordinates. - Choose sane defaults: top_n=5 (clamp 1–20), region_code="IN", language_code="en". - If the request is not a place search (greetings, self-questions, general knowledge), DO NOT call any tool. CONVERSATION AWARENESS (no external memory; rely only on history in this chat): - If the user previously told you their name in this conversation, you may use it. - If they ask “what is my name?” and the name is not in the visible history context, say you’re not sure. PLANNING OUTPUT (JSON ONLY): Return a single JSON object with keys: { "should_call_tool": boolean, "normalized_query": string | null, "top_n": number | null, "region_code": string | null, "language_code": string | null, "strict": boolean | null, "require_viewport_fit": boolean | null, "use_bbox_from_api": boolean | null, "clarification": string | null } RULES: - If you don't need to call the tool, set should_call_tool=false and put the concise reply in "clarification". - If you call the tool, keep explanation out of the plan; the final message will be composed separately. - Do NOT include your chain-of-thought or any extra keys. """ PLANNER_PROMPT = ChatPromptTemplate.from_messages( [ SystemMessage(content=SYSTEM_PROMPT), MessagesPlaceholder(variable_name="history"), # ← critical: model sees prior turns ("human", "User says: {user_text}\n\n" "Context:\n- bounding_box_available: {bbox_available}\n" "- We already have the exact bounding box from API if available.\n\n" "Return ONLY the JSON plan described above."), ] ) class Plan(BaseModel): should_call_tool: bool normalized_query: Optional[str] = None top_n: Optional[int] = Field(default=5, ge=1, le=20) region_code: Optional[str] = "IN" language_code: Optional[str] = "en" strict: Optional[bool] = True require_viewport_fit: Optional[bool] = False use_bbox_from_api: Optional[bool] = True clarification: Optional[str] = None def _coerce_json(s: str) -> Optional[Dict[str, Any]]: if not s: return None raw = s.strip() if raw.startswith("```"): raw = raw.strip("`") parts = raw.split("\n", 1) raw = parts[1] if len(parts) > 1 and not parts[0].lstrip().startswith("{") else raw start = raw.find("{") end = raw.rfind("}") if start == -1 or end == -1 or end <= start: return None try: return json.loads(raw[start : end + 1]) except Exception: return None def _format_error_message(e: Exception, query: str = "", has_bbox: bool = False) -> str: log.exception("Agent error: %s", e) # More specific error messages based on context if has_bbox and query: return f"No {query} found in the specified area. This area might not have any {query} or try expanding the search boundary." elif has_bbox: return "No places found in the specified area. Try expanding the search boundary or searching in a different location." elif query: return f"No {query} found in this region. This area might not have any {query} or try searching in a nearby city." else: return "No matching places found. Try widening the area or share a clearer query." def _coerce_history(history_msgs: Optional[List]) -> List[BaseMessage]: """ Accepts: - List[BaseMessage] - List[{'role': 'user'|'assistant'|'system', 'content': str}] - List[('user'|'assistant'|'system', str)] """ if not history_msgs: return [] out: List[BaseMessage] = [] for m in history_msgs: if isinstance(m, BaseMessage): out.append(m) continue role, content = None, None if isinstance(m, dict): role, content = m.get("role"), m.get("content") elif isinstance(m, tuple) and len(m) >= 2: role, content = m[0], m[1] if not content: continue role = (role or "").lower() if role in ("user", "human"): out.append(HumanMessage(content=str(content))) elif role in ("assistant", "ai", "bot"): out.append(AIMessage(content=str(content))) elif role == "system": out.append(SystemMessage(content=str(content))) else: out.append(HumanMessage(content=str(content))) return out def run_agent( user_input: str, history_msgs: List, bbox: Optional[Dict[str, Dict[str, float]]] = None, *, enable_name_hint: bool = False, # keep False to test pure LLM recall name_hint_value: Optional[str] = None, # optional external memory if you ever want it ) -> Dict[str, Optional[str]]: """ Planner → (optional) tool → return {final_text, last_tool_json} - final_text: concise message (may be empty; caller can auto-format places) - last_tool_json: raw JSON string from search tool (if any) Memory policy: - By default, we pass only the conversation history. No hard-coded name or external hint. - If enable_name_hint=True and name_hint_value is provided by YOUR app, we add a small system memory line. """ llm = get_llm(temperature=0.15, max_tokens=1024) coerced_history = _coerce_history(history_msgs) # Optional: app-managed sticky memory (off by default) if enable_name_hint and name_hint_value: coerced_history = [ SystemMessage(content=f"Memory: The user's name is {name_hint_value}.") ] + coerced_history # 1) PLAN try: plan_text = (PLANNER_PROMPT | llm).invoke( { "history": coerced_history, "user_text": (user_input or "").strip(), "bbox_available": bool(bbox), } ) plan_obj = plan_text.content if hasattr(plan_text, "content") else str(plan_text) plan_dict = _coerce_json(plan_obj) or {} plan = Plan(**plan_dict) except Exception as e: log.exception("Planner LLM failed; falling back. %s", e) plan = Plan( should_call_tool=False, clarification="Please share a city or a map bounding box to search inside.", ) # 2) Decide action if not plan.should_call_tool: msg = (plan.clarification or "Please share a city or a map bounding box to search inside.").strip() return {"final_text": msg, "last_tool_json": None} # 3) Normalize params query = (plan.normalized_query or "").strip() if not query: return { "final_text": "I need a category or search text (e.g., “school”, “cafe”).", "last_tool_json": None, } top_n = max(1, min(20, int(plan.top_n or 5))) region_code = (plan.region_code or "IN").strip() language_code = (plan.language_code or "en").strip() strict = bool(plan.strict if plan.strict is not None else True) require_viewport_fit = bool(plan.require_viewport_fit) tool_bbox = bbox if (plan.use_bbox_from_api and bbox) else None # 4) Tool call try: raw = search_places_tool.invoke( { "query": query, "top_n": top_n, "region_code": region_code, "language_code": language_code, "bounding_box": tool_bbox, "strict": strict, "require_viewport_fit": require_viewport_fit, } ) if not isinstance(raw, str): raw = json.dumps(raw, ensure_ascii=False) # Check if the tool returned empty results try: parsed_results = json.loads(raw) if raw else [] if isinstance(parsed_results, list) and len(parsed_results) == 0: # No places found - return contextual message has_bbox = bool(tool_bbox) error_msg = _format_error_message(Exception("No results"), query, has_bbox) return {"final_text": error_msg, "last_tool_json": raw} except json.JSONDecodeError: pass # If we can't parse, just return the raw result return {"final_text": "", "last_tool_json": raw} except Exception as e: has_bbox = bool(tool_bbox) return {"final_text": _format_error_message(e, query, has_bbox), "last_tool_json": None}