talk2map-prod / Talk2Map_API_Documentation.md
Noel-Teens's picture
testing workflow
622b3c4
|
Raw History Blame Contribute Delete
11 kB
# 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.