File size: 5,960 Bytes
bfa95ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# app.py
from __future__ import annotations

import json
import re
from typing import List, Optional

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse
import uvicorn

from agent.agent_runner import run_agent
from agent.models import (
    LatLon,
    BoundingBox,
    Place,
    AgentReply,
    Turn,
    ChatRequest,
    ChatResponse,
)

app = FastAPI(title="Talk2Map API", version="1.0.0")
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

def _sanitize_text(s: Optional[str]) -> str:
    if not s:
        return ""
    s = re.sub(r"<\|header_start\|>.*?<\|header_end\|>", "", s, flags=re.S | re.I)
    s = re.sub(r"<\|im_start\|>.*?<\|im_end\|>", "", s, flags=re.S | re.I)
    s = re.sub(r"<\|[^>]*\|>", "", s)
    return s.strip()

def _looks_like_tool_json(s: Optional[str]) -> bool:
    if not s or not isinstance(s, str):
        return False
    s = s.strip()
    if not s or s[0] not in "[{":
        return False
    try:
        obj = json.loads(s)
        return isinstance(obj, list) and (len(obj) == 0 or isinstance(obj[0], dict))
    except Exception:
        return False

def _tool_json_to_places(raw_json: Optional[str]) -> List[Place]:
    if not raw_json:
        return []
    try:
        data = json.loads(raw_json)
    except Exception:
        return []
    if not isinstance(data, list):
        return []
    out: List[Place] = []
    for p in data:
        vp = p.get("viewport") or {}
        low = vp.get("low") or {}
        high = vp.get("high") or {}
        out.append(
            Place(
                name=p.get("name"),
                address=p.get("address"),
                latitude=p.get("lat"),
                longitude=p.get("lng"),
                bounding_box=(
                    BoundingBox(
                        north_east=LatLon(lat=high.get("latitude"), lon=high.get("longitude")),
                        south_west=LatLon(lat=low.get("latitude"), lon=low.get("longitude")),
                    )
                    if vp
                    else None
                ),
                rating=p.get("rating"),
                user_rating_count=p.get("userRatingCount"),
                maps_url=p.get("mapsUrl"),
            )
        )
    return out

def _fmt_places_md(places: List[Place]) -> str:
    lines = []
    for i, p in enumerate(places, 1):
        rating = f" (Rating ★ {p.rating}, Reviews {p.user_rating_count})" if p.rating is not None else ""
        url = f" — {p.maps_url}" if p.maps_url else ""
        latlng = f"\nlat,lng: {p.latitude},{p.longitude}"
        box = ""
        if p.bounding_box and p.bounding_box.north_east and p.bounding_box.south_west:
            ne, sw = p.bounding_box.north_east, p.bounding_box.south_west
            box = f"\nSW: ({sw.lat}, {sw.lon}), NE: ({ne.lat}, {ne.lon})"
        lines.append(f"{i}. {p.name} — {p.address}{rating}{url}{latlng}{box}")
    return "\n".join(lines)

@app.post("/chat", response_model=ChatResponse)
def chat(req: ChatRequest) -> ChatResponse:
    lc_history = []
    for t in (req.conversation_history or [])[-8:]:
        if t.human:
            lc_history.append({"type": "human", "content": str(t.human)[:2000]})
        if t.ai is not None:
            ai_text = t.ai["message"] if isinstance(t.ai, dict) and "message" in t.ai else str(t.ai)
            lc_history.append({"type": "ai", "content": ai_text[:2000]})

    bbox = None
    if req.bounding_box and req.bounding_box.north_east and req.bounding_box.south_west:
        bbox = {
            "north_east": {"lat": req.bounding_box.north_east.lat, "lon": req.bounding_box.north_east.lon},
            "south_west": {"lat": req.bounding_box.south_west.lat, "lon": req.bounding_box.south_west.lon},
        }

    result = run_agent(req.user_input or "", lc_history, bbox=bbox)

    message_text = result.get("final_text") or ""
    last_tool_json = result.get("last_tool_json")

    if _looks_like_tool_json(message_text):
        last_tool_json = message_text
        message_text = ""

    places = _tool_json_to_places(last_tool_json)

    if not message_text and places:
        message_text = _fmt_places_md(places)

    # Provide more contextual fallback message
    if not message_text:
        if bbox and req.user_input:
            message_text = f"No {req.user_input} found in the specified area. This area might not have any {req.user_input} or try expanding the search boundary."
        elif bbox:
            message_text = "No places found in the specified area. Try expanding the search boundary or searching in a different location."
        elif req.user_input:
            message_text = f"No {req.user_input} found in this region. This area might not have any {req.user_input} or try searching in a nearby city."
        else:
            message_text = "I couldn't find anything for that request."
    
    message_text = _sanitize_text(message_text)

    agent_reply = AgentReply(message=message_text, places=places)
    updated_history: List[Turn] = list(req.conversation_history or [])
    updated_history.append(Turn(human=req.user_input or "", ai=agent_reply.model_dump()))

    return ChatResponse(agent_reply=agent_reply, conversation_history=updated_history)

@app.get("/", response_class=HTMLResponse)
def index():
    try:
        with open("api/static/index.html", "r", encoding="utf-8") as f:
            return f.read()
    except Exception:
        return HTMLResponse(
            "<!doctype html><html><head><meta charset='utf-8'><title>Talk2Map</title></head>"
            "<body><h1>Talk2Map API</h1><p>POST to <code>/chat</code> to use the assistant.</p></body></html>"
        )

@app.get("/health")
def health():
    return {"status": "ok"}

if __name__ == "__main__":
    uvicorn.run("app:app", host="127.0.0.1", port=8000, reload=True)