Spaces:
Sleeping
Sleeping
File size: 9,159 Bytes
622b3c4 | 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 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 | # 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}
|