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
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423

# Talk2Map (MapMate) API — Full Documentation

_Last updated: 2025-08-29 12:48 _

This document describes the public HTTP API for **Talk2Map (MapMate)** — a chat + places service that blends a natural‑language agent with Google Places lookups. It includes request/response formats, schemas, examples, and implementation notes.

> **Key behavior**: If a request contains **only** a `bounding_box` and **empty** `user_input`, the backend **skips the LLM agent** and queries Google Places **directly** (via `maptool.py`). The response still returns a user‑friendly `message` and a structured `places` list in `agent_reply`.

---

## Base URL

- Local development: `http://localhost:8000`  
- All examples below use a Postman variable `{baseUrl}` that defaults to `http://localhost:8000`.

CORS is enabled broadly for development (`*`).

---

## Authentication

None required for local development. Google Places API credentials are read from the server environment (`PLACES_API_KEY`).

---

## Version

- API: `v1.0.0` (FastAPI title: **Talk2Map API**)

---

## Endpoints

### 1) Health

**GET** `{baseUrl}/health`

Simple health check.

**Response**
```json
{ "status": "ok" }
```

**cURL**
```bash
curl -s {baseUrl}/health
```

---

### 2) Chat

**POST** `{baseUrl}/chat`

Drives the conversation flow. Depending on input, the server either:
1) Runs the LLM agent with tools **(normal path)**, or
2) If **only** a `bounding_box` is provided (and `user_input` is empty/whitespace), **skips the agent** and queries Google Places **directly** via `maptool.py` **(bbox‑only path)**.

#### Headers

- `Content-Type: application/json`
- _Optional_ for bbox-only: `X-Top-N: <int>` — a client hint for maximum results (server may cap/ignore).

#### Request Body — Schema

```ts
interface LatLon { lat?: number; lon?: number; }

interface BoundingBox {
  north_east?: LatLon;
  south_west?: LatLon;
}

interface Turn {
  human: string;
  ai?: string | Record<string, any>;
}

interface ChatRequest {
  user_input: string;                // free-text user message (may be empty in bbox-only flow)
  conversation_history?: Turn[];     // prior chat turns (optional)
  bounding_box?: BoundingBox;        // when present (and user_input empty) triggers bbox-only places lookup
}
```

#### Response Body — Schema

```ts
interface Place {
  name?: string;
  address?: string;
  latitude?: number;
  longitude?: number;
  bounding_box?: {
    north_east?: LatLon;
    south_west?: LatLon;
  };
  rating?: number;
  user_rating_count?: number;
  maps_url?: string;
}

interface AgentReply {
  message: string;  // user-friendly text, may include Markdown
  places: Place[];  // structured places (may be empty list)
}

interface ChatResponse {
  agent_reply: AgentReply;
  conversation_history: Turn[];  // the server-augmented history (source of truth)
}
```

> The `message` field is always present and is suitable for Markdown rendering. The `places` array is filled when a Places search is executed, either by the agent or directly in bbox‑only mode.

---

## Usage Patterns & Examples

### A) Normal Agent Call with Places (e.g., “best 2 hotels in Chennai”)

**Request**
```http
POST {baseUrl}/chat
Content-Type: application/json

{
  "user_input": "best 2 hotel in chennai",
  "conversation_history": [
    {"human": "hello", "ai": "hello sir"}
  ]
}
```

**Response (example)** — contains a Markdown `message` and a structured `places` array (2 hotels).
```json
{
  "agent_reply": {
    "message": "1. ITC Grand Chola...",
    "places": [ { "...": "see schema above" } ]
  },
  "conversation_history": [ /* prior + this turn */ ]
}
```

**cURL**
```bash
curl -s -X POST {baseUrl}/chat   -H "Content-Type: application/json"   -d '{
    "user_input": "best 2 hotel in chennai",
    "conversation_history": [{"human":"hello","ai":"hello sir"}]
  }'
```

---

### B) General Knowledge (no Places)

**Request**
```http
POST {baseUrl}/chat
Content-Type: application/json

{
  "user_input": "What is the capital of India?",
  "conversation_history": [
    {"human": "hello", "ai": "hello sir"}
  ]
}
```

**Response (example)** — `places` is an empty list.
```json
{
  "agent_reply": { "message": "The capital of India is New Delhi.", "places": [] },
  "conversation_history": [ /* prior + this turn */ ]
}
```

**cURL**
```bash
curl -s -X POST {baseUrl}/chat   -H "Content-Type: application/json"   -d '{
    "user_input":"What is the capital of India?",
    "conversation_history":[{"human":"hello","ai":"hello sir"}]
  }'
```

---

### C) Contextual Follow-up: Lat/Lng for a Place mentioned earlier

**Request**
```http
POST {baseUrl}/chat
Content-Type: application/json

{
  "user_input": "give me the lat and lan of ITC Grand Chola",
  "conversation_history": [
    { "human": "hello", "ai": "hello sir" },
    { "human": "best 2 hotel in chennai", "ai": { "message": "...", "places": [ /* two hotels */ ] } }
  ]
}
```

**Response (example)** — agent uses context to answer succinctly; may include a 1‑element `places` for the matched item.
```json
{
  "agent_reply": {
    "message": "lat,lng: 13.010613, 80.2206015",
    "places": [ { "...": "place details" } ]
  },
  "conversation_history": [ /* prior + this turn */ ]
}
```

**cURL**
```bash
curl -s -X POST {baseUrl}/chat   -H "Content-Type: application/json"   -d '{
    "user_input":"give me the lat and lan of ITC Grand Chola",
    "conversation_history":[
      {"human":"hello","ai":"hello sir"},
      {"human":"best 2 hotel in chennai","ai":{"message":"...","places":[/*...*/]}}
    ]
  }'
```

---

### D) Bounding Box Only — Places via `maptool.py` (Agent Skipped)

**Behavior**: If `user_input` is empty/whitespace **and** `bounding_box` is present, the server **bypasses** the agent and directly queries Google Places with a rectangle `locationBias`. The server constructs a friendly `message` listing results and returns the full list in `places`.

**Request**
```http
POST {baseUrl}/chat
Content-Type: application/json
X-Top-N: 10   # optional hint

{
  "user_input": "",
  "conversation_history": [],
  "bounding_box": {
    "north_east": { "lat": 13.011865130291502, "lon": 80.2222132802915 },
    "south_west": { "lat": 13.009167169708498, "lon": 80.21951531970849 }
  }
}
```

**Response (example)**
```json
{
  "agent_reply": {
    "message": "Here are notable places in the selected area (NE: 13.011865, 80.222213 | SW: 13.009167, 80.219515):\n1. ...",
    "places": [ { "...": "see schema" } ]
  },
  "conversation_history": [
    { "human": "", "ai": { "message": "Here are notable places...", "places": [ /* ... */ ] } }
  ]
}
```

**cURL**
```bash
curl -s -X POST {baseUrl}/chat   -H "Content-Type: application/json"   -H "X-Top-N: 10"   -d '{
    "user_input": "",
    "conversation_history": [],
    "bounding_box": {
      "north_east": { "lat": 13.011865130291502, "lon": 80.2222132802915 },
      "south_west": { "lat": 13.009167169708498, "lon": 80.21951531970849 }
    }
  }'
```

---

## Data Models (Server-side)

### Pydantic Models (`agent/models.py`)

```py
class LLMMessage(BaseModel):
    message: str  # final markdown text

class LatLon(BaseModel):
    lat: Optional[float] = None
    lon: Optional[float] = None

class BoundingBox(BaseModel):
    north_east: Optional[LatLon] = None
    south_west: Optional[LatLon] = None

class Place(BaseModel):
    name: Optional[str] = None
    address: Optional[str] = None
    latitude: Optional[float] = None
    longitude: Optional[float] = None
    bounding_box: Optional[BoundingBox] = None
    rating: Optional[float] = None
    user_rating_count: Optional[int] = None
    maps_url: Optional[str] = None

class AgentReply(BaseModel):
    message: str
    places: List[Place] = Field(default_factory=list)

class Turn(BaseModel):
    human: str
    ai: Optional[Union[str, Dict[str, Any]]] = None

class ChatRequest(BaseModel):
    user_input: str
    conversation_history: List[Turn] = Field(default_factory=list)
    bounding_box: Optional[BoundingBox] = None

class ChatResponse(BaseModel):
    agent_reply: AgentReply
    conversation_history: List[Turn]
```

---

## Google Places Integration

- **Endpoint used** (server-to-Google): `https://places.googleapis.com/v1/places:searchText`
- **Headers**: `X-Goog-Api-Key: $PLACES_API_KEY`, `X-Goog-FieldMask: places.displayName, ..., nextPageToken`
- **Default query** for bbox-only: `"points of interest"` (configurable)
- **locationBias rectangle** is built from the provided `bounding_box`:
  ```json
  {
    "locationBias": {
      "rectangle": {
        "low": { "latitude": SW.lat, "longitude": SW.lon },
        "high": { "latitude": NE.lat, "longitude": NE.lon }
      }
    }
  }
  ```
- Pagination via `nextPageToken` is handled internally until `top_n` results or no more pages.

Returned place fields are mapped to the API’s `Place` schema.

---

## Status Codes

- `200 OK` — Successful response.
- `400 Bad Request` — Invalid JSON / missing required fields / invalid bbox shape.
- `500 Internal Server Error` — Uncaught server error (including upstream Places errors).

On Places errors, the server raises a 5xx with the upstream message included for debugging.

---

## Headers & Conventions

- `Content-Type: application/json` for all POSTs.
- Optional `X-Top-N` for bbox-only calls (hint only).
- Responses use UTF‑8 and may contain Markdown in `agent_reply.message`.

---

## Rate Limiting & Quotas

- No server-side rate limiter in this reference implementation.
- Upstream Google Places usage is limited by your `PLACES_API_KEY` quota.

---

## Error Examples

**Invalid bbox values**
```json
{ "detail": "SW.lat must be <= NE.lat; SW.lon must be <= NE.lon" }
```

**Places API error**
```json
{ "detail": "Places API error 403: {\"error\": {\"message\": \"API key not valid\"}}" }
```

---

## Environment Variables

- `PLACES_API_KEY` _(required)_: Google Places (Places API v1) key.
- Optional `.env` usage is supported by `dotenv` for local development.

---

## Postman

A ready-to-import Postman collection is available:

- **[Talk2Map.postman_collection.json](sandbox:/mnt/data/Talk2Map.postman_collection.json)**

Import it into Postman and set `{baseUrl}` as needed.

---

## Changelog

- **v1.0.0**
  - Added **bbox-only** flow: if `bounding_box` present and `user_input` empty → **skip agent**, query Google Places directly.
  - Unified response shape via `agent_reply: { message, places }`.
  - Documented schemas and examples for all common flows.

---

## Notes for Frontend Integrators

- Render `agent_reply.message` as **Markdown** (sanitize HTML).
- Show `agent_reply.places` in a card list; each card can link to `maps_url` or a `https://www.google.com/maps?q=lat,lng` fallback.
- For bbox-only UX, collect `NE` and `SW` coordinates and submit with empty `user_input`.
- The sample UI adds a **Bounding Box Search** form that triggers the bbox-only flow.

---

## License

This API documentation is provided as-is for internal integration and testing.