Noel-Teens commited on
Commit
bfa95ad
·
0 Parent(s):

testing new workflow

Browse files
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
.github/config/newman.env ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Newman Test Configuration
2
+ # This file contains configuration for running Newman tests
3
+
4
+ # Test timeouts (in milliseconds)
5
+ REQUEST_TIMEOUT=30000
6
+ SCRIPT_TIMEOUT=10000
7
+
8
+ # Delay between requests (in milliseconds)
9
+ REQUEST_DELAY=2000
10
+
11
+ # Retry configuration
12
+ MAX_RETRIES=3
13
+ RETRY_DELAY=5
14
+
15
+ # HuggingFace deployment wait time (in seconds)
16
+ HF_DEPLOYMENT_WAIT=120
17
+
18
+ # API health check configuration
19
+ HEALTH_CHECK_MAX_ATTEMPTS=10
20
+ HEALTH_CHECK_RETRY_DELAY=30
21
+
22
+ # Test environment URLs
23
+ TEST_ENVIRONMENT_URL=https://neurostack-in-talk2map-test.hf.space
24
+ PRODUCTION_ENVIRONMENT_URL=https://neurostack-in-talk2map-prod.hf.space
25
+
26
+ # Test coverage requirements
27
+ MINIMUM_PASS_RATE=80
28
+
29
+ # Report configuration
30
+ GENERATE_HTML_REPORT=true
31
+ GENERATE_JSON_REPORT=true
32
+ REPORT_RETENTION_DAYS=30
.github/scripts/validate-postman.sh ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Postman Collection Validator
4
+ # This script validates the Talk2Map Postman collection before running tests
5
+
6
+ echo "🔍 Validating Postman collection..."
7
+
8
+ # Check if collection file exists
9
+ if [ ! -f "Talk2Map.postman_collection.json" ]; then
10
+ echo "❌ Postman collection file not found!"
11
+ exit 1
12
+ fi
13
+
14
+ # Check if collection is valid JSON
15
+ if ! jq empty Talk2Map.postman_collection.json 2>/dev/null; then
16
+ echo "❌ Invalid JSON in Postman collection!"
17
+ exit 1
18
+ fi
19
+
20
+ # Extract collection info
21
+ collection_name=$(jq -r '.info.name' Talk2Map.postman_collection.json)
22
+ echo "✅ Collection: $collection_name"
23
+
24
+ # Count requests
25
+ request_count=$(jq '[.item[].request] | length' Talk2Map.postman_collection.json)
26
+ echo "✅ Total requests: $request_count"
27
+
28
+ # List all request names
29
+ echo "📋 Available endpoints:"
30
+ jq -r '.item[].name' Talk2Map.postman_collection.json | sed 's/^/ - /'
31
+
32
+ # Check for required variables
33
+ if jq -e '.variable[] | select(.key=="baseUrl")' Talk2Map.postman_collection.json > /dev/null; then
34
+ default_url=$(jq -r '.variable[] | select(.key=="baseUrl") | .value' Talk2Map.postman_collection.json)
35
+ echo "✅ Base URL variable found (default: $default_url)"
36
+ else
37
+ echo "⚠️ No baseUrl variable found in collection"
38
+ fi
39
+
40
+ # Validate bounding_box requirements for Talk2Map API
41
+ echo "🔍 Checking bounding_box requirements..."
42
+ missing_bbox_count=0
43
+
44
+ # Check each request for bounding_box field (excluding health check)
45
+ for i in $(jq '.item | to_entries[] | select(.value.name != "Health") | .key' Talk2Map.postman_collection.json); do
46
+ request_name=$(jq -r ".item[$i].name" Talk2Map.postman_collection.json)
47
+
48
+ # Only check the main request body (not originalRequest in responses)
49
+ if jq -e ".item[$i].request.body.raw" Talk2Map.postman_collection.json > /dev/null; then
50
+ raw_body=$(jq -r ".item[$i].request.body.raw" Talk2Map.postman_collection.json)
51
+
52
+ # Parse the raw JSON body and check for bounding_box
53
+ if echo "$raw_body" | jq -e '.bounding_box' > /dev/null 2>&1; then
54
+ echo "✅ Has bounding_box: $request_name"
55
+ else
56
+ echo "❌ Missing bounding_box in: $request_name"
57
+ echo " Raw body preview: $(echo "$raw_body" | head -c 100)..."
58
+ ((missing_bbox_count++))
59
+ fi
60
+ else
61
+ echo "⚠️ No request body found for: $request_name"
62
+ fi
63
+ done
64
+
65
+ if [ $missing_bbox_count -gt 0 ]; then
66
+ echo "❌ $missing_bbox_count requests missing required bounding_box field!"
67
+ echo "Talk2Map API requires bounding_box for all /chat endpoints."
68
+ exit 1
69
+ fi
70
+
71
+ echo "✅ All requests have required bounding_box field!"
72
+ echo "✅ Postman collection validation complete!"
.github/workflows/api-testing.yml ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: API Endpoint Testing
2
+
3
+ on:
4
+ workflow_run:
5
+ workflows: ["Staging Branch CI"]
6
+ types:
7
+ - completed
8
+ branches:
9
+ - staging
10
+ workflow_dispatch:
11
+ inputs:
12
+ base_url:
13
+ description: 'Base URL for API testing'
14
+ required: false
15
+ default: 'https://neurostack-in-talk2map-test.hf.space'
16
+ wait_time:
17
+ description: 'Wait time in seconds before testing (for HF deployment)'
18
+ required: false
19
+ default: '120'
20
+ environment:
21
+ description: 'Environment to test (test/production)'
22
+ required: false
23
+ default: 'test'
24
+ type: choice
25
+ options:
26
+ - test
27
+ - production
28
+
29
+ permissions:
30
+ contents: read
31
+ issues: write
32
+ pull-requests: write
33
+
34
+ jobs:
35
+ api-testing:
36
+ runs-on: ubuntu-latest
37
+ if: ${{ github.event.workflow_run.conclusion == 'success' || github.event_name == 'workflow_dispatch' }}
38
+
39
+ steps:
40
+ - name: Checkout code
41
+ uses: actions/checkout@v4
42
+
43
+ - name: Set environment variables
44
+ run: |
45
+ if [ "${{ github.event.inputs.environment }}" = "production" ]; then
46
+ echo "BASE_URL=https://neurostack-in-talk2map-prod.hf.space" >> $GITHUB_ENV
47
+ echo "ENVIRONMENT=production" >> $GITHUB_ENV
48
+ echo "WAIT_TIME=60" >> $GITHUB_ENV
49
+ else
50
+ echo "BASE_URL=${{ github.event.inputs.base_url || 'https://neurostack-in-talk2map-test.hf.space' }}" >> $GITHUB_ENV
51
+ echo "ENVIRONMENT=test" >> $GITHUB_ENV
52
+ echo "WAIT_TIME=${{ github.event.inputs.wait_time || '120' }}" >> $GITHUB_ENV
53
+ fi
54
+
55
+ echo "Testing environment: $ENVIRONMENT"
56
+ echo "Target URL: $BASE_URL"
57
+
58
+ - name: Set up Node.js
59
+ uses: actions/setup-node@v4
60
+ with:
61
+ node-version: '18'
62
+
63
+ - name: Install Newman (Postman CLI)
64
+ run: npm install -g newman newman-reporter-htmlextra
65
+
66
+ - name: Validate Postman Collection
67
+ run: |
68
+ # Install jq for JSON parsing
69
+ sudo apt-get update && sudo apt-get install -y jq
70
+
71
+ # Make validation script executable and run it
72
+ chmod +x .github/scripts/validate-postman.sh
73
+ ./.github/scripts/validate-postman.sh
74
+
75
+ - name: Wait for HuggingFace deployment
76
+ run: |
77
+ echo "Waiting $WAIT_TIME seconds for HuggingFace deployment to be ready..."
78
+ sleep $WAIT_TIME
79
+
80
+ echo "Checking if API is accessible at $BASE_URL..."
81
+ # Try to reach the health endpoint with retries
82
+ for i in {1..10}; do
83
+ if curl -f -s "$BASE_URL/health" > /dev/null; then
84
+ echo "✅ API is accessible at $BASE_URL"
85
+ break
86
+ else
87
+ echo "⏳ Attempt $i: API not ready yet, waiting 30 seconds..."
88
+ sleep 30
89
+ fi
90
+
91
+ if [ $i -eq 10 ]; then
92
+ echo "❌ API is not accessible after 10 attempts"
93
+ exit 1
94
+ fi
95
+ done
96
+
97
+ - name: Prepare Postman environment
98
+ run: |
99
+ # Create Newman environment file with dynamic base URL
100
+ cat > newman-environment.json << EOF
101
+ {
102
+ "id": "talk2map-$ENVIRONMENT-env",
103
+ "name": "Talk2Map $ENVIRONMENT Environment",
104
+ "values": [
105
+ {
106
+ "key": "baseUrl",
107
+ "value": "$BASE_URL",
108
+ "enabled": true
109
+ }
110
+ ]
111
+ }
112
+ EOF
113
+
114
+ echo "Created environment file with baseUrl: $BASE_URL"
115
+
116
+ - name: Run API Tests with Newman
117
+ id: run-tests
118
+ env:
119
+ GROQ_API_KEY: ${{ secrets.GROQ_API_KEY }}
120
+ run: |
121
+ echo "🚀 Starting API endpoint testing for $ENVIRONMENT environment..."
122
+
123
+ # Run Newman with HTML reporter and better error handling
124
+ newman run Talk2Map.postman_collection.json \
125
+ --environment newman-environment.json \
126
+ --reporters cli,htmlextra \
127
+ --reporter-htmlextra-export api-test-report-$ENVIRONMENT.html \
128
+ --reporter-htmlextra-title "Talk2Map API Test Report - $ENVIRONMENT" \
129
+ --timeout-request 30000 \
130
+ --timeout-script 10000 \
131
+ --delay-request 3000 \
132
+ --verbose \
133
+ --bail \
134
+ && echo "test_status=success" >> $GITHUB_OUTPUT \
135
+ || echo "test_status=failure" >> $GITHUB_OUTPUT
136
+
137
+ - name: Upload Test Report
138
+ uses: actions/upload-artifact@v4
139
+ if: always()
140
+ with:
141
+ name: api-test-report-${{ env.ENVIRONMENT }}
142
+ path: api-test-report-${{ env.ENVIRONMENT }}.html
143
+ retention-days: 30
144
+
145
+ - name: Create Test Summary
146
+ if: always()
147
+ run: |
148
+ echo "## 🧪 API Test Results - $ENVIRONMENT Environment" >> $GITHUB_STEP_SUMMARY
149
+ echo "" >> $GITHUB_STEP_SUMMARY
150
+ echo "**Test Environment:** $ENVIRONMENT" >> $GITHUB_STEP_SUMMARY
151
+ echo "**Target URL:** $BASE_URL" >> $GITHUB_STEP_SUMMARY
152
+ echo "**Test Status:** ${{ steps.run-tests.outputs.test_status }}" >> $GITHUB_STEP_SUMMARY
153
+ echo "" >> $GITHUB_STEP_SUMMARY
154
+
155
+ if [ -f "api-test-report-$ENVIRONMENT.html" ]; then
156
+ echo "✅ **Test report generated successfully**" >> $GITHUB_STEP_SUMMARY
157
+ echo "" >> $GITHUB_STEP_SUMMARY
158
+ echo "📈 **Download the detailed HTML report from the Artifacts section above**" >> $GITHUB_STEP_SUMMARY
159
+ else
160
+ echo "❌ **Test report generation failed**" >> $GITHUB_STEP_SUMMARY
161
+ fi
162
+
163
+ echo "" >> $GITHUB_STEP_SUMMARY
164
+ echo "### Test Endpoints Covered:" >> $GITHUB_STEP_SUMMARY
165
+ echo "- 🏥 Health Check" >> $GITHUB_STEP_SUMMARY
166
+ echo "- 🏨 Chat with Places (Hotels in Chennai)" >> $GITHUB_STEP_SUMMARY
167
+ echo "- 💬 Chat without Places (General Knowledge)" >> $GITHUB_STEP_SUMMARY
168
+ echo "- 📍 Contextual Lat/Lng Query" >> $GITHUB_STEP_SUMMARY
169
+ echo "- 🗺️ Bounding Box Only Query" >> $GITHUB_STEP_SUMMARY
170
+
171
+ - name: Health Check Verification
172
+ run: |
173
+ echo "🔍 Final health check verification..."
174
+
175
+ response=$(curl -s -w "HTTP_STATUS:%{http_code}" "$BASE_URL/health")
176
+ http_status=$(echo $response | grep -o "HTTP_STATUS:[0-9]*" | cut -d: -f2)
177
+ body=$(echo $response | sed 's/HTTP_STATUS:[0-9]*$//')
178
+
179
+ if [ "$http_status" = "200" ]; then
180
+ echo "✅ Health check passed - API is healthy"
181
+ echo "Response: $body"
182
+ else
183
+ echo "❌ Health check failed - HTTP Status: $http_status"
184
+ echo "Response: $body"
185
+ exit 1
186
+ fi
187
+
188
+ - name: Create test success notification
189
+ if: steps.run-tests.outputs.test_status == 'success'
190
+ uses: actions/github-script@v7
191
+ with:
192
+ script: |
193
+ const title = `✅ API Tests Passed - ${{ env.ENVIRONMENT }} Environment`;
194
+ const body = `## API Testing Successful
195
+
196
+ **Environment:** \`${{ env.ENVIRONMENT }}\`
197
+ **Target URL:** ${{ env.BASE_URL }}
198
+ **Commit:** ${context.sha}
199
+
200
+ ### Test Results:
201
+ - ✅ All API endpoints responded correctly
202
+ - ✅ Health check passed
203
+ - ✅ Chat functionality verified
204
+ - ✅ Bounding box queries working
205
+
206
+ ### Test Coverage:
207
+ - Health Check endpoint
208
+ - Chat with Places (Hotels in Chennai)
209
+ - Chat without Places (General Knowledge)
210
+ - Contextual Lat/Lng Query
211
+ - Bounding Box Only Query
212
+
213
+ **📈 Detailed test report available in workflow artifacts**`;
214
+
215
+ github.rest.issues.create({
216
+ owner: context.repo.owner,
217
+ repo: context.repo.repo,
218
+ title: title,
219
+ body: body,
220
+ labels: ['api-test-success', '${{ env.ENVIRONMENT }}']
221
+ });
222
+
223
+ - name: Create test failure alert
224
+ if: steps.run-tests.outputs.test_status == 'failure'
225
+ uses: actions/github-script@v7
226
+ with:
227
+ script: |
228
+ const title = `❌ API Tests Failed - ${{ env.ENVIRONMENT }} Environment`;
229
+ const body = `## API Testing Failed
230
+
231
+ **Environment:** \`${{ env.ENVIRONMENT }}\`
232
+ **Target URL:** ${{ env.BASE_URL }}
233
+ **Commit:** ${context.sha}
234
+ **Workflow Run:** [View Logs](${context.payload.repository.html_url}/actions/runs/${context.runId})
235
+
236
+ ### Issue:
237
+ API endpoint tests failed in the ${{ env.ENVIRONMENT }} environment.
238
+
239
+ ### Possible Causes:
240
+ - API endpoints not responding correctly
241
+ - Authentication issues (GROQ_API_KEY)
242
+ - Network connectivity problems
243
+ - Application errors in deployed code
244
+ - Test data or configuration issues
245
+
246
+ ### Action Required:
247
+ 1. Check the [workflow logs](${context.payload.repository.html_url}/actions/runs/${context.runId})
248
+ 2. Review the test report in artifacts
249
+ 3. Verify the API is accessible at ${{ env.BASE_URL }}
250
+ 4. Check for application errors or configuration issues
251
+
252
+ **⚠️ ${{ env.ENVIRONMENT }} environment may have issues - investigation required!**`;
253
+
254
+ github.rest.issues.create({
255
+ owner: context.repo.owner,
256
+ repo: context.repo.repo,
257
+ title: title,
258
+ body: body,
259
+ labels: ['api-test-failure', '${{ env.ENVIRONMENT }}', 'urgent']
260
+ });
.github/workflows/manual-feature-merge.yml ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Manual Feature Testing and Staging Merge
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ inputs:
6
+ feature_branch:
7
+ description: 'Feature branch name to test and merge'
8
+ required: true
9
+ type: string
10
+ reason:
11
+ description: 'Reason for merging to staging'
12
+ required: false
13
+ default: 'Feature ready for staging'
14
+
15
+ permissions:
16
+ contents: write
17
+ issues: write
18
+
19
+ jobs:
20
+ test-and-merge-feature:
21
+ runs-on: ubuntu-latest
22
+ steps:
23
+ - name: Checkout feature branch
24
+ uses: actions/checkout@v4
25
+ with:
26
+ ref: ${{ github.event.inputs.feature_branch }}
27
+ fetch-depth: 0
28
+ token: ${{ secrets.GITHUB_TOKEN }}
29
+
30
+ - name: Set up Python
31
+ uses: actions/setup-python@v5
32
+ with:
33
+ python-version: '3.11'
34
+
35
+ - name: Install dependencies
36
+ run: |
37
+ python -m pip install --upgrade pip
38
+ pip install -r requirements.txt
39
+
40
+ - name: Run tests on feature branch
41
+ id: test-feature
42
+ env:
43
+ GROQ_API_KEY: ${{ secrets.GROQ_API_KEY }}
44
+ run: |
45
+ echo "Running tests on feature branch: ${{ github.event.inputs.feature_branch }}"
46
+ echo "Reason: ${{ github.event.inputs.reason }}"
47
+ pytest -v
48
+ echo "✅ Feature branch tests passed!"
49
+
50
+ - name: Check for merge conflicts with staging
51
+ id: conflict-check
52
+ env:
53
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
54
+ run: |
55
+ echo "Checking for potential merge conflicts with staging..."
56
+ git fetch origin staging:staging 2>/dev/null || {
57
+ echo "staging_exists=false" >> $GITHUB_OUTPUT
58
+ echo "⚠️ Staging branch doesn't exist yet. Will create it."
59
+ exit 0
60
+ }
61
+
62
+ echo "staging_exists=true" >> $GITHUB_OUTPUT
63
+
64
+ # Try a test merge to check for conflicts
65
+ git checkout staging
66
+ git checkout ${{ github.event.inputs.feature_branch }}
67
+
68
+ if git merge-tree $(git merge-base staging ${{ github.event.inputs.feature_branch }}) staging ${{ github.event.inputs.feature_branch }} | grep -q "<<<<<<< "; then
69
+ echo "has_conflicts=true" >> $GITHUB_OUTPUT
70
+ echo "❌ Merge conflicts detected with staging branch!"
71
+
72
+ # Get conflict details
73
+ conflict_files=$(git merge-tree $(git merge-base staging ${{ github.event.inputs.feature_branch }}) staging ${{ github.event.inputs.feature_branch }} | grep "<<<<<<< " -A 10 -B 2 || echo "Unable to determine conflict details")
74
+ echo "conflict_details<<EOF" >> $GITHUB_OUTPUT
75
+ echo "$conflict_files" >> $GITHUB_OUTPUT
76
+ echo "EOF" >> $GITHUB_OUTPUT
77
+ else
78
+ echo "has_conflicts=false" >> $GITHUB_OUTPUT
79
+ echo "✅ No merge conflicts detected with staging!"
80
+ fi
81
+
82
+ - name: Merge feature to staging
83
+ if: success() && steps.test-feature.outcome == 'success' && steps.conflict-check.outputs.has_conflicts == 'false'
84
+ env:
85
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
86
+ run: |
87
+ echo "✅ Tests passed and no conflicts detected. Proceeding with merge to staging..."
88
+
89
+ git config --global user.email "github-actions[bot]@users.noreply.github.com"
90
+ git config --global user.name "github-actions[bot]"
91
+
92
+ # Fetch all branches
93
+ git fetch origin
94
+
95
+ # Handle staging branch creation or checkout
96
+ if [ "${{ steps.conflict-check.outputs.staging_exists }}" = "true" ]; then
97
+ echo "Checking out existing staging branch"
98
+ git checkout staging
99
+ git merge ${{ github.event.inputs.feature_branch }} --no-ff -m "Merge ${{ github.event.inputs.feature_branch }} to staging: ${{ github.event.inputs.reason }}"
100
+ else
101
+ echo "Creating staging branch from feature branch"
102
+ git checkout -b staging
103
+ fi
104
+
105
+ # Push to staging
106
+ git remote set-url origin https://x-access-token:${GITHUB_TOKEN}@github.com/${{ github.repository }}.git
107
+ echo "Pushing to staging branch..."
108
+ git push origin staging
109
+
110
+ echo "✅ Successfully merged ${{ github.event.inputs.feature_branch }} to staging!"
111
+ echo "🚀 This will trigger staging CI and deployment to HF test space..."
112
+
113
+ - name: Create success notification
114
+ if: success() && steps.test-feature.outcome == 'success' && steps.conflict-check.outputs.has_conflicts == 'false'
115
+ uses: actions/github-script@v7
116
+ with:
117
+ script: |
118
+ const title = `✅ Feature Merged to Staging: ${{ github.event.inputs.feature_branch }}`;
119
+ const body = `## Feature Successfully Merged to Staging
120
+
121
+ **Feature Branch:** \`${{ github.event.inputs.feature_branch }}\`
122
+ **Reason:** ${{ github.event.inputs.reason }}
123
+ **Commit:** ${context.sha}
124
+
125
+ ### Status:
126
+ - ✅ Feature tests passed
127
+ - ✅ No merge conflicts detected
128
+ - ✅ Successfully merged to staging
129
+ - 🚀 Staging CI triggered
130
+
131
+ ### Next Steps:
132
+ 1. [Staging CI workflow](${context.payload.repository.html_url}/actions) will run automatically
133
+ 2. If successful, code will be deployed to HuggingFace test space
134
+ 3. API testing will run against the test deployment
135
+ 4. When ready, use [Manual Promotion](${context.payload.repository.html_url}/actions/workflows/promote.yml) to deploy to production
136
+
137
+ **🎯 Test Environment:** https://neurostack-in-talk2map-test.hf.space`;
138
+
139
+ github.rest.issues.create({
140
+ owner: context.repo.owner,
141
+ repo: context.repo.repo,
142
+ title: title,
143
+ body: body,
144
+ labels: ['feature-merged', 'staging-updated']
145
+ });
146
+
147
+ - name: Create failure notification
148
+ if: failure() || steps.test-feature.outcome == 'failure' || steps.conflict-check.outputs.has_conflicts == 'true'
149
+ uses: actions/github-script@v7
150
+ with:
151
+ script: |
152
+ let title, body, labels;
153
+
154
+ if ('${{ steps.test-feature.outcome }}' === 'failure') {
155
+ title = `❌ Feature Tests Failed: ${{ github.event.inputs.feature_branch }}`;
156
+ body = `## Feature Branch Tests Failed - Merge Blocked
157
+
158
+ **Feature Branch:** \`${{ github.event.inputs.feature_branch }}\`
159
+ **Commit:** ${context.sha}
160
+ **Workflow Run:** [View Logs](${context.payload.repository.html_url}/actions/runs/${context.runId})
161
+
162
+ ### Issue:
163
+ Tests failed on the feature branch. **Merge to staging is blocked.**
164
+
165
+ ### Action Required:
166
+ 1. Review the [failed test logs](${context.payload.repository.html_url}/actions/runs/${context.runId})
167
+ 2. Fix the failing tests in the feature branch
168
+ 3. Run this workflow again after fixes
169
+
170
+ ### Test Command:
171
+ \`\`\`bash
172
+ pytest -v
173
+ \`\`\`
174
+
175
+ **⚠️ No merge will occur until all tests pass.**`;
176
+ labels = ['test-failure', 'merge-blocked', 'urgent'];
177
+ } else if ('${{ steps.conflict-check.outputs.has_conflicts }}' === 'true') {
178
+ title = `🚨 Merge Conflicts: ${{ github.event.inputs.feature_branch }} → staging`;
179
+ body = `## Merge Conflicts Detected - Merge Blocked
180
+
181
+ **Feature Branch:** \`${{ github.event.inputs.feature_branch }}\`
182
+ **Target Branch:** \`staging\`
183
+ **Commit:** ${context.sha}
184
+
185
+ ### Conflict Details:
186
+ \`\`\`
187
+ ${{ steps.conflict-check.outputs.conflict_details }}
188
+ \`\`\`
189
+
190
+ ### Action Required:
191
+ Merge conflicts detected. **Merge is blocked.**
192
+
193
+ ### Resolution Steps:
194
+ \`\`\`bash
195
+ git checkout ${{ github.event.inputs.feature_branch }}
196
+ git fetch origin
197
+ git merge origin/staging
198
+ # Resolve conflicts manually in your editor
199
+ git add .
200
+ git commit -m "Resolve merge conflicts with staging"
201
+ git push origin ${{ github.event.inputs.feature_branch }}
202
+ \`\`\`
203
+
204
+ **⚠️ No merge will occur until conflicts are resolved.**`;
205
+ labels = ['merge-conflict', 'merge-blocked', 'urgent'];
206
+ } else {
207
+ title = `❌ Feature Merge Workflow Failed: ${{ github.event.inputs.feature_branch }}`;
208
+ body = `## Manual Merge Workflow Failed
209
+
210
+ **Feature Branch:** \`${{ github.event.inputs.feature_branch }}\`
211
+ **Commit:** ${context.sha}
212
+ **Workflow Run:** [View Logs](${context.payload.repository.html_url}/actions/runs/${context.runId})
213
+
214
+ ### Issue:
215
+ The manual merge workflow failed.
216
+
217
+ ### Action Required:
218
+ 1. Review the [workflow logs](${context.payload.repository.html_url}/actions/runs/${context.runId})
219
+ 2. Fix any issues and retry the workflow
220
+
221
+ **⚠️ No merge occurred due to workflow failure.**`;
222
+ labels = ['workflow-failure', 'merge-blocked', 'urgent'];
223
+ }
224
+
225
+ github.rest.issues.create({
226
+ owner: context.repo.owner,
227
+ repo: context.repo.repo,
228
+ title: title,
229
+ body: body,
230
+ labels: labels
231
+ });
.github/workflows/manual-promote.yml ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Manual Promotion (Staging to Main)
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ inputs:
6
+ reason:
7
+ description: 'Reason for manual promotion'
8
+ required: false
9
+ default: 'Manual promotion triggered'
10
+
11
+ permissions:
12
+ contents: write
13
+
14
+ jobs:
15
+ manual-promote:
16
+ runs-on: ubuntu-latest
17
+ steps:
18
+ - name: Checkout staging
19
+ uses: actions/checkout@v4
20
+ with:
21
+ ref: staging
22
+ fetch-depth: 0
23
+ lfs: true
24
+ token: ${{ secrets.GITHUB_TOKEN }}
25
+
26
+ - name: Set up Python
27
+ uses: actions/setup-python@v5
28
+ with:
29
+ python-version: '3.11'
30
+
31
+ - name: Install dependencies
32
+ run: |
33
+ python -m pip install --upgrade pip
34
+ pip install -r requirements.txt
35
+
36
+ - name: Run tests on staging
37
+ env:
38
+ GROQ_API_KEY: ${{ secrets.GROQ_API_KEY }}
39
+ run: pytest -v
40
+
41
+ - name: Promote staging to main
42
+ if: success()
43
+ env:
44
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
45
+ run: |
46
+ echo "Manual promotion reason: ${{ github.event.inputs.reason }}"
47
+ echo "Starting manual promotion from staging to main..."
48
+
49
+ git config --global user.email "github-actions[bot]@users.noreply.github.com"
50
+ git config --global user.name "github-actions[bot]"
51
+ git fetch origin
52
+
53
+ # Check if main branch exists remotely
54
+ if git show-ref --verify --quiet refs/remotes/origin/main; then
55
+ echo "Main branch exists, checking out and merging"
56
+ git checkout main
57
+
58
+ # Try to merge with strategy to resolve conflicts automatically
59
+ echo "Attempting to merge staging into main..."
60
+ if git merge staging --allow-unrelated-histories --no-ff -X theirs -m "Manual promote staging to main: ${{ github.event.inputs.reason }}"; then
61
+ echo "Merge successful"
62
+ else
63
+ echo "Merge conflicts detected, using staging version"
64
+ # Reset to staging state and create merge commit
65
+ git reset --hard staging
66
+ git commit --allow-empty -m "Manual promote staging to main (using staging version): ${{ github.event.inputs.reason }}"
67
+ fi
68
+ else
69
+ echo "Main branch doesn't exist, creating from staging"
70
+ git checkout -b main
71
+ fi
72
+
73
+ echo "Pushing to main branch..."
74
+ # Push to main using authenticated remote
75
+ git remote set-url origin https://x-access-token:${GITHUB_TOKEN}@github.com/${{ github.repository }}.git
76
+ git push origin main
77
+ echo "Successfully promoted staging to main!"
.github/workflows/promote.yml ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Manual Staging to Main Promotion
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ inputs:
6
+ reason:
7
+ description: 'Reason for promotion to main'
8
+ required: false
9
+ default: 'Manual promotion triggered'
10
+
11
+ permissions:
12
+ contents: write
13
+ issues: write
14
+
15
+ jobs:
16
+ test-staging-and-promote:
17
+ runs-on: ubuntu-latest
18
+ steps:
19
+ - name: Checkout staging
20
+ uses: actions/checkout@v4
21
+ with:
22
+ ref: staging
23
+ fetch-depth: 0
24
+ lfs: true
25
+ token: ${{ secrets.GITHUB_TOKEN }}
26
+
27
+ - name: Set up Python
28
+ uses: actions/setup-python@v5
29
+ with:
30
+ python-version: '3.11'
31
+
32
+ - name: Install dependencies
33
+ run: |
34
+ python -m pip install --upgrade pip
35
+ pip install -r requirements.txt
36
+
37
+ - name: Run tests on staging
38
+ id: test-staging
39
+ env:
40
+ GROQ_API_KEY: ${{ secrets.GROQ_API_KEY }}
41
+ run: |
42
+ echo "Manual promotion reason: ${{ github.event.inputs.reason }}"
43
+ echo "Starting manual promotion from staging to main..."
44
+ echo "Running tests on staging branch before promotion..."
45
+ pytest -v
46
+ echo "✅ Staging tests passed!"
47
+
48
+ - name: Check for merge conflicts with main
49
+ id: conflict-check
50
+ env:
51
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
52
+ run: |
53
+ echo "Checking for potential merge conflicts with main..."
54
+ git fetch origin main:main 2>/dev/null || {
55
+ echo "main_exists=false" >> $GITHUB_OUTPUT
56
+ echo "⚠️ Main branch doesn't exist yet. Will create it from staging."
57
+ exit 0
58
+ }
59
+
60
+ echo "main_exists=true" >> $GITHUB_OUTPUT
61
+
62
+ # Try a test merge to check for conflicts
63
+ git checkout main
64
+ git checkout staging
65
+
66
+ if git merge-tree $(git merge-base main staging) main staging | grep -q "<<<<<<< "; then
67
+ echo "has_conflicts=true" >> $GITHUB_OUTPUT
68
+ echo "❌ Merge conflicts detected with main branch!"
69
+
70
+ # Get conflict details
71
+ conflict_files=$(git merge-tree $(git merge-base main staging) main staging | grep "<<<<<<< " -A 10 -B 2 || echo "Unable to determine conflict details")
72
+ echo "conflict_details<<EOF" >> $GITHUB_OUTPUT
73
+ echo "$conflict_files" >> $GITHUB_OUTPUT
74
+ echo "EOF" >> $GITHUB_OUTPUT
75
+ else
76
+ echo "has_conflicts=false" >> $GITHUB_OUTPUT
77
+ echo "✅ No merge conflicts detected with main!"
78
+ fi
79
+
80
+ - name: Create conflict alert issue
81
+ if: steps.conflict-check.outputs.has_conflicts == 'true'
82
+ uses: actions/github-script@v7
83
+ with:
84
+ script: |
85
+ const title = `🚨 Staging to Main Merge Conflict Alert`;
86
+ const body = `## Merge Conflict Detected During Promotion
87
+
88
+ **Source Branch:** \`staging\`
89
+ **Target Branch:** \`main\`
90
+ **Commit:** ${context.sha}
91
+
92
+ ### Conflict Details:
93
+ \`\`\`
94
+ ${{ steps.conflict-check.outputs.conflict_details }}
95
+ \`\`\`
96
+
97
+ ### Action Required:
98
+ The staging branch cannot be automatically promoted to main due to merge conflicts.
99
+
100
+ **Options:**
101
+ 1. **Manual Resolution:** Use the [Manual Promotion workflow](${context.payload.repository.html_url}/actions/workflows/manual-promote.yml) after resolving conflicts
102
+ 2. **Fix Conflicts:** Manually resolve conflicts in a feature branch and re-merge to staging
103
+
104
+ ### Manual Resolution Commands:
105
+ \`\`\`bash
106
+ git checkout main
107
+ git pull origin main
108
+ git merge staging
109
+ # Resolve conflicts manually
110
+ git add .
111
+ git commit -m "Resolve staging to main merge conflicts"
112
+ git push origin main
113
+ \`\`\`
114
+
115
+ This issue will be closed when the promotion is successful.`;
116
+
117
+ github.rest.issues.create({
118
+ owner: context.repo.owner,
119
+ repo: context.repo.repo,
120
+ title: title,
121
+ body: body,
122
+ labels: ['merge-conflict', 'promotion-blocked', 'urgent']
123
+ });
124
+
125
+ - name: Create test failure alert
126
+ if: steps.test-staging.outcome == 'failure'
127
+ uses: actions/github-script@v7
128
+ with:
129
+ script: |
130
+ const title = `❌ Staging Tests Failed - Promotion Blocked`;
131
+ const body = `## Staging Branch Tests Failed
132
+
133
+ **Branch:** \`staging\`
134
+ **Commit:** ${context.sha}
135
+ **Workflow:** ${context.workflow}
136
+ **Run ID:** ${context.runId}
137
+
138
+ ### Issue:
139
+ Tests failed on the staging branch, blocking automatic promotion to main.
140
+
141
+ ### Action Required:
142
+ 1. Review the [failed workflow run](${context.payload.repository.html_url}/actions/runs/${context.runId})
143
+ 2. Fix the failing tests in a feature branch
144
+ 3. Merge the fix to staging to retry promotion
145
+
146
+ ### Test Command:
147
+ \`\`\`bash
148
+ pytest -v
149
+ \`\`\`
150
+
151
+ This issue will be closed when tests pass and promotion succeeds.`;
152
+
153
+ github.rest.issues.create({
154
+ owner: context.repo.owner,
155
+ repo: context.repo.repo,
156
+ title: title,
157
+ body: body,
158
+ labels: ['test-failure', 'promotion-blocked', 'urgent']
159
+ });
160
+
161
+ - name: Clean workspace
162
+ if: steps.test-staging.outcome == 'success' && steps.conflict-check.outputs.has_conflicts == 'false'
163
+ run: |
164
+ git reset --hard
165
+ git clean -fdx
166
+
167
+ - name: Promote staging to main
168
+ if: steps.test-staging.outcome == 'success' && steps.conflict-check.outputs.has_conflicts == 'false'
169
+ env:
170
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
171
+ run: |
172
+ echo "✅ Tests passed and no conflicts detected. Proceeding with promotion to main..."
173
+
174
+ git config --global user.email "github-actions[bot]@users.noreply.github.com"
175
+ git config --global user.name "github-actions[bot]"
176
+ git fetch origin
177
+ git reset --hard
178
+ git clean -fdx
179
+
180
+ # Handle main branch creation or checkout
181
+ if [ "${{ steps.conflict-check.outputs.main_exists }}" = "true" ]; then
182
+ echo "Checking out existing main branch"
183
+ git checkout main
184
+ git merge staging --no-ff -m "Auto-promote staging to main"
185
+ else
186
+ echo "Creating main branch from staging"
187
+ git checkout -b main
188
+ fi
189
+
190
+ # Push to main
191
+ git remote set-url origin https://x-access-token:${GITHUB_TOKEN}@github.com/${{ github.repository }}.git
192
+ echo "Pushing to main branch..."
193
+ git push origin main
194
+
195
+ echo "✅ Successfully promoted staging to main!"
196
+ echo "🚀 This will trigger deployment to production..."
197
+
198
+ - name: Create success notification
199
+ if: steps.test-staging.outcome == 'success' && steps.conflict-check.outputs.has_conflicts == 'false'
200
+ uses: actions/github-script@v7
201
+ with:
202
+ script: |
203
+ const title = `✅ Staging Successfully Promoted to Main`;
204
+ const body = `## Promotion Successful
205
+
206
+ **Source Branch:** \`staging\`
207
+ **Target Branch:** \`main\`
208
+ **Commit:** ${context.sha}
209
+
210
+ ### Status:
211
+ - ✅ Tests passed on staging
212
+ - ✅ No merge conflicts detected
213
+ - ✅ Successfully merged to main
214
+ - 🚀 Production deployment triggered
215
+
216
+ ### Next Steps:
217
+ The [Deploy to Production workflow](${context.payload.repository.html_url}/actions) will now run to deploy the main branch to HuggingFace production space.
218
+
219
+ **Production URL:** https://neurostack-in-talk2map-prod.hf.space`;
220
+
221
+ github.rest.issues.create({
222
+ owner: context.repo.owner,
223
+ repo: context.repo.repo,
224
+ title: title,
225
+ body: body,
226
+ labels: ['promotion-success', 'deployment']
227
+ });
.github/workflows/staging-ci.yml ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Staging Branch CI
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - staging
7
+ pull_request:
8
+ branches:
9
+ - staging
10
+
11
+ permissions:
12
+ contents: read
13
+ pull-requests: write
14
+ issues: write
15
+
16
+ jobs:
17
+ test-staging:
18
+ runs-on: ubuntu-latest
19
+ steps:
20
+ - name: Checkout staging branch
21
+ uses: actions/checkout@v4
22
+ with:
23
+ fetch-depth: 0
24
+ token: ${{ secrets.GITHUB_TOKEN }}
25
+
26
+ - name: Set up Python
27
+ uses: actions/setup-python@v5
28
+ with:
29
+ python-version: '3.11'
30
+
31
+ - name: Install dependencies
32
+ run: |
33
+ python -m pip install --upgrade pip
34
+ pip install -r requirements.txt
35
+
36
+ - name: Run tests on staging
37
+ id: test-staging
38
+ env:
39
+ GROQ_API_KEY: ${{ secrets.GROQ_API_KEY }}
40
+ run: |
41
+ echo "Running tests on staging branch after merge..."
42
+ pytest -v
43
+ echo "✅ Staging tests passed!"
44
+
45
+ - name: Deploy to HuggingFace test space
46
+ if: success() && github.event_name == 'push'
47
+ env:
48
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
49
+ HF_USERNAME: neurostack-in
50
+ SPACE_NAME: talk2map-test
51
+ run: |
52
+ echo "🚀 Deploying staging to HuggingFace test space..."
53
+
54
+ git config --global user.email "github-actions[bot]@users.noreply.github.com"
55
+ git config --global user.name "github-actions[bot]"
56
+
57
+ # Push to Hugging Face test space
58
+ git push --force \
59
+ https://$HF_USERNAME:$HF_TOKEN@huggingface.co/spaces/$HF_USERNAME/$SPACE_NAME \
60
+ staging:main
61
+
62
+ echo "✅ Successfully deployed to HF test space!"
63
+ echo "🎯 HuggingFace Test URL: https://neurostack-in-talk2map-test.hf.space"
64
+ echo "⏳ API testing will start automatically after deployment..."
65
+
66
+ - name: Create test failure alert
67
+ if: failure()
68
+ uses: actions/github-script@v7
69
+ with:
70
+ script: |
71
+ const title = `❌ Staging Tests Failed`;
72
+ const body = `## Staging Branch Tests Failed
73
+
74
+ **Branch:** \`staging\`
75
+ **Commit:** ${context.sha}
76
+ **Workflow Run:** [View Logs](${context.payload.repository.html_url}/actions/runs/${context.runId})
77
+
78
+ ### Issue:
79
+ Tests failed on the staging branch after merge.
80
+
81
+ ### Action Required:
82
+ 1. Review the [failed test logs](${context.payload.repository.html_url}/actions/runs/${context.runId})
83
+ 2. Fix the failing tests in a new feature branch
84
+ 3. Merge the fix to staging to retry
85
+
86
+ ### Test Command:
87
+ \`\`\`bash
88
+ pytest -v
89
+ \`\`\`
90
+
91
+ **⚠️ Staging branch has failing tests - promotion to main should be avoided until fixed.**`;
92
+
93
+ github.rest.issues.create({
94
+ owner: context.repo.owner,
95
+ repo: context.repo.repo,
96
+ title: title,
97
+ body: body,
98
+ labels: ['test-failure', 'staging', 'urgent']
99
+ });
100
+
101
+ - name: Create test success notification
102
+ if: success() && github.event_name == 'push'
103
+ uses: actions/github-script@v7
104
+ with:
105
+ script: |
106
+ const title = `✅ Staging Tests Passed - Ready for Promotion`;
107
+ const body = `## Staging Branch Tests Successful
108
+
109
+ **Branch:** \`staging\`
110
+ **Commit:** ${context.sha}
111
+ **Test Environment:** https://neurostack-in-talk2map-test.hf.space
112
+
113
+ ### Status:
114
+ - ✅ All tests passed on staging
115
+ - ✅ Deployed to HuggingFace test space
116
+ - ✅ Ready for manual promotion to main
117
+
118
+ ### Next Steps:
119
+ The staging branch is now tested and ready. When you're ready to promote to production:
120
+
121
+ 1. Use the [Manual Promotion workflow](${context.payload.repository.html_url}/actions/workflows/manual-promote.yml)
122
+ 2. Or merge staging to main manually if preferred
123
+
124
+ **🚀 Staging is ready for production promotion!**`;
125
+
126
+ github.rest.issues.create({
127
+ owner: context.repo.owner,
128
+ repo: context.repo.repo,
129
+ title: title,
130
+ body: body,
131
+ labels: ['staging-ready', 'promotion-ready']
132
+ });
.github/workflows/sync-to-hf.yml ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Deploy to Production
2
+
3
+ on:
4
+ workflow_run:
5
+ workflows: ["Manual Staging to Main Promotion"]
6
+ types:
7
+ - completed
8
+ branches:
9
+ - main
10
+ push:
11
+ branches:
12
+ - main
13
+
14
+ permissions:
15
+ contents: read
16
+ issues: write
17
+
18
+ jobs:
19
+ deploy-to-production:
20
+ runs-on: ubuntu-latest
21
+ if: ${{ github.event.workflow_run.conclusion == 'success' || github.event_name == 'push' }}
22
+ steps:
23
+ - name: Checkout main
24
+ uses: actions/checkout@v4
25
+ with:
26
+ ref: main
27
+ fetch-depth: 0
28
+ lfs: true
29
+
30
+ - name: Set up Python
31
+ uses: actions/setup-python@v5
32
+ with:
33
+ python-version: '3.11'
34
+
35
+ - name: Install dependencies
36
+ run: |
37
+ python -m pip install --upgrade pip
38
+ pip install -r requirements.txt
39
+
40
+ - name: Run final tests on main
41
+ id: test-main
42
+ env:
43
+ GROQ_API_KEY: ${{ secrets.GROQ_API_KEY }}
44
+ run: |
45
+ echo "Running final tests on main branch before production deployment..."
46
+ pytest -v
47
+ echo "✅ Main branch tests passed!"
48
+
49
+ - name: Configure git user
50
+ if: steps.test-main.outcome == 'success'
51
+ run: |
52
+ git config user.name "${GITHUB_ACTOR}"
53
+ git config user.email "${GITHUB_ACTOR}@users.noreply.github.com"
54
+
55
+ - name: Deploy to Hugging Face Production Space
56
+ if: steps.test-main.outcome == 'success'
57
+ id: deploy-hf
58
+ env:
59
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
60
+ HF_USERNAME: neurostack-in
61
+ SPACE_NAME: talk2map-prod
62
+ run: |
63
+ echo "🚀 Deploying main branch to Hugging Face production space..."
64
+
65
+ git push --force \
66
+ https://$HF_USERNAME:$HF_TOKEN@huggingface.co/spaces/$HF_USERNAME/$SPACE_NAME \
67
+ HEAD:main
68
+
69
+ echo "✅ Successfully deployed to production!"
70
+ echo "🌐 Production URL: https://neurostack-in-talk2map-prod.hf.space"
71
+
72
+ - name: Create deployment success notification
73
+ if: steps.test-main.outcome == 'success' && steps.deploy-hf.outcome == 'success'
74
+ uses: actions/github-script@v7
75
+ with:
76
+ script: |
77
+ const title = `🚀 Production Deployment Successful`;
78
+ const body = `## Production Deployment Complete
79
+
80
+ **Branch:** \`main\`
81
+ **Commit:** ${context.sha}
82
+ **Deployed to:** HuggingFace Production Space
83
+
84
+ ### Status:
85
+ - ✅ Final tests passed on main branch
86
+ - ✅ Successfully deployed to production
87
+ - 🌐 **Live URL:** https://neurostack-in-talk2map-prod.hf.space
88
+
89
+ ### Deployment Details:
90
+ - **Environment:** Production
91
+ - **Platform:** HuggingFace Spaces
92
+ - **Space Name:** neurostack-in/talk2map-prod
93
+ - **Deployment Time:** ${new Date().toISOString()}
94
+
95
+ ### Next Steps:
96
+ The production API is now live. You can:
97
+ 1. Test the production endpoints
98
+ 2. Monitor for any issues
99
+ 3. Run API tests against production if needed
100
+
101
+ API testing can be triggered manually using the [API Testing workflow](${context.payload.repository.html_url}/actions/workflows/api-testing.yml).`;
102
+
103
+ github.rest.issues.create({
104
+ owner: context.repo.owner,
105
+ repo: context.repo.repo,
106
+ title: title,
107
+ body: body,
108
+ labels: ['deployment-success', 'production']
109
+ });
110
+
111
+ - name: Create test failure alert
112
+ if: steps.test-main.outcome == 'failure'
113
+ uses: actions/github-script@v7
114
+ with:
115
+ script: |
116
+ const title = `❌ Production Deployment Blocked - Tests Failed`;
117
+ const body = `## Main Branch Tests Failed
118
+
119
+ **Branch:** \`main\`
120
+ **Commit:** ${context.sha}
121
+ **Workflow:** ${context.workflow}
122
+ **Run ID:** ${context.runId}
123
+
124
+ ### Issue:
125
+ Tests failed on the main branch, blocking production deployment.
126
+
127
+ ### Action Required:
128
+ 1. Review the [failed workflow run](${context.payload.repository.html_url}/actions/runs/${context.runId})
129
+ 2. Fix the failing tests
130
+ 3. Use a hotfix branch or roll back the problematic changes
131
+
132
+ ### Emergency Options:
133
+ - **Hotfix:** Create a hotfix branch, fix the issue, and merge to main
134
+ - **Rollback:** Revert the problematic commit and redeploy
135
+ - **Manual Deploy:** Use manual deployment after fixing issues locally
136
+
137
+ **⚠️ Production deployment is currently blocked!**`;
138
+
139
+ github.rest.issues.create({
140
+ owner: context.repo.owner,
141
+ repo: context.repo.repo,
142
+ title: title,
143
+ body: body,
144
+ labels: ['test-failure', 'deployment-blocked', 'production', 'urgent']
145
+ });
146
+
147
+ - name: Create deployment failure alert
148
+ if: steps.test-main.outcome == 'success' && steps.deploy-hf.outcome == 'failure'
149
+ uses: actions/github-script@v7
150
+ with:
151
+ script: |
152
+ const title = `❌ Production Deployment Failed`;
153
+ const body = `## HuggingFace Deployment Failed
154
+
155
+ **Branch:** \`main\`
156
+ **Commit:** ${context.sha}
157
+ **Workflow:** ${context.workflow}
158
+ **Run ID:** ${context.runId}
159
+
160
+ ### Issue:
161
+ Tests passed but deployment to HuggingFace production space failed.
162
+
163
+ ### Possible Causes:
164
+ - HuggingFace API token issues
165
+ - Network connectivity problems
166
+ - HuggingFace service issues
167
+ - Space configuration problems
168
+
169
+ ### Action Required:
170
+ 1. Check [workflow logs](${context.payload.repository.html_url}/actions/runs/${context.runId})
171
+ 2. Verify HF_TOKEN secret is valid
172
+ 3. Check HuggingFace space status
173
+ 4. Retry deployment manually if needed
174
+
175
+ **⚠️ Production deployment failed - manual intervention required!**`;
176
+
177
+ github.rest.issues.create({
178
+ owner: context.repo.owner,
179
+ repo: context.repo.repo,
180
+ title: title,
181
+ body: body,
182
+ labels: ['deployment-failure', 'production', 'urgent']
183
+ });
.gitignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ .env
2
+ __pycache__/
3
+ /__pycache__/
4
+ *.pyc
5
+ /api/__pycache__/
API_DOCUMENTATION.md ADDED
@@ -0,0 +1,798 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Talk2Map API Documentation
2
+
3
+ This document provides an overview of the MapMate API endpoints, including their descriptions, request formats, and example responses, generated from the `Talk2Map.postman_collection.json` file.
4
+
5
+ ## Endpoints
6
+
7
+ ---
8
+
9
+ ### Health
10
+
11
+ **Description:** Quick health check for the MapMate API.
12
+ **Method:** `GET`
13
+ **URL:** `{{baseUrl}}/health`
14
+
15
+ **Request:**
16
+ No specific request body or headers required.
17
+
18
+ **Response (Example):**
19
+ ```json
20
+ {
21
+ "status": "ok"
22
+ }
23
+ ```
24
+
25
+ ---
26
+
27
+ ### Chat — With Places (Hotels in Chennai)
28
+
29
+ **Description:** Calls `/chat` expecting places array (top 2 hotels in Chennai).
30
+ **Method:** `POST`
31
+ **URL:** `{{baseUrl}}/chat`
32
+
33
+ **Request Headers:**
34
+ ```
35
+ Content-Type: application/json
36
+ ```
37
+
38
+ **Request Body (Example):**
39
+ ```json
40
+ {
41
+ "user_input": "best 2 hotel in chennai",
42
+ "conversation_history": [
43
+ {
44
+ "human": "hello",
45
+ "ai": "hello sir"
46
+ }
47
+ ]
48
+ }
49
+ ```
50
+
51
+ **Response (Example - inferred from tests and request context):**
52
+ ```json
53
+ {
54
+ "agent_reply": {
55
+ "message": "1. ITC Grand Chola, a Luxury Collection Hotel, Chennai — 63, Mount Rd, Little Mount, Guindy, Chennai, Tamil Nadu 600032 (4.7 ★, 41869 Reviews, Maps URL)\n lat,lng: 13.010613, 80.2206015\n SW: (13.009167, 80.219515), NE: (13.011865, 80.222213)\n\n2. The Leela Palace Chennai - Seaside Modern Palace Hotel — Adyar Sea Face, Leela Palace Rd, MRC Nagar, Raja Annamalai Puram, Chennai, Tamil Nadu 600028 (4.6 ★, 15418 Reviews, Maps URL)\n lat,lng: 13.017048, 80.2736566\n SW: (13.016065, 80.271977), NE: (13.018762, 80.274675)",
56
+ "places": [
57
+ {
58
+ "name": "ITC Grand Chola, a Luxury Collection Hotel, Chennai",
59
+ "address": "63, Mount Rd, Little Mount, Guindy, Chennai, Tamil Nadu 600032",
60
+ "latitude": 13.010613,
61
+ "longitude": 80.2206015,
62
+ "bounding_box": {
63
+ "north_east": {
64
+ "lat": 13.011865130291502,
65
+ "lon": 80.2222132802915
66
+ },
67
+ "south_west": {
68
+ "lat": 13.009167169708498,
69
+ "lon": 80.21951531970849
70
+ }
71
+ },
72
+ "rating": 4.7,
73
+ "user_rating_count": 41869,
74
+ "maps_url": "https://maps.google.com/?cid=17494736093121177155&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
75
+ },
76
+ {
77
+ "name": "The Leela Palace Chennai - Seaside Modern Palace Hotel",
78
+ "address": "Adyar Sea Face, Leela Palace Rd, MRC Nagar, Raja Annamalai Puram, Chennai, Tamil Nadu 600028",
79
+ "latitude": 13.017048,
80
+ "longitude": 80.2736566,
81
+ "bounding_box": {
82
+ "north_east": {
83
+ "lat": 13.018762480291501,
84
+ "lon": 80.2746746802915
85
+ },
86
+ "south_west": {
87
+ "lat": 13.016064519708497,
88
+ "lon": 80.27197671970849
89
+ }
90
+ },
91
+ "rating": 4.6,
92
+ "user_rating_count": 15418,
93
+ "maps_url": "https://maps.google.com/?cid=7374804035710576015&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
94
+ }
95
+ ]
96
+ },
97
+ "conversation_history": [
98
+ {
99
+ "human": "hello",
100
+ "ai": "hello sir"
101
+ },
102
+ {
103
+ "human": "best 2 hotel in chennai",
104
+ "ai": {
105
+ "message": "1. ITC Grand Chola, a Luxury Collection Hotel, Chennai — 63, Mount Rd, Little Mount, Guindy, Chennai, Tamil Nadu 600032 (4.7 ★, 41869 Reviews, Maps URL)\n lat,lng: 13.010613, 80.2206015\n SW: (13.009167, 80.219515), NE: (13.011865, 80.222213)\n\n2. The Leela Palace Chennai - Seaside Modern Palace Hotel — Adyar Sea Face, Leela Palace Rd, MRC Nagar, Raja Annamalai Puram, Chennai, Tamil Nadu 600028 (4.6 ★, 15418 Reviews, Maps URL)\n lat,lng: 13.017048, 80.2736566\n SW: (13.016065, 80.271977), NE: (13.018762, 80.274675)",
106
+ "places": [
107
+ {
108
+ "name": "ITC Grand Chola, a Luxury Collection Hotel, Chennai",
109
+ "address": "63, Mount Rd, Little Mount, Guindy, Chennai, Tamil Nadu 600032",
110
+ "latitude": 13.010613,
111
+ "longitude": 80.2206015,
112
+ "bounding_box": {
113
+ "north_east": {
114
+ "lat": 13.011865130291502,
115
+ "lon": 80.2222132802915
116
+ },
117
+ "south_west": {
118
+ "lat": 13.009167169708498,
119
+ "lon": 80.21951531970849
120
+ }
121
+ },
122
+ "rating": 4.7,
123
+ "user_rating_count": 41869,
124
+ "maps_url": "https://maps.google.com/?cid=17494736093121177155&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
125
+ },
126
+ {
127
+ "name": "The Leela Palace Chennai - Seaside Modern Palace Hotel",
128
+ "address": "Adyar Sea Face, Leela Palace Rd, MRC Nagar, Raja Annamalai Puram, Chennai, Tamil Nadu 600028",
129
+ "latitude": 13.017048,
130
+ "longitude": 80.2736566,
131
+ "bounding_box": {
132
+ "north_east": {
133
+ "lat": 13.018762480291501,
134
+ "lon": 80.2746746802915
135
+ },
136
+ "south_west": {
137
+ "lat": 13.016064519708497,
138
+ "lon": 80.27197671970849
139
+ }
140
+ },
141
+ "rating": 4.6,
142
+ "user_rating_count": 15418,
143
+ "maps_url": "https://maps.google.com/?cid=7374804035710576015&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
144
+ }
145
+ ]
146
+ }
147
+ }
148
+ ]
149
+ }
150
+ ```
151
+
152
+ ---
153
+
154
+ ### Chat — No Places (General Knowledge)
155
+
156
+ **Description:** Calls `/chat` expecting NO places array for a general question.
157
+ **Method:** `POST`
158
+ **URL:** `{{baseUrl}}/chat`
159
+
160
+ **Request Headers:**
161
+ ```
162
+ Content-Type: application/json
163
+ ```
164
+
165
+ **Request Body (Example):**
166
+ ```json
167
+ {
168
+ "user_input": "What is the capital of India?",
169
+ "conversation_history": [
170
+ {
171
+ "human": "hello",
172
+ "ai": "hello sir"
173
+ }
174
+ ]
175
+ }
176
+ ```
177
+
178
+ **Response (Example - inferred from tests):**
179
+ ```json
180
+ {
181
+ "agent_reply": {
182
+ "message": "The capital of India is New Delhi.",
183
+ "places": []
184
+ },
185
+ "conversation_history": [
186
+ {
187
+ "human": "hello",
188
+ "ai": "hello sir"
189
+ },
190
+ {
191
+ "human": "What is the capital of India?",
192
+ "ai": {
193
+ "message": "The capital of India is New Delhi.",
194
+ "places": []
195
+ }
196
+ }
197
+ ]
198
+ }
199
+ ```
200
+
201
+ ---
202
+
203
+ ### Chat — Lat/Lng for ITC Grand Chola (contextual)
204
+
205
+ **Description:** Follow-up that asks for latitude/longitude of ITC Grand Chola using prior conversation context.
206
+ **Method:** `POST`
207
+ **URL:** `{{baseUrl}}/chat`
208
+
209
+ **Request Headers:**
210
+ ```
211
+ Content-Type: application/json
212
+ ```
213
+
214
+ **Request Body (Example):**
215
+ ```json
216
+ {
217
+ "user_input": "give me the lat and lan of ITC Grand Chola",
218
+ "conversation_history": [
219
+ {
220
+ "human": "hello",
221
+ "ai": "hello sir"
222
+ },
223
+ {
224
+ "human": "best 2 hotel in chennai",
225
+ "ai": {
226
+ "message": "1. ITC Grand Chola, a Luxury Collection Hotel, Chennai — 63, Mount Rd, Little Mount, Guindy, Chennai, Tamil Nadu 600032 (4.7 ★, 41868 Reviews, Maps URL)\nlat,lng: 13.010613, 80.2206015\nSW: (13.009167, 80.219515), NE: (13.011865, 80.222213)\n\n2. The Leela Palace Chennai - Seaside Modern Palace Hotel — Adyar Sea Face, Leela Palace Rd, MRC Nagar, Raja Annamalai Puram, Chennai, Tamil Nadu 600028 (4.6 ★, 15413 Reviews, Maps URL)\nlat,lng: 13.017048, 80.2736566\nSW: (13.016065, 80.271977), NE: (13.018762, 80.274675)",
227
+ "places": [
228
+ {
229
+ "name": "ITC Grand Chola, a Luxury Collection Hotel, Chennai",
230
+ "address": "63, Mount Rd, Little Mount, Guindy, Chennai, Tamil Nadu 600032",
231
+ "latitude": 13.010613,
232
+ "longitude": 80.2206015,
233
+ "bounding_box": {
234
+ "north_east": {
235
+ "lat": 13.011865130291502,
236
+ "lon": 80.2222132802915
237
+ },
238
+ "south_west": {
239
+ "lat": 13.009167169708498,
240
+ "lon": 80.21951531970849
241
+ }
242
+ },
243
+ "rating": 4.7,
244
+ "user_rating_count": 41868,
245
+ "maps_url": "https://maps.google.com/?cid=17494736093121177155&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
246
+ },
247
+ {
248
+ "name": "The Leela Palace Chennai - Seaside Modern Palace Hotel",
249
+ "address": "Adyar Sea Face, Leela Palace Rd, MRC Nagar, Raja Annamalai Puram, Chennai, Tamil Nadu 600028",
250
+ "latitude": 13.017048,
251
+ "longitude": 80.2736566,
252
+ "bounding_box": {
253
+ "north_east": {
254
+ "lat": 13.018762480291501,
255
+ "lon": 80.2746746802915
256
+ },
257
+ "south_west": {
258
+ "lat": 13.016064519708497,
259
+ "lon": 80.27197671970849
260
+ }
261
+ },
262
+ "rating": 4.6,
263
+ "user_rating_count": 15413,
264
+ "maps_url": "https://maps.google.com/?cid=7374804035710576015&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
265
+ }
266
+ ]
267
+ }
268
+ }
269
+ ]
270
+ }
271
+ ```
272
+
273
+ **Response (Example - inferred from tests):**
274
+ ```json
275
+ {
276
+ "agent_reply": {
277
+ "message": "lat,lng: 13.010613, 80.2206015",
278
+ "places": [
279
+ {
280
+ "name": "ITC Grand Chola, a Luxury Collection Hotel, Chennai",
281
+ "address": "63, Mount Rd, Little Mount, Guindy, Chennai, Tamil Nadu 600032",
282
+ "latitude": 13.010613,
283
+ "longitude": 80.2206015,
284
+ "bounding_box": {
285
+ "north_east": {
286
+ "lat": 13.011865130291502,
287
+ "lon": 80.2222132802915
288
+ },
289
+ "south_west": {
290
+ "lat": 13.009167169708498,
291
+ "lon": 80.21951531970849
292
+ }
293
+ },
294
+ "rating": 4.7,
295
+ "user_rating_count": 41869,
296
+ "maps_url": "https://maps.google.com/?cid=17494736093121177155&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
297
+ }
298
+ ]
299
+ },
300
+ "conversation_history": [
301
+ {
302
+ "human": "hello",
303
+ "ai": "hello sir"
304
+ },
305
+ {
306
+ "human": "best 2 hotel in chennai",
307
+ "ai": {
308
+ "message": "1. ITC Grand Chola, a Luxury Collection Hotel, Chennai — 63, Mount Rd, Little Mount, Guindy, Chennai, Tamil Nadu 600032 (4.7 ★, 41868 Reviews, Maps URL)\nlat,lng: 13.010613, 80.2206015\nSW: (13.009167, 80.219515), NE: (13.011865, 80.222213)\n\n2. The Leela Palace Chennai - Seaside Modern Palace Hotel — Adyar Sea Face, Leela Palace Rd, MRC Nagar, Raja Annamalai Puram, Chennai, Tamil Nadu 600028 (4.6 ★, 15413 Reviews, Maps URL)\nlat,lng: 13.017048, 80.2736566\nSW: (13.016065, 80.271977), NE: (13.018762, 80.274675)",
309
+ "places": [
310
+ {
311
+ "name": "ITC Grand Chola, a Luxury Collection Hotel, Chennai",
312
+ "address": "63, Mount Rd, Little Mount, Guindy, Chennai, Tamil Nadu 600032",
313
+ "latitude": 13.010613,
314
+ "longitude": 80.2206015,
315
+ "bounding_box": {
316
+ "north_east": {
317
+ "lat": 13.011865130291502,
318
+ "lon": 80.2222132802915
319
+ },
320
+ "south_west": {
321
+ "lat": 13.009167169708498,
322
+ "lon": 80.21951531970849
323
+ }
324
+ },
325
+ "rating": 4.7,
326
+ "user_rating_count": 41868,
327
+ "maps_url": "https://maps.google.com/?cid=17494736093121177155&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
328
+ },
329
+ {
330
+ "name": "The Leela Palace Chennai - Seaside Modern Palace Hotel",
331
+ "address": "Adyar Sea Face, Leela Palace Rd, MRC Nagar, Raja Annamalai Puram, Chennai, Tamil Nadu 600028",
332
+ "latitude": 13.017048,
333
+ "longitude": 80.2736566,
334
+ "bounding_box": {
335
+ "north_east": {
336
+ "lat": 13.018762480291501,
337
+ "lon": 80.2746746802915
338
+ },
339
+ "south_west": {
340
+ "lat": 13.016064519708497,
341
+ "lon": 80.27197671970849
342
+ }
343
+ },
344
+ "rating": 4.6,
345
+ "user_rating_count": 15413,
346
+ "maps_url": "https://maps.google.com/?cid=7374804035710576015&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
347
+ }
348
+ ]
349
+ }
350
+ },
351
+ {
352
+ "human": "give me the lat and lan of ITC Grand Chola",
353
+ "ai": {
354
+ "message": "lat,lng: 13.010613, 80.2206015",
355
+ "places": [
356
+ {
357
+ "name": "ITC Grand Chola, a Luxury Collection Hotel, Chennai",
358
+ "address": "63, Mount Rd, Little Mount, Guindy, Chennai, Tamil Nadu 600032",
359
+ "latitude": 13.010613,
360
+ "longitude": 80.2206015,
361
+ "bounding_box": {
362
+ "north_east": {
363
+ "lat": 13.011865130291502,
364
+ "lon": 80.2222132802915
365
+ },
366
+ "south_west": {
367
+ "lat": 13.009167169708498,
368
+ "lon": 80.21951531970849
369
+ }
370
+ },
371
+ "rating": 4.7,
372
+ "user_rating_count": 41869,
373
+ "maps_url": "https://maps.google.com/?cid=17494736093121177155&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
374
+ }
375
+ ]
376
+ }
377
+ }
378
+ ]
379
+ }
380
+
381
+ ### D) Bounding Box Only
382
+
383
+ # Req
384
+
385
+ {
386
+ "user_input": "",
387
+ "conversation_history": [],
388
+ "bounding_box": {
389
+ "north_east": {
390
+ "lat": 13.011865130291502,
391
+ "lon": 80.2222132802915
392
+ },
393
+ "south_west": {
394
+ "lat": 13.009167169708498,
395
+ "lon": 80.21951531970849
396
+ }
397
+ }
398
+ }
399
+
400
+ # Res
401
+
402
+ {
403
+ "agent_reply": {
404
+ "message": "Here are notable places in the selected area (NE: 13.011865, 80.222213 | SW: 13.009167, 80.219515):\n1. Guindy National Park — Rangeguindy, Chennai, Tamil Nadu 600022 — ★ 4.1 (27135 reviews) — Maps: https://maps.google.com/?cid=16909873477740471949&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\n2. AMMA PARK — 167, 63, Kodambakkam Rd, Subramania Salai, Karpaga Vinayaka Nagar, Saidapet, Chennai, Tamil Nadu 600015 — ★ 4.2 (3391 reviews) — Maps: https://maps.google.com/?cid=3851909234074842151&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\n3. Semmozhi Poonga - Chennai, Tamilnadu — Cathedral Rd, opposite American Consulate, Ellaiamman Colony, Teynampet, Chennai, Tamil Nadu 600086 — ★ 4.1 (28482 reviews) — Maps: https://maps.google.com/?cid=9895380879195658203&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\n4. Marina Beach — Marina Beach, Triplicane, Chennai, Tamil Nadu 600005 — ★ 4.4 (21806 reviews) — Maps: https://maps.google.com/?cid=11765186568882202891&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\n5. Jeeva Park — 3/2, Arul Ammal Street, T. Nagar, Chennai, Tamil Nadu 600017 — ★ 4.3 (6389 reviews) — Maps: https://maps.google.com/?cid=11273320818868375015&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\n6. Madras War Cemetery — 257V+JH5, Mount Poonamallee Rd, Ramapuram, Nandambakkam, Chennai, Tamil Nadu 600089 — ★ 4.4 (270 reviews) — Maps: https://maps.google.com/?cid=14746003291783654129&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\n7. Ashok Pillar — Grand Southern Trunk Rd, Zaffarkhanpet, Ashok Nagar, Chennai, Tamil Nadu 600083 — ★ 4.4 (8420 reviews) — Maps: https://maps.google.com/?cid=8848595929871765267&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\n8. Vivekananda House — Kamaraj Salai, VIVEKANANDA HOUSE, Marina Beach Road, Neelam Basha Dargapuram, Triplicane, Chennai, Tamil Nadu 600005 — ★ 4.5 (9780 reviews) — Maps: https://maps.google.com/?cid=326711951594524721&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\n9. Government Museum Chennai — Pantheon Rd, Egmore, Chennai, Tamil Nadu 600008 — ★ 4.3 (18625 reviews) — Maps: https://maps.google.com/?cid=10738827242996767798&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\n10. Victory War Memorial — 37FP+96X, Port Trust Officers Quarters, Sathya Nagar, Chennai Port Trust, Chennai, Tamil Nadu 600009 — ★ 4.5 (1415 reviews) — Maps: https://maps.google.com/?cid=4194342415919237682&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA",
405
+ "places": [
406
+ {
407
+ "name": "Guindy National Park",
408
+ "address": "Rangeguindy, Chennai, Tamil Nadu 600022",
409
+ "latitude": 13.0049251,
410
+ "longitude": 80.2378725,
411
+ "bounding_box": {
412
+ "north_east": {
413
+ "lat": 13.006023130291501,
414
+ "lon": 80.2397574802915
415
+ },
416
+ "south_west": {
417
+ "lat": 13.003325169708496,
418
+ "lon": 80.2370595197085
419
+ }
420
+ },
421
+ "rating": 4.1,
422
+ "user_rating_count": 27135,
423
+ "maps_url": "https://maps.google.com/?cid=16909873477740471949&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
424
+ },
425
+ {
426
+ "name": "AMMA PARK",
427
+ "address": "167, 63, Kodambakkam Rd, Subramania Salai, Karpaga Vinayaka Nagar, Saidapet, Chennai, Tamil Nadu 600015",
428
+ "latitude": 13.026311399999999,
429
+ "longitude": 80.219393,
430
+ "bounding_box": {
431
+ "north_east": {
432
+ "lat": 13.027641180291502,
433
+ "lon": 80.2209456802915
434
+ },
435
+ "south_west": {
436
+ "lat": 13.024943219708497,
437
+ "lon": 80.2182477197085
438
+ }
439
+ },
440
+ "rating": 4.2,
441
+ "user_rating_count": 3391,
442
+ "maps_url": "https://maps.google.com/?cid=3851909234074842151&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
443
+ },
444
+ {
445
+ "name": "Semmozhi Poonga - Chennai, Tamilnadu",
446
+ "address": "Cathedral Rd, opposite American Consulate, Ellaiamman Colony, Teynampet, Chennai, Tamil Nadu 600086",
447
+ "latitude": 13.050537100000001,
448
+ "longitude": 80.2514128,
449
+ "bounding_box": {
450
+ "north_east": {
451
+ "lat": 13.051588030291501,
452
+ "lon": 80.2534814302915
453
+ },
454
+ "south_west": {
455
+ "lat": 13.048890069708497,
456
+ "lon": 80.2507834697085
457
+ }
458
+ },
459
+ "rating": 4.1,
460
+ "user_rating_count": 28482,
461
+ "maps_url": "https://maps.google.com/?cid=9895380879195658203&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
462
+ },
463
+ {
464
+ "name": "Marina Beach",
465
+ "address": "Marina Beach, Triplicane, Chennai, Tamil Nadu 600005",
466
+ "latitude": 13.0471263,
467
+ "longitude": 80.2824339,
468
+ "bounding_box": {
469
+ "north_east": {
470
+ "lat": 13.048588330291503,
471
+ "lon": 80.28301168029151
472
+ },
473
+ "south_west": {
474
+ "lat": 13.045890369708498,
475
+ "lon": 80.28031371970849
476
+ }
477
+ },
478
+ "rating": 4.4,
479
+ "user_rating_count": 21806,
480
+ "maps_url": "https://maps.google.com/?cid=11765186568882202891&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
481
+ },
482
+ {
483
+ "name": "Jeeva Park",
484
+ "address": "3/2, Arul Ammal Street, T. Nagar, Chennai, Tamil Nadu 600017",
485
+ "latitude": 13.0439662,
486
+ "longitude": 80.2377935,
487
+ "bounding_box": {
488
+ "north_east": {
489
+ "lat": 13.045231480291502,
490
+ "lon": 80.2391895802915
491
+ },
492
+ "south_west": {
493
+ "lat": 13.042533519708497,
494
+ "lon": 80.23649161970849
495
+ }
496
+ },
497
+ "rating": 4.3,
498
+ "user_rating_count": 6389,
499
+ "maps_url": "https://maps.google.com/?cid=11273320818868375015&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
500
+ },
501
+ {
502
+ "name": "Madras War Cemetery",
503
+ "address": "257V+JH5, Mount Poonamallee Rd, Ramapuram, Nandambakkam, Chennai, Tamil Nadu 600089",
504
+ "latitude": 13.0140107,
505
+ "longitude": 80.1939804,
506
+ "bounding_box": {
507
+ "north_east": {
508
+ "lat": 13.015330230291502,
509
+ "lon": 80.19528418029151
510
+ },
511
+ "south_west": {
512
+ "lat": 13.012632269708497,
513
+ "lon": 80.1925862197085
514
+ }
515
+ },
516
+ "rating": 4.4,
517
+ "user_rating_count": 270,
518
+ "maps_url": "https://maps.google.com/?cid=14746003291783654129&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
519
+ },
520
+ {
521
+ "name": "Ashok Pillar",
522
+ "address": "Grand Southern Trunk Rd, Zaffarkhanpet, Ashok Nagar, Chennai, Tamil Nadu 600083",
523
+ "latitude": 13.0348542,
524
+ "longitude": 80.21216869999999,
525
+ "bounding_box": {
526
+ "north_east": {
527
+ "lat": 13.036210630291501,
528
+ "lon": 80.2135662302915
529
+ },
530
+ "south_west": {
531
+ "lat": 13.033512669708497,
532
+ "lon": 80.21086826970848
533
+ }
534
+ },
535
+ "rating": 4.4,
536
+ "user_rating_count": 8420,
537
+ "maps_url": "https://maps.google.com/?cid=8848595929871765267&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
538
+ },
539
+ {
540
+ "name": "Vivekananda House",
541
+ "address": "Kamaraj Salai, VIVEKANANDA HOUSE, Marina Beach Road, Neelam Basha Dargapuram, Triplicane, Chennai, Tamil Nadu 600005",
542
+ "latitude": 13.049467499999999,
543
+ "longitude": 80.2803374,
544
+ "bounding_box": {
545
+ "north_east": {
546
+ "lat": 13.050864630291503,
547
+ "lon": 80.2818583302915
548
+ },
549
+ "south_west": {
550
+ "lat": 13.048166669708499,
551
+ "lon": 80.27916036970848
552
+ }
553
+ },
554
+ "rating": 4.5,
555
+ "user_rating_count": 9780,
556
+ "maps_url": "https://maps.google.com/?cid=326711951594524721&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
557
+ },
558
+ {
559
+ "name": "Government Museum Chennai",
560
+ "address": "Pantheon Rd, Egmore, Chennai, Tamil Nadu 600008",
561
+ "latitude": 13.069764099999999,
562
+ "longitude": 80.2570356,
563
+ "bounding_box": {
564
+ "north_east": {
565
+ "lat": 13.071094980291502,
566
+ "lon": 80.25840153029151
567
+ },
568
+ "south_west": {
569
+ "lat": 13.068397019708497,
570
+ "lon": 80.2557035697085
571
+ }
572
+ },
573
+ "rating": 4.3,
574
+ "user_rating_count": 18625,
575
+ "maps_url": "https://maps.google.com/?cid=10738827242996767798&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
576
+ },
577
+ {
578
+ "name": "Victory War Memorial",
579
+ "address": "37FP+96X, Port Trust Officers Quarters, Sathya Nagar, Chennai Port Trust, Chennai, Tamil Nadu 600009",
580
+ "latitude": 13.0734897,
581
+ "longitude": 80.285625,
582
+ "bounding_box": {
583
+ "north_east": {
584
+ "lat": 13.074859480291504,
585
+ "lon": 80.2868239802915
586
+ },
587
+ "south_west": {
588
+ "lat": 13.0721615197085,
589
+ "lon": 80.2841260197085
590
+ }
591
+ },
592
+ "rating": 4.5,
593
+ "user_rating_count": 1415,
594
+ "maps_url": "https://maps.google.com/?cid=4194342415919237682&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
595
+ }
596
+ ]
597
+ },
598
+ "conversation_history": [
599
+ {
600
+ "human": "",
601
+ "ai": {
602
+ "message": "Here are notable places in the selected area (NE: 13.011865, 80.222213 | SW: 13.009167, 80.219515):\n1. Guindy National Park — Rangeguindy, Chennai, Tamil Nadu 600022 — ★ 4.1 (27135 reviews) — Maps: https://maps.google.com/?cid=16909873477740471949&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\n2. AMMA PARK — 167, 63, Kodambakkam Rd, Subramania Salai, Karpaga Vinayaka Nagar, Saidapet, Chennai, Tamil Nadu 600015 — ★ 4.2 (3391 reviews) — Maps: https://maps.google.com/?cid=3851909234074842151&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\n3. Semmozhi Poonga - Chennai, Tamilnadu — Cathedral Rd, opposite American Consulate, Ellaiamman Colony, Teynampet, Chennai, Tamil Nadu 600086 — ★ 4.1 (28482 reviews) — Maps: https://maps.google.com/?cid=9895380879195658203&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\n4. Marina Beach — Marina Beach, Triplicane, Chennai, Tamil Nadu 600005 — ★ 4.4 (21806 reviews) — Maps: https://maps.google.com/?cid=11765186568882202891&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\n5. Jeeva Park — 3/2, Arul Ammal Street, T. Nagar, Chennai, Tamil Nadu 600017 — ★ 4.3 (6389 reviews) — Maps: https://maps.google.com/?cid=11273320818868375015&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\n6. Madras War Cemetery — 257V+JH5, Mount Poonamallee Rd, Ramapuram, Nandambakkam, Chennai, Tamil Nadu 600089 — ★ 4.4 (270 reviews) — Maps: https://maps.google.com/?cid=14746003291783654129&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\n7. Ashok Pillar — Grand Southern Trunk Rd, Zaffarkhanpet, Ashok Nagar, Chennai, Tamil Nadu 600083 — ★ 4.4 (8420 reviews) — Maps: https://maps.google.com/?cid=8848595929871765267&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\n8. Vivekananda House — Kamaraj Salai, VIVEKANANDA HOUSE, Marina Beach Road, Neelam Basha Dargapuram, Triplicane, Chennai, Tamil Nadu 600005 — ★ 4.5 (9780 reviews) — Maps: https://maps.google.com/?cid=326711951594524721&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\n9. Government Museum Chennai — Pantheon Rd, Egmore, Chennai, Tamil Nadu 600008 — ★ 4.3 (18625 reviews) — Maps: https://maps.google.com/?cid=10738827242996767798&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\n10. Victory War Memorial — 37FP+96X, Port Trust Officers Quarters, Sathya Nagar, Chennai Port Trust, Chennai, Tamil Nadu 600009 — ★ 4.5 (1415 reviews) — Maps: https://maps.google.com/?cid=4194342415919237682&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA",
603
+ "places": [
604
+ {
605
+ "name": "Guindy National Park",
606
+ "address": "Rangeguindy, Chennai, Tamil Nadu 600022",
607
+ "latitude": 13.0049251,
608
+ "longitude": 80.2378725,
609
+ "bounding_box": {
610
+ "north_east": {
611
+ "lat": 13.006023130291501,
612
+ "lon": 80.2397574802915
613
+ },
614
+ "south_west": {
615
+ "lat": 13.003325169708496,
616
+ "lon": 80.2370595197085
617
+ }
618
+ },
619
+ "rating": 4.1,
620
+ "user_rating_count": 27135,
621
+ "maps_url": "https://maps.google.com/?cid=16909873477740471949&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
622
+ },
623
+ {
624
+ "name": "AMMA PARK",
625
+ "address": "167, 63, Kodambakkam Rd, Subramania Salai, Karpaga Vinayaka Nagar, Saidapet, Chennai, Tamil Nadu 600015",
626
+ "latitude": 13.026311399999999,
627
+ "longitude": 80.219393,
628
+ "bounding_box": {
629
+ "north_east": {
630
+ "lat": 13.027641180291502,
631
+ "lon": 80.2209456802915
632
+ },
633
+ "south_west": {
634
+ "lat": 13.024943219708497,
635
+ "lon": 80.2182477197085
636
+ }
637
+ },
638
+ "rating": 4.2,
639
+ "user_rating_count": 3391,
640
+ "maps_url": "https://maps.google.com/?cid=3851909234074842151&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
641
+ },
642
+ {
643
+ "name": "Semmozhi Poonga - Chennai, Tamilnadu",
644
+ "address": "Cathedral Rd, opposite American Consulate, Ellaiamman Colony, Teynampet, Chennai, Tamil Nadu 600086",
645
+ "latitude": 13.050537100000001,
646
+ "longitude": 80.2514128,
647
+ "bounding_box": {
648
+ "north_east": {
649
+ "lat": 13.051588030291501,
650
+ "lon": 80.2534814302915
651
+ },
652
+ "south_west": {
653
+ "lat": 13.048890069708497,
654
+ "lon": 80.2507834697085
655
+ }
656
+ },
657
+ "rating": 4.1,
658
+ "user_rating_count": 28482,
659
+ "maps_url": "https://maps.google.com/?cid=9895380879195658203&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
660
+ },
661
+ {
662
+ "name": "Marina Beach",
663
+ "address": "Marina Beach, Triplicane, Chennai, Tamil Nadu 600005",
664
+ "latitude": 13.0471263,
665
+ "longitude": 80.2824339,
666
+ "bounding_box": {
667
+ "north_east": {
668
+ "lat": 13.048588330291503,
669
+ "lon": 80.28301168029151
670
+ },
671
+ "south_west": {
672
+ "lat": 13.045890369708498,
673
+ "lon": 80.28031371970849
674
+ }
675
+ },
676
+ "rating": 4.4,
677
+ "user_rating_count": 21806,
678
+ "maps_url": "https://maps.google.com/?cid=11765186568882202891&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
679
+ },
680
+ {
681
+ "name": "Jeeva Park",
682
+ "address": "3/2, Arul Ammal Street, T. Nagar, Chennai, Tamil Nadu 600017",
683
+ "latitude": 13.0439662,
684
+ "longitude": 80.2377935,
685
+ "bounding_box": {
686
+ "north_east": {
687
+ "lat": 13.045231480291502,
688
+ "lon": 80.2391895802915
689
+ },
690
+ "south_west": {
691
+ "lat": 13.042533519708497,
692
+ "lon": 80.23649161970849
693
+ }
694
+ },
695
+ "rating": 4.3,
696
+ "user_rating_count": 6389,
697
+ "maps_url": "https://maps.google.com/?cid=11273320818868375015&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
698
+ },
699
+ {
700
+ "name": "Madras War Cemetery",
701
+ "address": "257V+JH5, Mount Poonamallee Rd, Ramapuram, Nandambakkam, Chennai, Tamil Nadu 600089",
702
+ "latitude": 13.0140107,
703
+ "longitude": 80.1939804,
704
+ "bounding_box": {
705
+ "north_east": {
706
+ "lat": 13.015330230291502,
707
+ "lon": 80.19528418029151
708
+ },
709
+ "south_west": {
710
+ "lat": 13.012632269708497,
711
+ "lon": 80.1925862197085
712
+ }
713
+ },
714
+ "rating": 4.4,
715
+ "user_rating_count": 270,
716
+ "maps_url": "https://maps.google.com/?cid=14746003291783654129&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
717
+ },
718
+ {
719
+ "name": "Ashok Pillar",
720
+ "address": "Grand Southern Trunk Rd, Zaffarkhanpet, Ashok Nagar, Chennai, Tamil Nadu 600083",
721
+ "latitude": 13.0348542,
722
+ "longitude": 80.21216869999999,
723
+ "bounding_box": {
724
+ "north_east": {
725
+ "lat": 13.036210630291501,
726
+ "lon": 80.2135662302915
727
+ },
728
+ "south_west": {
729
+ "lat": 13.033512669708497,
730
+ "lon": 80.21086826970848
731
+ }
732
+ },
733
+ "rating": 4.4,
734
+ "user_rating_count": 8420,
735
+ "maps_url": "https://maps.google.com/?cid=8848595929871765267&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
736
+ },
737
+ {
738
+ "name": "Vivekananda House",
739
+ "address": "Kamaraj Salai, VIVEKANANDA HOUSE, Marina Beach Road, Neelam Basha Dargapuram, Triplicane, Chennai, Tamil Nadu 600005",
740
+ "latitude": 13.049467499999999,
741
+ "longitude": 80.2803374,
742
+ "bounding_box": {
743
+ "north_east": {
744
+ "lat": 13.050864630291503,
745
+ "lon": 80.2818583302915
746
+ },
747
+ "south_west": {
748
+ "lat": 13.048166669708499,
749
+ "lon": 80.27916036970848
750
+ }
751
+ },
752
+ "rating": 4.5,
753
+ "user_rating_count": 9780,
754
+ "maps_url": "https://maps.google.com/?cid=326711951594524721&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
755
+ },
756
+ {
757
+ "name": "Government Museum Chennai",
758
+ "address": "Pantheon Rd, Egmore, Chennai, Tamil Nadu 600008",
759
+ "latitude": 13.069764099999999,
760
+ "longitude": 80.2570356,
761
+ "bounding_box": {
762
+ "north_east": {
763
+ "lat": 13.071094980291502,
764
+ "lon": 80.25840153029151
765
+ },
766
+ "south_west": {
767
+ "lat": 13.068397019708497,
768
+ "lon": 80.2557035697085
769
+ }
770
+ },
771
+ "rating": 4.3,
772
+ "user_rating_count": 18625,
773
+ "maps_url": "https://maps.google.com/?cid=10738827242996767798&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
774
+ },
775
+ {
776
+ "name": "Victory War Memorial",
777
+ "address": "37FP+96X, Port Trust Officers Quarters, Sathya Nagar, Chennai Port Trust, Chennai, Tamil Nadu 600009",
778
+ "latitude": 13.0734897,
779
+ "longitude": 80.285625,
780
+ "bounding_box": {
781
+ "north_east": {
782
+ "lat": 13.074859480291504,
783
+ "lon": 80.2868239802915
784
+ },
785
+ "south_west": {
786
+ "lat": 13.0721615197085,
787
+ "lon": 80.2841260197085
788
+ }
789
+ },
790
+ "rating": 4.5,
791
+ "user_rating_count": 1415,
792
+ "maps_url": "https://maps.google.com/?cid=4194342415919237682&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
793
+ }
794
+ ]
795
+ }
796
+ }
797
+ ]
798
+ }
Dockerfile ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Base image
2
+ FROM python:3.10-slim
3
+
4
+ # Set environment variables
5
+ ENV PYTHONDONTWRITEBYTECODE 1
6
+ ENV PYTHONUNBUFFERED 1
7
+
8
+ # Set working directory
9
+ WORKDIR /app
10
+
11
+ # Install dependencies
12
+ COPY requirements.txt /app/
13
+ RUN pip install --upgrade pip && pip install -r requirements.txt
14
+
15
+ # Copy project files
16
+ COPY . /app/
17
+
18
+ # Expose port (use Hugging Face $PORT or fallback to 7860)
19
+ EXPOSE 7860
20
+
21
+ # Start server (use $PORT dynamically)
22
+ CMD uvicorn api.app:app --host 0.0.0.0 --port ${PORT:-7860}
README.md ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Talk2map
3
+ emoji: 🏃
4
+ colorFrom: yellow
5
+ colorTo: indigo
6
+ sdk: docker
7
+ pinned: false
8
+ ---
9
+
10
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
11
+
12
+ # Talk2Map 🗺️🤖
13
+
14
+ **Talk2Map** is a conversational microservice that lets you ask about places naturally.
15
+ It returns **location details, coordinates, bounding box**, and maintains a **conversation history** for smooth human-like interactions.
16
+
17
+ ---
18
+
19
+ ## ✨ Features
20
+
21
+ * Natural language queries (e.g., *“best hotel in Chennai”*)
22
+ * Returns **place details**: name, address, latitude & longitude
23
+ * Returns **bounding box (square coordinates)** of a location/building
24
+ * Maintains **conversation history** with human/AI messages
25
+ * Provides both structured data + natural **agent reply**
26
+ * REST API microservice (Python FastAPI / Node Express ready)
27
+
28
+ ---
29
+
30
+ ## 📡 API Usage
31
+
32
+ ### Request
33
+
34
+ Send your query with **conversation history**:
35
+
36
+ ```json
37
+ {
38
+ "user_input": "best 2 hotel in chennai",
39
+ "conversation_history": [
40
+ {
41
+ "human": "hello",
42
+ "ai": "hello sir"
43
+ }
44
+ ]
45
+ }
46
+ ```
47
+
48
+ ---
49
+
50
+ ### Response
51
+
52
+ Talk2Map replies with both **natural text** and updated **conversation history**:
53
+
54
+ ```json
55
+ {
56
+ "agent_reply": "The best hotel I found in Chennai is Taj Coromandel, located at 37 Mahatma Gandhi Road, Nungambakkam. Its coordinates are latitude 13.061 and longitude 80.251.",
57
+ "conversation_history": [
58
+ {
59
+ "human": "hello",
60
+ "ai": "hello sir"
61
+ },
62
+ {
63
+ "human": "best hotel in Chennai",
64
+ "ai": "The best hotel I found in Chennai is Taj Coromandel, located at 37 Mahatma Gandhi Road, Nungambakkam. Its coordinates are latitude 13.061 and longitude 80.251."
65
+ }
66
+ ]
67
+ }
68
+ ```
69
+
70
+ ---
71
+
72
+ ### Extended Response with Location Data
73
+
74
+ Optionally, you can also include **location details** + **bounding box** in the response:
75
+
76
+ ```json
77
+ {
78
+ "agent_reply": {
79
+ "message": "1. ITC Grand Chola, a Luxury Collection Hotel, Chennai — 63, Mount Rd, Little Mount, Guindy, Chennai, Tamil Nadu 600032 (4.7 ★, 41868 Reviews, Maps URL)\nlat,lng: 13.010613, 80.2206015\nSW: (13.009167, 80.219515), NE: (13.011865, 80.222213)\n\n2. The Leela Palace Chennai - Seaside Modern Palace Hotel — Adyar Sea Face, Leela Palace Rd, MRC Nagar, Raja Annamalai Puram, Chennai, Tamil Nadu 600028 (4.6 ★, 15413 Reviews, Maps URL)\nlat,lng: 13.017048, 80.2736566\nSW: (13.016065, 80.271977), NE: (13.018762, 80.274675)",
80
+ "places": [
81
+ {
82
+ "name": "ITC Grand Chola, a Luxury Collection Hotel, Chennai",
83
+ "address": "63, Mount Rd, Little Mount, Guindy, Chennai, Tamil Nadu 600032",
84
+ "latitude": 13.010613,
85
+ "longitude": 80.2206015,
86
+ "bounding_box": {
87
+ "north_east": {
88
+ "lat": 13.011865130291502,
89
+ "lon": 80.2222132802915
90
+ },
91
+ "south_west": {
92
+ "lat": 13.009167169708498,
93
+ "lon": 80.21951531970849
94
+ }
95
+ },
96
+ "rating": 4.7,
97
+ "user_rating_count": 41868,
98
+ "maps_url": "https://maps.google.com/?cid=17494736093121177155&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
99
+ },
100
+ {
101
+ "name": "The Leela Palace Chennai - Seaside Modern Palace Hotel",
102
+ "address": "Adyar Sea Face, Leela Palace Rd, MRC Nagar, Raja Annamalai Puram, Chennai, Tamil Nadu 600028",
103
+ "latitude": 13.017048,
104
+ "longitude": 80.2736566,
105
+ "bounding_box": {
106
+ "north_east": {
107
+ "lat": 13.018762480291501,
108
+ "lon": 80.2746746802915
109
+ },
110
+ "south_west": {
111
+ "lat": 13.016064519708497,
112
+ "lon": 80.27197671970849
113
+ }
114
+ },
115
+ "rating": 4.6,
116
+ "user_rating_count": 15413,
117
+ "maps_url": "https://maps.google.com/?cid=7374804035710576015&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
118
+ }
119
+ ]
120
+ },
121
+ "conversation_history": [
122
+ {
123
+ "human": "hello",
124
+ "ai": "hello sir"
125
+ },
126
+ {
127
+ "human": "best 2 hotel in chennai",
128
+ "ai": {
129
+ "message": "1. ITC Grand Chola, a Luxury Collection Hotel, Chennai — 63, Mount Rd, Little Mount, Guindy, Chennai, Tamil Nadu 600032 (4.7 ★, 41868 Reviews, Maps URL)\nlat,lng: 13.010613, 80.2206015\nSW: (13.009167, 80.219515), NE: (13.011865, 80.222213)\n\n2. The Leela Palace Chennai - Seaside Modern Palace Hotel — Adyar Sea Face, Leela Palace Rd, MRC Nagar, Raja Annamalai Puram, Chennai, Tamil Nadu 600028 (4.6 ★, 15413 Reviews, Maps URL)\nlat,lng: 13.017048, 80.2736566\nSW: (13.016065, 80.271977), NE: (13.018762, 80.274675)",
130
+ "places": [
131
+ {
132
+ "name": "ITC Grand Chola, a Luxury Collection Hotel, Chennai",
133
+ "address": "63, Mount Rd, Little Mount, Guindy, Chennai, Tamil Nadu 600032",
134
+ "latitude": 13.010613,
135
+ "longitude": 80.2206015,
136
+ "bounding_box": {
137
+ "north_east": {
138
+ "lat": 13.011865130291502,
139
+ "lon": 80.2222132802915
140
+ },
141
+ "south_west": {
142
+ "lat": 13.009167169708498,
143
+ "lon": 80.21951531970849
144
+ }
145
+ },
146
+ "rating": 4.7,
147
+ "user_rating_count": 41868,
148
+ "maps_url": "https://maps.google.com/?cid=17494736093121177155&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
149
+ },
150
+ {
151
+ "name": "The Leela Palace Chennai - Seaside Modern Palace Hotel",
152
+ "address": "Adyar Sea Face, Leela Palace Rd, MRC Nagar, Raja Annamalai Puram, Chennai, Tamil Nadu 600028",
153
+ "latitude": 13.017048,
154
+ "longitude": 80.2736566,
155
+ "bounding_box": {
156
+ "north_east": {
157
+ "lat": 13.018762480291501,
158
+ "lon": 80.2746746802915
159
+ },
160
+ "south_west": {
161
+ "lat": 13.016064519708497,
162
+ "lon": 80.27197671970849
163
+ }
164
+ },
165
+ "rating": 4.6,
166
+ "user_rating_count": 15413,
167
+ "maps_url": "https://maps.google.com/?cid=7374804035710576015&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA"
168
+ }
169
+ ]
170
+ }
171
+ }
172
+ ]
173
+ }
174
+ ```
175
+
176
+ ---
177
+
178
+ ## 🛠 Tech Stack
179
+
180
+ * **Python + FastAPI**
181
+ * **Geocoding APIs** (Google Maps)
182
+
183
+
184
+
185
+
186
+
187
+
Talk2Map.postman_collection.json ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "info": {
3
+ "name": "Talk2Map API",
4
+ "_postman_id": "a5f3f9f0-9e1e-47aa-9f5c-1f0c1a1e0001",
5
+ "description": "Postman collection for Talk2Map (MapMate) API including bbox-only chat flow.",
6
+ "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
7
+ },
8
+ "item": [
9
+ {
10
+ "name": "Health",
11
+ "request": {
12
+ "method": "GET",
13
+ "header": [],
14
+ "url": {
15
+ "raw": "{{baseUrl}}/health",
16
+ "host": [
17
+ "{{baseUrl}}"
18
+ ],
19
+ "path": [
20
+ "health"
21
+ ]
22
+ }
23
+ },
24
+ "response": [
25
+ {
26
+ "name": "200 OK",
27
+ "originalRequest": {
28
+ "method": "GET",
29
+ "header": [],
30
+ "url": {
31
+ "raw": "{{baseUrl}}/health",
32
+ "host": [
33
+ "{{baseUrl}}"
34
+ ],
35
+ "path": [
36
+ "health"
37
+ ]
38
+ }
39
+ },
40
+ "status": "OK",
41
+ "code": 200,
42
+ "_postman_previewlanguage": "json",
43
+ "header": [
44
+ {
45
+ "key": "Content-Type",
46
+ "value": "application/json"
47
+ }
48
+ ],
49
+ "body": "{\n \"status\": \"ok\"\n}"
50
+ }
51
+ ]
52
+ },
53
+ {
54
+ "name": "Chat \u2014 With Places (Hotels in Chennai)",
55
+ "request": {
56
+ "method": "POST",
57
+ "header": [
58
+ {
59
+ "key": "Content-Type",
60
+ "value": "application/json"
61
+ }
62
+ ],
63
+ "body": {
64
+ "mode": "raw",
65
+ "raw": "{\n \"user_input\": \"best 2 hotel in chennai\",\n \"conversation_history\": [\n {\n \"human\": \"hello\",\n \"ai\": \"hello sir\"\n }\n ],\n \"bounding_box\": {\n \"north_east\": {\n \"lat\": 13.2,\n \"lon\": 80.4\n },\n \"south_west\": {\n \"lat\": 12.8,\n \"lon\": 80.1\n }\n }\n}"
66
+ },
67
+ "url": {
68
+ "raw": "{{baseUrl}}/chat",
69
+ "host": [
70
+ "{{baseUrl}}"
71
+ ],
72
+ "path": [
73
+ "chat"
74
+ ]
75
+ },
76
+ "description": "Calls /chat and expects places array (top 2 hotels in Chennai)."
77
+ },
78
+ "response": [
79
+ {
80
+ "name": "200 OK (example)",
81
+ "originalRequest": {
82
+ "method": "POST",
83
+ "header": [
84
+ {
85
+ "key": "Content-Type",
86
+ "value": "application/json"
87
+ }
88
+ ],
89
+ "body": {
90
+ "mode": "raw",
91
+ "raw": "{\n \"user_input\": \"best 2 hotel in chennai\",\n \"conversation_history\": [\n {\n \"human\": \"hello\",\n \"ai\": \"hello sir\"\n }\n ],\n \"bounding_box\": {\n \"north_east\": {\n \"lat\": 13.2,\n \"lon\": 80.4\n },\n \"south_west\": {\n \"lat\": 12.8,\n \"lon\": 80.1\n }\n }\n}"
92
+ },
93
+ "url": {
94
+ "raw": "{{baseUrl}}/chat",
95
+ "host": [
96
+ "{{baseUrl}}"
97
+ ],
98
+ "path": [
99
+ "chat"
100
+ ]
101
+ }
102
+ },
103
+ "status": "OK",
104
+ "code": 200,
105
+ "_postman_previewlanguage": "json",
106
+ "header": [
107
+ {
108
+ "key": "Content-Type",
109
+ "value": "application/json"
110
+ }
111
+ ],
112
+ "body": "{\n \"agent_reply\": {\n \"message\": \"1. ITC Grand Chola, a Luxury Collection Hotel, Chennai \\u2014 63, Mount Rd, Little Mount, Guindy, Chennai, Tamil Nadu 600032 (4.7 \\u2605, 41869 Reviews, Maps URL)\\n lat,lng: 13.010613, 80.2206015\\n SW: (13.009167, 80.219515), NE: (13.011865, 80.222213)\\n\\n2. The Leela Palace Chennai - Seaside Modern Palace Hotel \\u2014 Adyar Sea Face, Leela Palace Rd, MRC Nagar, Raja Annamalai Puram, Chennai, Tamil Nadu 600028 (4.6 \\u2605, 15418 Reviews, Maps URL)\\n lat,lng: 13.017048, 80.2736566\\n SW: (13.016065, 80.271977), NE: (13.018762, 80.274675)\",\n \"places\": [\n {\n \"name\": \"ITC Grand Chola, a Luxury Collection Hotel, Chennai\",\n \"address\": \"63, Mount Rd, Little Mount, Guindy, Chennai, Tamil Nadu 600032\",\n \"latitude\": 13.010613,\n \"longitude\": 80.2206015,\n \"bounding_box\": {\n \"north_east\": {\n \"lat\": 13.011865130291502,\n \"lon\": 80.2222132802915\n },\n \"south_west\": {\n \"lat\": 13.009167169708498,\n \"lon\": 80.21951531970849\n }\n },\n \"rating\": 4.7,\n \"user_rating_count\": 41869,\n \"maps_url\": \"https://maps.google.com/?cid=17494736093121177155&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\"\n },\n {\n \"name\": \"The Leela Palace Chennai - Seaside Modern Palace Hotel\",\n \"address\": \"Adyar Sea Face, Leela Palace Rd, MRC Nagar, Raja Annamalai Puram, Chennai, Tamil Nadu 600028\",\n \"latitude\": 13.017048,\n \"longitude\": 80.2736566,\n \"bounding_box\": {\n \"north_east\": {\n \"lat\": 13.018762480291501,\n \"lon\": 80.2746746802915\n },\n \"south_west\": {\n \"lat\": 13.016064519708497,\n \"lon\": 80.27197671970849\n }\n },\n \"rating\": 4.6,\n \"user_rating_count\": 15418,\n \"maps_url\": \"https://maps.google.com/?cid=7374804035710576015&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\"\n }\n ]\n },\n \"conversation_history\": [\n {\n \"human\": \"hello\",\n \"ai\": \"hello sir\"\n },\n {\n \"human\": \"best 2 hotel in chennai\",\n \"ai\": {\n \"message\": \"1. ITC Grand Chola, a Luxury Collection Hotel, Chennai \\u2014 63, Mount Rd, Little Mount, Guindy, Chennai, Tamil Nadu 600032 (4.7 \\u2605, 41869 Reviews, Maps URL)\\n lat,lng: 13.010613, 80.2206015\\n SW: (13.009167, 80.219515), NE: (13.011865, 80.222213)\\n\\n2. The Leela Palace Chennai - Seaside Modern Palace Hotel \\u2014 Adyar Sea Face, Leela Palace Rd, MRC Nagar, Raja Annamalai Puram, Chennai, Tamil Nadu 600028 (4.6 \\u2605, 15418 Reviews, Maps URL)\\n lat,lng: 13.017048, 80.2736566\\n SW: (13.016065, 80.271977), NE: (13.018762, 80.274675)\",\n \"places\": [\n {\n \"name\": \"ITC Grand Chola, a Luxury Collection Hotel, Chennai\",\n \"address\": \"63, Mount Rd, Little Mount, Guindy, Chennai, Tamil Nadu 600032\",\n \"latitude\": 13.010613,\n \"longitude\": 80.2206015,\n \"bounding_box\": {\n \"north_east\": {\n \"lat\": 13.011865130291502,\n \"lon\": 80.2222132802915\n },\n \"south_west\": {\n \"lat\": 13.009167169708498,\n \"lon\": 80.21951531970849\n }\n },\n \"rating\": 4.7,\n \"user_rating_count\": 41869,\n \"maps_url\": \"https://maps.google.com/?cid=17494736093121177155&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\"\n },\n {\n \"name\": \"The Leela Palace Chennai - Seaside Modern Palace Hotel\",\n \"address\": \"Adyar Sea Face, Leela Palace Rd, MRC Nagar, Raja Annamalai Puram, Chennai, Tamil Nadu 600028\",\n \"latitude\": 13.017048,\n \"longitude\": 80.2736566,\n \"bounding_box\": {\n \"north_east\": {\n \"lat\": 13.018762480291501,\n \"lon\": 80.2746746802915\n },\n \"south_west\": {\n \"lat\": 13.016064519708497,\n \"lon\": 80.27197671970849\n }\n },\n \"rating\": 4.6,\n \"user_rating_count\": 15418,\n \"maps_url\": \"https://maps.google.com/?cid=7374804035710576015&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\"\n }\n ]\n }\n }\n ]\n}"
113
+ }
114
+ ]
115
+ },
116
+ {
117
+ "name": "Chat \u2014 No Places (General Knowledge)",
118
+ "request": {
119
+ "method": "POST",
120
+ "header": [
121
+ {
122
+ "key": "Content-Type",
123
+ "value": "application/json"
124
+ }
125
+ ],
126
+ "body": {
127
+ "mode": "raw",
128
+ "raw": "{\n \"user_input\": \"What is the capital of India?\",\n \"conversation_history\": [\n {\n \"human\": \"hello\",\n \"ai\": \"hello sir\"\n }\n ],\n \"bounding_box\": {\n \"north_east\": {\n \"lat\": 28.8,\n \"lon\": 77.5\n },\n \"south_west\": {\n \"lat\": 28.4,\n \"lon\": 77.0\n }\n }\n}"
129
+ },
130
+ "url": {
131
+ "raw": "{{baseUrl}}/chat",
132
+ "host": [
133
+ "{{baseUrl}}"
134
+ ],
135
+ "path": [
136
+ "chat"
137
+ ]
138
+ },
139
+ "description": "Calls /chat for a general question where no Places data is expected."
140
+ },
141
+ "response": [
142
+ {
143
+ "name": "200 OK (example)",
144
+ "originalRequest": {
145
+ "method": "POST",
146
+ "header": [
147
+ {
148
+ "key": "Content-Type",
149
+ "value": "application/json"
150
+ }
151
+ ],
152
+ "body": {
153
+ "mode": "raw",
154
+ "raw": "{\n \"user_input\": \"What is the capital of India?\",\n \"conversation_history\": [\n {\n \"human\": \"hello\",\n \"ai\": \"hello sir\"\n }\n ],\n \"bounding_box\": {\n \"north_east\": {\n \"lat\": 28.8,\n \"lon\": 77.5\n },\n \"south_west\": {\n \"lat\": 28.4,\n \"lon\": 77.0\n }\n }\n}"
155
+ },
156
+ "url": {
157
+ "raw": "{{baseUrl}}/chat",
158
+ "host": [
159
+ "{{baseUrl}}"
160
+ ],
161
+ "path": [
162
+ "chat"
163
+ ]
164
+ }
165
+ },
166
+ "status": "OK",
167
+ "code": 200,
168
+ "_postman_previewlanguage": "json",
169
+ "header": [
170
+ {
171
+ "key": "Content-Type",
172
+ "value": "application/json"
173
+ }
174
+ ],
175
+ "body": "{\n \"agent_reply\": {\n \"message\": \"The capital of India is New Delhi.\",\n \"places\": []\n },\n \"conversation_history\": [\n {\n \"human\": \"hello\",\n \"ai\": \"hello sir\"\n },\n {\n \"human\": \"What is the capital of India?\",\n \"ai\": {\n \"message\": \"The capital of India is New Delhi.\",\n \"places\": []\n }\n }\n ]\n}"
176
+ }
177
+ ]
178
+ },
179
+ {
180
+ "name": "Chat \u2014 Lat/Lng for ITC Grand Chola (contextual)",
181
+ "request": {
182
+ "method": "POST",
183
+ "header": [
184
+ {
185
+ "key": "Content-Type",
186
+ "value": "application/json"
187
+ }
188
+ ],
189
+ "body": {
190
+ "mode": "raw",
191
+ "raw": "{\n \"user_input\": \"give me the lat and lan of ITC Grand Chola\",\n \"conversation_history\": [\n {\n \"human\": \"hello\",\n \"ai\": \"hello sir\"\n },\n {\n \"human\": \"best 2 hotel in chennai\",\n \"ai\": {\n \"message\": \"1. ITC Grand Chola, a Luxury Collection Hotel, Chennai \\u2014 63, Mount Rd, Little Mount, Guindy, Chennai, Tamil Nadu 600032 (4.7 \\u2605, 41869 Reviews, Maps URL)\\n lat,lng: 13.010613, 80.2206015\\n SW: (13.009167, 80.219515), NE: (13.011865, 80.222213)\\n\\n2. The Leela Palace Chennai - Seaside Modern Palace Hotel \\u2014 Adyar Sea Face, Leela Palace Rd, MRC Nagar, Raja Annamalai Puram, Chennai, Tamil Nadu 600028 (4.6 \\u2605, 15418 Reviews, Maps URL)\\n lat,lng: 13.017048, 80.2736566\\n SW: (13.016065, 80.271977), NE: (13.018762, 80.274675)\",\n \"places\": [\n {\n \"name\": \"ITC Grand Chola, a Luxury Collection Hotel, Chennai\",\n \"address\": \"63, Mount Rd, Little Mount, Guindy, Chennai, Tamil Nadu 600032\",\n \"latitude\": 13.010613,\n \"longitude\": 80.2206015,\n \"bounding_box\": {\n \"north_east\": {\n \"lat\": 13.011865130291502,\n \"lon\": 80.2222132802915\n },\n \"south_west\": {\n \"lat\": 13.009167169708498,\n \"lon\": 80.21951531970849\n }\n },\n \"rating\": 4.7,\n \"user_rating_count\": 41869,\n \"maps_url\": \"https://maps.google.com/?cid=17494736093121177155&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\"\n },\n {\n \"name\": \"The Leela Palace Chennai - Seaside Modern Palace Hotel\",\n \"address\": \"Adyar Sea Face, Leela Palace Rd, MRC Nagar, Raja Annamalai Puram, Chennai, Tamil Nadu 600028\",\n \"latitude\": 13.017048,\n \"longitude\": 80.2736566,\n \"bounding_box\": {\n \"north_east\": {\n \"lat\": 13.018762480291501,\n \"lon\": 80.2746746802915\n },\n \"south_west\": {\n \"lat\": 13.016064519708497,\n \"lon\": 80.27197671970849\n }\n },\n \"rating\": 4.6,\n \"user_rating_count\": 15418,\n \"maps_url\": \"https://maps.google.com/?cid=7374804035710576015&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\"\n }\n ]\n }\n }\n ],\n \"bounding_box\": {\n \"north_east\": {\n \"lat\": 13.012,\n \"lon\": 80.225\n },\n \"south_west\": {\n \"lat\": 13.009,\n \"lon\": 80.218\n }\n }\n}"
192
+ },
193
+ "url": {
194
+ "raw": "{{baseUrl}}/chat",
195
+ "host": [
196
+ "{{baseUrl}}"
197
+ ],
198
+ "path": [
199
+ "chat"
200
+ ]
201
+ },
202
+ "description": "Follow-up asking for latitude/longitude using prior context."
203
+ },
204
+ "response": [
205
+ {
206
+ "name": "200 OK (example)",
207
+ "originalRequest": {
208
+ "method": "POST",
209
+ "header": [
210
+ {
211
+ "key": "Content-Type",
212
+ "value": "application/json"
213
+ }
214
+ ],
215
+ "body": {
216
+ "mode": "raw",
217
+ "raw": "{\n \"user_input\": \"give me the lat and lan of ITC Grand Chola\",\n \"conversation_history\": [\n {\n \"human\": \"hello\",\n \"ai\": \"hello sir\"\n },\n {\n \"human\": \"best 2 hotel in chennai\",\n \"ai\": {\n \"message\": \"1. ITC Grand Chola, a Luxury Collection Hotel, Chennai \\u2014 63, Mount Rd, Little Mount, Guindy, Chennai, Tamil Nadu 600032 (4.7 \\u2605, 41869 Reviews, Maps URL)\\n lat,lng: 13.010613, 80.2206015\\n SW: (13.009167, 80.219515), NE: (13.011865, 80.222213)\\n\\n2. The Leela Palace Chennai - Seaside Modern Palace Hotel \\u2014 Adyar Sea Face, Leela Palace Rd, MRC Nagar, Raja Annamalai Puram, Chennai, Tamil Nadu 600028 (4.6 \\u2605, 15418 Reviews, Maps URL)\\n lat,lng: 13.017048, 80.2736566\\n SW: (13.016065, 80.271977), NE: (13.018762, 80.274675)\",\n \"places\": [\n {\n \"name\": \"ITC Grand Chola, a Luxury Collection Hotel, Chennai\",\n \"address\": \"63, Mount Rd, Little Mount, Guindy, Chennai, Tamil Nadu 600032\",\n \"latitude\": 13.010613,\n \"longitude\": 80.2206015,\n \"bounding_box\": {\n \"north_east\": {\n \"lat\": 13.011865130291502,\n \"lon\": 80.2222132802915\n },\n \"south_west\": {\n \"lat\": 13.009167169708498,\n \"lon\": 80.21951531970849\n }\n },\n \"rating\": 4.7,\n \"user_rating_count\": 41869,\n \"maps_url\": \"https://maps.google.com/?cid=17494736093121177155&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\"\n },\n {\n \"name\": \"The Leela Palace Chennai - Seaside Modern Palace Hotel\",\n \"address\": \"Adyar Sea Face, Leela Palace Rd, MRC Nagar, Raja Annamalai Puram, Chennai, Tamil Nadu 600028\",\n \"latitude\": 13.017048,\n \"longitude\": 80.2736566,\n \"bounding_box\": {\n \"north_east\": {\n \"lat\": 13.018762480291501,\n \"lon\": 80.2746746802915\n },\n \"south_west\": {\n \"lat\": 13.016064519708497,\n \"lon\": 80.27197671970849\n }\n },\n \"rating\": 4.6,\n \"user_rating_count\": 15418,\n \"maps_url\": \"https://maps.google.com/?cid=7374804035710576015&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\"\n }\n ]\n }\n }\n ]\n}"
218
+ },
219
+ "url": {
220
+ "raw": "{{baseUrl}}/chat",
221
+ "host": [
222
+ "{{baseUrl}}"
223
+ ],
224
+ "path": [
225
+ "chat"
226
+ ]
227
+ }
228
+ },
229
+ "status": "OK",
230
+ "code": 200,
231
+ "_postman_previewlanguage": "json",
232
+ "header": [
233
+ {
234
+ "key": "Content-Type",
235
+ "value": "application/json"
236
+ }
237
+ ],
238
+ "body": "{\n \"agent_reply\": {\n \"message\": \"lat,lng: 13.010613, 80.2206015\",\n \"places\": [\n {\n \"name\": \"ITC Grand Chola, a Luxury Collection Hotel, Chennai\",\n \"address\": \"63, Mount Rd, Little Mount, Guindy, Chennai, Tamil Nadu 600032\",\n \"latitude\": 13.010613,\n \"longitude\": 80.2206015,\n \"bounding_box\": {\n \"north_east\": {\n \"lat\": 13.011865130291502,\n \"lon\": 80.2222132802915\n },\n \"south_west\": {\n \"lat\": 13.009167169708498,\n \"lon\": 80.21951531970849\n }\n },\n \"rating\": 4.7,\n \"user_rating_count\": 41869,\n \"maps_url\": \"https://maps.google.com/?cid=17494736093121177155&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\"\n }\n ]\n },\n \"conversation_history\": [\n {\n \"human\": \"hello\",\n \"ai\": \"hello sir\"\n },\n {\n \"human\": \"best 2 hotel in chennai\",\n \"ai\": {\n \"message\": \"1. ITC Grand Chola, a Luxury Collection Hotel, Chennai \\u2014 63, Mount Rd, Little Mount, Guindy, Chennai, Tamil Nadu 600032 (4.7 \\u2605, 41868 Reviews, Maps URL)\\nlat,lng: 13.010613, 80.2206015\\nSW: (13.009167, 80.219515), NE: (13.011865, 80.222213)\\n\\n2. The Leela Palace Chennai - Seaside Modern Palace Hotel \\u2014 Adyar Sea Face, Leela Palace Rd, MRC Nagar, Raja Annamalai Puram, Chennai, Tamil Nadu 600028 (4.6 \\u2605, 15413 Reviews, Maps URL)\\nlat,lng: 13.017048, 80.2736566\\nSW: (13.016065, 80.271977), NE: (13.018762, 80.274675)\",\n \"places\": [\n {\n \"name\": \"ITC Grand Chola, a Luxury Collection Hotel, Chennai\",\n \"address\": \"63, Mount Rd, Little Mount, Guindy, Chennai, Tamil Nadu 600032\",\n \"latitude\": 13.010613,\n \"longitude\": 80.2206015,\n \"bounding_box\": {\n \"north_east\": {\n \"lat\": 13.011865130291502,\n \"lon\": 80.2222132802915\n },\n \"south_west\": {\n \"lat\": 13.009167169708498,\n \"lon\": 80.21951531970849\n }\n },\n \"rating\": 4.7,\n \"user_rating_count\": 41868,\n \"maps_url\": \"https://maps.google.com/?cid=17494736093121177155&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\"\n },\n {\n \"name\": \"The Leela Palace Chennai - Seaside Modern Palace Hotel\",\n \"address\": \"Adyar Sea Face, Leela Palace Rd, MRC Nagar, Raja Annamalai Puram, Chennai, Tamil Nadu 600028\",\n \"latitude\": 13.017048,\n \"longitude\": 80.2736566,\n \"bounding_box\": {\n \"north_east\": {\n \"lat\": 13.018762480291501,\n \"lon\": 80.2746746802915\n },\n \"south_west\": {\n \"lat\": 13.016064519708497,\n \"lon\": 80.27197671970849\n }\n },\n \"rating\": 4.6,\n \"user_rating_count\": 15413,\n \"maps_url\": \"https://maps.google.com/?cid=7374804035710576015&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\"\n }\n ]\n }\n },\n {\n \"human\": \"give me the lat and lan of ITC Grand Chola\",\n \"ai\": {\n \"message\": \"lat,lng: 13.010613, 80.2206015\",\n \"places\": [\n {\n \"name\": \"ITC Grand Chola, a Luxury Collection Hotel, Chennai\",\n \"address\": \"63, Mount Rd, Little Mount, Guindy, Chennai, Tamil Nadu 600032\",\n \"latitude\": 13.010613,\n \"longitude\": 80.2206015,\n \"bounding_box\": {\n \"north_east\": {\n \"lat\": 13.011865130291502,\n \"lon\": 80.2222132802915\n },\n \"south_west\": {\n \"lat\": 13.009167169708498,\n \"lon\": 80.21951531970849\n }\n },\n \"rating\": 4.7,\n \"user_rating_count\": 41869,\n \"maps_url\": \"https://maps.google.com/?cid=17494736093121177155&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\"\n }\n ]\n }\n }\n ]\n}"
239
+ }
240
+ ]
241
+ },
242
+ {
243
+ "name": "Chat \u2014 Bounding Box Only (Places via maptool)",
244
+ "request": {
245
+ "method": "POST",
246
+ "header": [
247
+ {
248
+ "key": "Content-Type",
249
+ "value": "application/json"
250
+ },
251
+ {
252
+ "key": "X-Top-N",
253
+ "value": "10",
254
+ "description": "Optional cap for results"
255
+ }
256
+ ],
257
+ "body": {
258
+ "mode": "raw",
259
+ "raw": "{\n \"user_input\": \"\",\n \"conversation_history\": [],\n \"bounding_box\": {\n \"north_east\": {\n \"lat\": 13.011865130291502,\n \"lon\": 80.2222132802915\n },\n \"south_west\": {\n \"lat\": 13.009167169708498,\n \"lon\": 80.21951531970849\n }\n }\n}"
260
+ },
261
+ "url": {
262
+ "raw": "{{baseUrl}}/chat",
263
+ "host": [
264
+ "{{baseUrl}}"
265
+ ],
266
+ "path": [
267
+ "chat"
268
+ ]
269
+ },
270
+ "description": "Calls /chat with empty user_input and a bounding_box object. The backend skips the agent and queries Google Places via maptool only."
271
+ },
272
+ "response": [
273
+ {
274
+ "name": "200 OK (example)",
275
+ "originalRequest": {
276
+ "method": "POST",
277
+ "header": [
278
+ {
279
+ "key": "Content-Type",
280
+ "value": "application/json"
281
+ },
282
+ {
283
+ "key": "X-Top-N",
284
+ "value": "10",
285
+ "description": "Optional cap for results"
286
+ }
287
+ ],
288
+ "body": {
289
+ "mode": "raw",
290
+ "raw": "{\n \"user_input\": \"\",\n \"conversation_history\": [],\n \"bounding_box\": {\n \"north_east\": {\n \"lat\": 13.011865130291502,\n \"lon\": 80.2222132802915\n },\n \"south_west\": {\n \"lat\": 13.009167169708498,\n \"lon\": 80.21951531970849\n }\n }\n}"
291
+ },
292
+ "url": {
293
+ "raw": "{{baseUrl}}/chat",
294
+ "host": [
295
+ "{{baseUrl}}"
296
+ ],
297
+ "path": [
298
+ "chat"
299
+ ]
300
+ }
301
+ },
302
+ "status": "OK",
303
+ "code": 200,
304
+ "_postman_previewlanguage": "json",
305
+ "header": [
306
+ {
307
+ "key": "Content-Type",
308
+ "value": "application/json"
309
+ }
310
+ ],
311
+ "body": "{\n \"agent_reply\": {\n \"message\": \"Here are notable places in the selected area (NE: 13.011865, 80.222213 | SW: 13.009167, 80.219515):\\n1. ITC Grand Chola, a Luxury Collection Hotel, Chennai \\u2014 63, Mount Rd, Little Mount, Guindy, Chennai, Tamil Nadu 600032 \\u2014 \\u2605 4.7 (41869 reviews) \\u2014 Maps: https://maps.google.com/?cid=17494736093121177155&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\",\n \"places\": [\n {\n \"name\": \"ITC Grand Chola, a Luxury Collection Hotel, Chennai\",\n \"address\": \"63, Mount Rd, Little Mount, Guindy, Chennai, Tamil Nadu 600032\",\n \"latitude\": 13.010613,\n \"longitude\": 80.2206015,\n \"bounding_box\": {\n \"north_east\": {\n \"lat\": 13.011865130291502,\n \"lon\": 80.2222132802915\n },\n \"south_west\": {\n \"lat\": 13.009167169708498,\n \"lon\": 80.21951531970849\n }\n },\n \"rating\": 4.7,\n \"user_rating_count\": 41869,\n \"maps_url\": \"https://maps.google.com/?cid=17494736093121177155&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\"\n },\n {\n \"name\": \"The Leela Palace Chennai - Seaside Modern Palace Hotel\",\n \"address\": \"Adyar Sea Face, Leela Palace Rd, MRC Nagar, Raja Annamalai Puram, Chennai, Tamil Nadu 600028\",\n \"latitude\": 13.017048,\n \"longitude\": 80.2736566,\n \"bounding_box\": {\n \"north_east\": {\n \"lat\": 13.018762480291501,\n \"lon\": 80.2746746802915\n },\n \"south_west\": {\n \"lat\": 13.016064519708497,\n \"lon\": 80.27197671970849\n }\n },\n \"rating\": 4.6,\n \"user_rating_count\": 15418,\n \"maps_url\": \"https://maps.google.com/?cid=7374804035710576015&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\"\n }\n ]\n },\n \"conversation_history\": [\n {\n \"human\": \"\",\n \"ai\": {\n \"message\": \"Here are notable places in the selected area (NE: 13.011865, 80.222213 | SW: 13.009167, 80.219515):\\n1. ITC Grand Chola, a Luxury Collection Hotel, Chennai \\u2014 63, Mount Rd, Little Mount, Guindy, Chennai, Tamil Nadu 600032 \\u2014 \\u2605 4.7 (41869 reviews) \\u2014 Maps: https://maps.google.com/?cid=17494736093121177155&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\",\n \"places\": [\n {\n \"name\": \"ITC Grand Chola, a Luxury Collection Hotel, Chennai\",\n \"address\": \"63, Mount Rd, Little Mount, Guindy, Chennai, Tamil Nadu 600032\",\n \"latitude\": 13.010613,\n \"longitude\": 80.2206015,\n \"bounding_box\": {\n \"north_east\": {\n \"lat\": 13.011865130291502,\n \"lon\": 80.2222132802915\n },\n \"south_west\": {\n \"lat\": 13.009167169708498,\n \"lon\": 80.21951531970849\n }\n },\n \"rating\": 4.7,\n \"user_rating_count\": 41869,\n \"maps_url\": \"https://maps.google.com/?cid=17494736093121177155&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\"\n },\n {\n \"name\": \"The Leela Palace Chennai - Seaside Modern Palace Hotel\",\n \"address\": \"Adyar Sea Face, Leela Palace Rd, MRC Nagar, Raja Annamalai Puram, Chennai, Tamil Nadu 600028\",\n \"latitude\": 13.017048,\n \"longitude\": 80.2736566,\n \"bounding_box\": {\n \"north_east\": {\n \"lat\": 13.018762480291501,\n \"lon\": 80.2746746802915\n },\n \"south_west\": {\n \"lat\": 13.016064519708497,\n \"lon\": 80.27197671970849\n }\n },\n \"rating\": 4.6,\n \"user_rating_count\": 15418,\n \"maps_url\": \"https://maps.google.com/?cid=7374804035710576015&g_mp=Cidnb29nbGUubWFwcy5wbGFjZXMudjEuUGxhY2VzLlNlYXJjaFRleHQQABgEIAA\"\n }\n ]\n }\n }\n ]\n}"
312
+ }
313
+ ]
314
+ }
315
+ ],
316
+ "variable": [
317
+ {
318
+ "key": "baseUrl",
319
+ "value": "https://neurostack-in-talk2map-test.hf.space"
320
+ }
321
+ ]
322
+ }
Talk2Map_API_Documentation.md ADDED
@@ -0,0 +1,422 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # Talk2Map (MapMate) API — Full Documentation
3
+
4
+ _Last updated: 2025-08-29 12:48 _
5
+
6
+ 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.
7
+
8
+ > **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`.
9
+
10
+ ---
11
+
12
+ ## Base URL
13
+
14
+ - Local development: `http://localhost:8000`
15
+ - All examples below use a Postman variable `{baseUrl}` that defaults to `http://localhost:8000`.
16
+
17
+ CORS is enabled broadly for development (`*`).
18
+
19
+ ---
20
+
21
+ ## Authentication
22
+
23
+ None required for local development. Google Places API credentials are read from the server environment (`PLACES_API_KEY`).
24
+
25
+ ---
26
+
27
+ ## Version
28
+
29
+ - API: `v1.0.0` (FastAPI title: **Talk2Map API**)
30
+
31
+ ---
32
+
33
+ ## Endpoints
34
+
35
+ ### 1) Health
36
+
37
+ **GET** `{baseUrl}/health`
38
+
39
+ Simple health check.
40
+
41
+ **Response**
42
+ ```json
43
+ { "status": "ok" }
44
+ ```
45
+
46
+ **cURL**
47
+ ```bash
48
+ curl -s {baseUrl}/health
49
+ ```
50
+
51
+ ---
52
+
53
+ ### 2) Chat
54
+
55
+ **POST** `{baseUrl}/chat`
56
+
57
+ Drives the conversation flow. Depending on input, the server either:
58
+ 1) Runs the LLM agent with tools **(normal path)**, or
59
+ 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)**.
60
+
61
+ #### Headers
62
+
63
+ - `Content-Type: application/json`
64
+ - _Optional_ for bbox-only: `X-Top-N: <int>` — a client hint for maximum results (server may cap/ignore).
65
+
66
+ #### Request Body — Schema
67
+
68
+ ```ts
69
+ interface LatLon { lat?: number; lon?: number; }
70
+
71
+ interface BoundingBox {
72
+ north_east?: LatLon;
73
+ south_west?: LatLon;
74
+ }
75
+
76
+ interface Turn {
77
+ human: string;
78
+ ai?: string | Record<string, any>;
79
+ }
80
+
81
+ interface ChatRequest {
82
+ user_input: string; // free-text user message (may be empty in bbox-only flow)
83
+ conversation_history?: Turn[]; // prior chat turns (optional)
84
+ bounding_box?: BoundingBox; // when present (and user_input empty) triggers bbox-only places lookup
85
+ }
86
+ ```
87
+
88
+ #### Response Body — Schema
89
+
90
+ ```ts
91
+ interface Place {
92
+ name?: string;
93
+ address?: string;
94
+ latitude?: number;
95
+ longitude?: number;
96
+ bounding_box?: {
97
+ north_east?: LatLon;
98
+ south_west?: LatLon;
99
+ };
100
+ rating?: number;
101
+ user_rating_count?: number;
102
+ maps_url?: string;
103
+ }
104
+
105
+ interface AgentReply {
106
+ message: string; // user-friendly text, may include Markdown
107
+ places: Place[]; // structured places (may be empty list)
108
+ }
109
+
110
+ interface ChatResponse {
111
+ agent_reply: AgentReply;
112
+ conversation_history: Turn[]; // the server-augmented history (source of truth)
113
+ }
114
+ ```
115
+
116
+ > 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.
117
+
118
+ ---
119
+
120
+ ## Usage Patterns & Examples
121
+
122
+ ### A) Normal Agent Call with Places (e.g., “best 2 hotels in Chennai”)
123
+
124
+ **Request**
125
+ ```http
126
+ POST {baseUrl}/chat
127
+ Content-Type: application/json
128
+
129
+ {
130
+ "user_input": "best 2 hotel in chennai",
131
+ "conversation_history": [
132
+ {"human": "hello", "ai": "hello sir"}
133
+ ]
134
+ }
135
+ ```
136
+
137
+ **Response (example)** — contains a Markdown `message` and a structured `places` array (2 hotels).
138
+ ```json
139
+ {
140
+ "agent_reply": {
141
+ "message": "1. ITC Grand Chola...",
142
+ "places": [ { "...": "see schema above" } ]
143
+ },
144
+ "conversation_history": [ /* prior + this turn */ ]
145
+ }
146
+ ```
147
+
148
+ **cURL**
149
+ ```bash
150
+ curl -s -X POST {baseUrl}/chat -H "Content-Type: application/json" -d '{
151
+ "user_input": "best 2 hotel in chennai",
152
+ "conversation_history": [{"human":"hello","ai":"hello sir"}]
153
+ }'
154
+ ```
155
+
156
+ ---
157
+
158
+ ### B) General Knowledge (no Places)
159
+
160
+ **Request**
161
+ ```http
162
+ POST {baseUrl}/chat
163
+ Content-Type: application/json
164
+
165
+ {
166
+ "user_input": "What is the capital of India?",
167
+ "conversation_history": [
168
+ {"human": "hello", "ai": "hello sir"}
169
+ ]
170
+ }
171
+ ```
172
+
173
+ **Response (example)** — `places` is an empty list.
174
+ ```json
175
+ {
176
+ "agent_reply": { "message": "The capital of India is New Delhi.", "places": [] },
177
+ "conversation_history": [ /* prior + this turn */ ]
178
+ }
179
+ ```
180
+
181
+ **cURL**
182
+ ```bash
183
+ curl -s -X POST {baseUrl}/chat -H "Content-Type: application/json" -d '{
184
+ "user_input":"What is the capital of India?",
185
+ "conversation_history":[{"human":"hello","ai":"hello sir"}]
186
+ }'
187
+ ```
188
+
189
+ ---
190
+
191
+ ### C) Contextual Follow-up: Lat/Lng for a Place mentioned earlier
192
+
193
+ **Request**
194
+ ```http
195
+ POST {baseUrl}/chat
196
+ Content-Type: application/json
197
+
198
+ {
199
+ "user_input": "give me the lat and lan of ITC Grand Chola",
200
+ "conversation_history": [
201
+ { "human": "hello", "ai": "hello sir" },
202
+ { "human": "best 2 hotel in chennai", "ai": { "message": "...", "places": [ /* two hotels */ ] } }
203
+ ]
204
+ }
205
+ ```
206
+
207
+ **Response (example)** — agent uses context to answer succinctly; may include a 1‑element `places` for the matched item.
208
+ ```json
209
+ {
210
+ "agent_reply": {
211
+ "message": "lat,lng: 13.010613, 80.2206015",
212
+ "places": [ { "...": "place details" } ]
213
+ },
214
+ "conversation_history": [ /* prior + this turn */ ]
215
+ }
216
+ ```
217
+
218
+ **cURL**
219
+ ```bash
220
+ curl -s -X POST {baseUrl}/chat -H "Content-Type: application/json" -d '{
221
+ "user_input":"give me the lat and lan of ITC Grand Chola",
222
+ "conversation_history":[
223
+ {"human":"hello","ai":"hello sir"},
224
+ {"human":"best 2 hotel in chennai","ai":{"message":"...","places":[/*...*/]}}
225
+ ]
226
+ }'
227
+ ```
228
+
229
+ ---
230
+
231
+ ### D) Bounding Box Only — Places via `maptool.py` (Agent Skipped)
232
+
233
+ **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`.
234
+
235
+ **Request**
236
+ ```http
237
+ POST {baseUrl}/chat
238
+ Content-Type: application/json
239
+ X-Top-N: 10 # optional hint
240
+
241
+ {
242
+ "user_input": "",
243
+ "conversation_history": [],
244
+ "bounding_box": {
245
+ "north_east": { "lat": 13.011865130291502, "lon": 80.2222132802915 },
246
+ "south_west": { "lat": 13.009167169708498, "lon": 80.21951531970849 }
247
+ }
248
+ }
249
+ ```
250
+
251
+ **Response (example)**
252
+ ```json
253
+ {
254
+ "agent_reply": {
255
+ "message": "Here are notable places in the selected area (NE: 13.011865, 80.222213 | SW: 13.009167, 80.219515):\n1. ...",
256
+ "places": [ { "...": "see schema" } ]
257
+ },
258
+ "conversation_history": [
259
+ { "human": "", "ai": { "message": "Here are notable places...", "places": [ /* ... */ ] } }
260
+ ]
261
+ }
262
+ ```
263
+
264
+ **cURL**
265
+ ```bash
266
+ curl -s -X POST {baseUrl}/chat -H "Content-Type: application/json" -H "X-Top-N: 10" -d '{
267
+ "user_input": "",
268
+ "conversation_history": [],
269
+ "bounding_box": {
270
+ "north_east": { "lat": 13.011865130291502, "lon": 80.2222132802915 },
271
+ "south_west": { "lat": 13.009167169708498, "lon": 80.21951531970849 }
272
+ }
273
+ }'
274
+ ```
275
+
276
+ ---
277
+
278
+ ## Data Models (Server-side)
279
+
280
+ ### Pydantic Models (`agent/models.py`)
281
+
282
+ ```py
283
+ class LLMMessage(BaseModel):
284
+ message: str # final markdown text
285
+
286
+ class LatLon(BaseModel):
287
+ lat: Optional[float] = None
288
+ lon: Optional[float] = None
289
+
290
+ class BoundingBox(BaseModel):
291
+ north_east: Optional[LatLon] = None
292
+ south_west: Optional[LatLon] = None
293
+
294
+ class Place(BaseModel):
295
+ name: Optional[str] = None
296
+ address: Optional[str] = None
297
+ latitude: Optional[float] = None
298
+ longitude: Optional[float] = None
299
+ bounding_box: Optional[BoundingBox] = None
300
+ rating: Optional[float] = None
301
+ user_rating_count: Optional[int] = None
302
+ maps_url: Optional[str] = None
303
+
304
+ class AgentReply(BaseModel):
305
+ message: str
306
+ places: List[Place] = Field(default_factory=list)
307
+
308
+ class Turn(BaseModel):
309
+ human: str
310
+ ai: Optional[Union[str, Dict[str, Any]]] = None
311
+
312
+ class ChatRequest(BaseModel):
313
+ user_input: str
314
+ conversation_history: List[Turn] = Field(default_factory=list)
315
+ bounding_box: Optional[BoundingBox] = None
316
+
317
+ class ChatResponse(BaseModel):
318
+ agent_reply: AgentReply
319
+ conversation_history: List[Turn]
320
+ ```
321
+
322
+ ---
323
+
324
+ ## Google Places Integration
325
+
326
+ - **Endpoint used** (server-to-Google): `https://places.googleapis.com/v1/places:searchText`
327
+ - **Headers**: `X-Goog-Api-Key: $PLACES_API_KEY`, `X-Goog-FieldMask: places.displayName, ..., nextPageToken`
328
+ - **Default query** for bbox-only: `"points of interest"` (configurable)
329
+ - **locationBias rectangle** is built from the provided `bounding_box`:
330
+ ```json
331
+ {
332
+ "locationBias": {
333
+ "rectangle": {
334
+ "low": { "latitude": SW.lat, "longitude": SW.lon },
335
+ "high": { "latitude": NE.lat, "longitude": NE.lon }
336
+ }
337
+ }
338
+ }
339
+ ```
340
+ - Pagination via `nextPageToken` is handled internally until `top_n` results or no more pages.
341
+
342
+ Returned place fields are mapped to the API’s `Place` schema.
343
+
344
+ ---
345
+
346
+ ## Status Codes
347
+
348
+ - `200 OK` — Successful response.
349
+ - `400 Bad Request` — Invalid JSON / missing required fields / invalid bbox shape.
350
+ - `500 Internal Server Error` — Uncaught server error (including upstream Places errors).
351
+
352
+ On Places errors, the server raises a 5xx with the upstream message included for debugging.
353
+
354
+ ---
355
+
356
+ ## Headers & Conventions
357
+
358
+ - `Content-Type: application/json` for all POSTs.
359
+ - Optional `X-Top-N` for bbox-only calls (hint only).
360
+ - Responses use UTF‑8 and may contain Markdown in `agent_reply.message`.
361
+
362
+ ---
363
+
364
+ ## Rate Limiting & Quotas
365
+
366
+ - No server-side rate limiter in this reference implementation.
367
+ - Upstream Google Places usage is limited by your `PLACES_API_KEY` quota.
368
+
369
+ ---
370
+
371
+ ## Error Examples
372
+
373
+ **Invalid bbox values**
374
+ ```json
375
+ { "detail": "SW.lat must be <= NE.lat; SW.lon must be <= NE.lon" }
376
+ ```
377
+
378
+ **Places API error**
379
+ ```json
380
+ { "detail": "Places API error 403: {\"error\": {\"message\": \"API key not valid\"}}" }
381
+ ```
382
+
383
+ ---
384
+
385
+ ## Environment Variables
386
+
387
+ - `PLACES_API_KEY` _(required)_: Google Places (Places API v1) key.
388
+ - Optional `.env` usage is supported by `dotenv` for local development.
389
+
390
+ ---
391
+
392
+ ## Postman
393
+
394
+ A ready-to-import Postman collection is available:
395
+
396
+ - **[Talk2Map.postman_collection.json](sandbox:/mnt/data/Talk2Map.postman_collection.json)**
397
+
398
+ Import it into Postman and set `{baseUrl}` as needed.
399
+
400
+ ---
401
+
402
+ ## Changelog
403
+
404
+ - **v1.0.0**
405
+ - Added **bbox-only** flow: if `bounding_box` present and `user_input` empty → **skip agent**, query Google Places directly.
406
+ - Unified response shape via `agent_reply: { message, places }`.
407
+ - Documented schemas and examples for all common flows.
408
+
409
+ ---
410
+
411
+ ## Notes for Frontend Integrators
412
+
413
+ - Render `agent_reply.message` as **Markdown** (sanitize HTML).
414
+ - 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.
415
+ - For bbox-only UX, collect `NE` and `SW` coordinates and submit with empty `user_input`.
416
+ - The sample UI adds a **Bounding Box Search** form that triggers the bbox-only flow.
417
+
418
+ ---
419
+
420
+ ## License
421
+
422
+ This API documentation is provided as-is for internal integration and testing.
WORKFLOW_GUIDE.md ADDED
@@ -0,0 +1,400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Talk2Map CI/CD Workflow Guide
2
+
3
+ This document explains the complete CI/CD workflow for the Talk2Map FastAPI project, including feature development, testing, and deployment processes.
4
+
5
+ ## 🔄 Workflow Overview
6
+
7
+ The workflow implements a **fully manual-controlled feature → staging → main → production** pipeline where:
8
+
9
+ - 👥 **Developer manually triggers all actions** - No automatic testing on feature branches
10
+ - 🧪 **Tests run only when developer initiates** - Complete manual control
11
+ - 🚀 **Manual promotion at every stage** - Developers decide when to advance
12
+
13
+ **Key principle: Developers have complete control over when testing and merging happens.**
14
+
15
+ ```
16
+ graph TD
17
+ A[Developer creates feature/name branch] --> B[Push code to feature branch]
18
+ B --> C[👥 Developer manually triggers feature testing]
19
+ C --> D[Manual Feature Testing workflow]
20
+ D --> E[Run tests on feature branch]
21
+ E --> F{Tests pass?}
22
+ F -->|No| G[❌ Fix tests and retry]
23
+ F -->|Yes| H[Check conflicts with staging]
24
+ H --> I{Conflicts detected?}
25
+ I -->|Yes| J[❌ Resolve conflicts and retry]
26
+ I -->|No| K[✅ Merge to staging]
27
+ K --> L[Staging CI triggers automatically]
28
+ L --> M[Run tests on staging]
29
+ M --> N{Tests pass?}
30
+ N -->|No| O[❌ Create failure issue]
31
+ N -->|Yes| P[✅ Deploy to HF Test Space]
32
+ P --> Q[API Testing workflow triggers]
33
+ Q --> R[👥 Developer manually promotes to main]
34
+ R --> S[Manual Promotion workflow]
35
+ S --> T[Run tests on staging again]
36
+ T --> U{Tests pass?}
37
+ U -->|No| V[❌ Block promotion]
38
+ U -->|Yes| W[✅ Merge to main]
39
+ W --> X[Deploy to Production triggers]
40
+ X --> Y[Run final tests on main]
41
+ Y --> Z{Tests pass?}
42
+ Z -->|No| AA[❌ Block deployment]
43
+ Z -->|Yes| BB[🚀 Deploy to HF Production]
44
+ ```
45
+
46
+ ## 🚫 **STRICT BLOCKING POLICY**
47
+
48
+ **The workflow implements a zero-tolerance policy for failures:**
49
+
50
+ ### ❌ What Blocks Merges:
51
+ 1. **Test Failures** - Any failing test in `pytest -v`
52
+ 2. **Merge Conflicts** - Any conflicts detected between branches
53
+ 3. **Workflow Errors** - Any step failure in the CI pipeline
54
+
55
+ ### 🚨 What Happens When Blocked:
56
+ 1. **NO MERGE OCCURS** - The workflow stops immediately
57
+ 2. **GitHub Issue Created** - Detailed alert with:
58
+ - Exact failure reason
59
+ - Step-by-step resolution instructions
60
+ - Links to relevant logs and resources
61
+ 3. **Labels Applied** - `merge-blocked`, `urgent` for easy filtering
62
+ 4. **Developer Notification** - Issue assignment and team alerts
63
+
64
+ ### ✅ Merge Only Happens When:
65
+ - ✅ **ALL tests pass** (`pytest -v` returns 0)
66
+ - ✅ **NO conflicts detected** (clean merge possible)
67
+ - ✅ **Workflow completes successfully** (all steps green)
68
+
69
+ **Remember: Better to block a merge than break the pipeline!**
70
+
71
+ ---
72
+
73
+ ## 📈 Workflow Components
74
+
75
+ ### 1. Manual Feature Testing and Staging Merge (`manual-feature-merge.yml`)
76
+ **Triggers:** Manual workflow dispatch only
77
+ **Purpose:** Test feature branch and merge to staging when developer is ready
78
+
79
+ **Manual Process:**
80
+ 1. Developer triggers workflow with feature branch name
81
+ 2. Run tests on specified feature branch using `pytest -v`
82
+ 3. Check for merge conflicts with staging branch
83
+ 4. **ONLY if BOTH conditions are met:**
84
+ - ✅ All feature tests pass
85
+ - ✅ No merge conflicts detected
86
+
87
+ **THEN:** Merge feature to staging
88
+
89
+ 5. **If ANY condition fails:**
90
+ - ❌ **NO MERGE OCCURS**
91
+ - 🚨 GitHub issue created with detailed failure information
92
+ - 🚫 Developer must fix issues and retry
93
+
94
+ **Key Features:**
95
+ - ✅ **Complete manual control** - No automatic testing on feature branches
96
+ - ✅ Pre-merge conflict detection
97
+ - ✅ Test validation before merge
98
+ - ✅ Detailed success/failure notifications
99
+
100
+ ### 2. Staging Branch CI (`staging-ci.yml`)
101
+ **Triggers:** Push to `staging` branch (after manual merge)
102
+ **Purpose:** Test and deploy staging after developer merges
103
+
104
+ **Process:**
105
+ 1. **Tests run AFTER merge to staging**
106
+ 2. If tests pass:
107
+ - Deploy to HuggingFace test space
108
+ - Create success notification
109
+ - Mark as "ready for promotion"
110
+ 3. If tests fail:
111
+ - Create failure alert
112
+ - Block further progression
113
+
114
+ **Key Features:**
115
+ - ✅ **Post-merge testing** - tests run after code is in staging
116
+ - ✅ Automatic test space deployment
117
+ - ✅ Clear success/failure notifications
118
+ - ✅ Ready-for-promotion status
119
+ ### 3. API Endpoint Testing (`api-testing.yml`)
120
+ **Triggers:** After successful Staging Branch CI
121
+ **Purpose:** Test deployed API endpoints on HuggingFace
122
+
123
+ **Process:**
124
+ 1. Wait for HuggingFace deployment (configurable wait time)
125
+ 2. Validate Postman collection
126
+ 3. Run Newman tests against deployed API
127
+ 4. Generate HTML test reports
128
+ 5. Create success/failure notifications
129
+
130
+ **Environments:**
131
+ - **Test:** `https://neurostack-in-talk2map-test.hf.space`
132
+ - **Production:** `https://neurostack-in-talk2map-prod.hf.space`
133
+
134
+ **Manual Trigger Options:**
135
+ - Custom base URL
136
+ - Environment selection (test/production)
137
+ - Custom wait time
138
+
139
+ ### 4. Manual Staging to Main Promotion (`promote.yml`)
140
+ **Triggers:** Manual workflow dispatch only
141
+ **Purpose:** Manually promote staging to main when developer is ready
142
+
143
+ **Manual Process:**
144
+ 1. Developer triggers the workflow manually
145
+ 2. Run tests on staging branch again
146
+ 3. Check for merge conflicts with main branch
147
+ 4. **ONLY if BOTH conditions are met:**
148
+ - ✅ All staging tests pass
149
+ - ✅ No merge conflicts with main
150
+
151
+ **THEN:** Merge staging to main and trigger production deployment
152
+
153
+ 5. **If ANY condition fails:**
154
+ - ❌ **NO PROMOTION OCCURS**
155
+ - 🚨 Detailed GitHub issue created with resolution steps
156
+ - 🚫 Production deployment blocked
157
+
158
+ **Manual Control:**
159
+ - ✅ **Developer decides when to promote** - No automatic promotion
160
+ - ✅ Final validation before production
161
+ - ✅ Conflict detection and blocking
162
+ - ✅ Clear success/failure feedback
163
+
164
+ ### 5. Production Deployment (`sync-to-hf.yml`)
165
+ **Triggers:** After successful staging to main promotion
166
+ **Purpose:** Deploy main branch to production **ONLY with final validation**
167
+
168
+ **Strict Blocking Process:**
169
+ 1. Run final tests on main branch
170
+ 2. **ONLY if tests pass:**
171
+ - ✅ Deploy to HuggingFace production space
172
+ - ✅ Create deployment success notification
173
+
174
+ 3. **If tests fail:**
175
+ - ❌ **NO DEPLOYMENT OCCURS**
176
+ - 🚨 Production deployment blocked
177
+ - 🚫 Create urgent alert for manual intervention
178
+
179
+ **Production Safety:**
180
+ - ✅ **Final gate:** Last chance to catch issues before production
181
+ - ✅ Zero-downtime protection: No broken code reaches production
182
+ - ✅ Emergency procedures documented for failures
183
+ - ✅ Deployment success/failure notifications
184
+
185
+ **Production URL:** `https://neurostack-in-talk2map-prod.hf.space`
186
+
187
+ ### 6. Manual Promotion (`manual-promote.yml`)
188
+ **Purpose:** Emergency manual promotion from staging to main (alternative method)
189
+
190
+ **Use Cases:**
191
+ - Resolve complex merge conflicts manually
192
+ - Emergency deployments
193
+ - Override automatic promotion when needed
194
+
195
+ ## 🚀 Developer Workflow
196
+
197
+ ### Step 1: Create Feature Branch
198
+ ```bash
199
+ # Create and switch to feature branch
200
+ git checkout -b feature/your-feature-name
201
+
202
+ # Make your changes
203
+ # ... code changes ...
204
+
205
+ # Commit and push
206
+ git add .
207
+ git commit -m "Add your feature"
208
+ git push origin feature/your-feature-name
209
+ ```
210
+
211
+ ### Step 2: Manual Feature Testing and Staging Merge
212
+ ```bash
213
+ # When ready to test and merge your feature:
214
+ # Go to GitHub Actions → Manual Feature Testing and Staging Merge → Run workflow
215
+ # Provide:
216
+ # - Feature branch name: feature/your-feature-name
217
+ # - Reason: "Feature ready for staging"
218
+ ```
219
+
220
+ **What happens:**
221
+ 1. **Manual Feature Testing** workflow runs
222
+ 2. Tests execute on your feature branch
223
+ 3. If successful and no conflicts, merges to staging
224
+ 4. **No automatic testing** - only when you trigger it
225
+
226
+ ### Step 3: Staging Validation (Automatic)
227
+ 1. **Staging CI** runs automatically after merge
228
+ 2. Tests execute on the staging branch
229
+ 3. If successful, deploys to HuggingFace test space
230
+ 4. **API Testing** runs against the test deployment
231
+
232
+ ### Step 4: Manual Promotion to Production
233
+ ```bash
234
+ # When ready to go to production:
235
+ # Go to Actions → Manual Staging to Main Promotion → Run workflow
236
+ # Provide reason for promotion
237
+ ```
238
+
239
+ **What happens:**
240
+ 1. **Manual Promotion** workflow runs
241
+ 2. Tests run on staging again
242
+ 3. If successful and no conflicts, promotes to main
243
+ 4. **Production deployment** triggers automatically
244
+
245
+ ### Step 5: Production Deployment (Automatic)
246
+ 1. **Production deployment** runs after main is updated
247
+ 2. Final tests run on main branch
248
+ 3. Main branch deployed to HuggingFace production
249
+ 4. Production API is live
250
+
251
+ ## 🔧 Configuration
252
+
253
+ ### Environment Variables Required
254
+ - `GROQ_API_KEY`: For running tests
255
+ - `HF_TOKEN`: HuggingFace deployment token
256
+ - `GITHUB_TOKEN`: Automatically provided by GitHub
257
+
258
+ ### HuggingFace Spaces
259
+ - **Test Space:** `neurostack-in/talk2map-test`
260
+ - **Production Space:** `neurostack-in/talk2map-prod`
261
+
262
+ ### Test Configuration
263
+ Tests are located in the `tests/` directory:
264
+ - `tests/unit/` - Unit tests
265
+ - `tests/integration/` - Integration tests
266
+ - `tests/e2e/` - End-to-end tests
267
+
268
+ Run tests locally: `pytest -v`
269
+
270
+ ## 🚨 Error Handling & Alerts
271
+
272
+ The workflow creates GitHub Issues for various failure scenarios:
273
+
274
+ ### Merge Conflicts
275
+ - **Title:** "🚨 Merge Conflict Alert: Feature branch X cannot merge to staging"
276
+ - **Content:** Detailed conflict information and resolution steps
277
+ - **Labels:** `merge-conflict`, `urgent`
278
+
279
+ ### Test Failures
280
+ - **Title:** "❌ Feature Branch CI Failed: branch-name"
281
+ - **Content:** Workflow run links and troubleshooting steps
282
+ - **Labels:** `ci-failure`, `urgent`
283
+
284
+ ### API Test Failures
285
+ - **Title:** "❌ API Tests Failed - Environment"
286
+ - **Content:** Test results and debugging information
287
+ - **Labels:** `api-test-failure`, `environment`, `urgent`
288
+
289
+ ### Deployment Issues
290
+ - **Title:** "❌ Production Deployment Failed"
291
+ - **Content:** Deployment logs and recovery steps
292
+ - **Labels:** `deployment-failure`, `production`, `urgent`
293
+
294
+ ## 🎯 Best Practices
295
+
296
+ ### Branch Naming
297
+ - Use `feature/` prefix for all feature branches
298
+ - Example: `feature/add-user-authentication`
299
+ - Example: `feature/fix-map-rendering`
300
+
301
+ ### Commit Messages
302
+ - Use clear, descriptive commit messages
303
+ - Reference issues when applicable
304
+ - Follow conventional commit format when possible
305
+
306
+ ### Testing
307
+ - Run tests locally before pushing: `pytest -v`
308
+ - Ensure all tests pass before creating pull requests
309
+ - Add tests for new features and bug fixes
310
+
311
+ ### Conflict Resolution
312
+ - Pull latest staging changes before starting new features
313
+ - Resolve conflicts promptly when alerts are created
314
+ - Test thoroughly after resolving conflicts
315
+
316
+ ## 🔍 Monitoring & Debugging
317
+
318
+ ### Workflow Status
319
+ - Check GitHub Actions tab for workflow status
320
+ - Review workflow logs for detailed information
321
+ - Monitor GitHub Issues for automated alerts
322
+
323
+ ### API Testing
324
+ - Download HTML test reports from workflow artifacts
325
+ - Use manual API testing workflow for debugging
326
+ - Test both environments (test/production) as needed
327
+
328
+ ### HuggingFace Deployments
329
+ - Check HuggingFace Space logs for deployment issues
330
+ - Verify API accessibility after deployments
331
+ - Monitor space status and performance
332
+
333
+ ## 🆘 Troubleshooting
334
+
335
+ ### Common Issues
336
+
337
+ #### 1. Merge Conflicts
338
+ **Solution:** Follow the commands in the automated GitHub issue
339
+ ```bash
340
+ git checkout feature/your-branch
341
+ git fetch origin
342
+ git merge origin/staging
343
+ # Resolve conflicts manually
344
+ git add .
345
+ git commit -m "Resolve merge conflicts with staging"
346
+ git push origin feature/your-branch
347
+ ```
348
+
349
+ #### 2. Test Failures
350
+ **Solution:** Check workflow logs and fix failing tests
351
+ ```bash
352
+ # Run tests locally
353
+ pytest -v
354
+
355
+ # Fix failing tests
356
+ # Commit and push fixes
357
+ git add .
358
+ git commit -m "Fix failing tests"
359
+ git push origin feature/your-branch
360
+ ```
361
+
362
+ #### 3. API Tests Failing
363
+ **Solution:** Check API accessibility and configuration
364
+ - Verify GROQ_API_KEY is valid
365
+ - Check HuggingFace deployment status
366
+ - Review API logs and error messages
367
+
368
+ #### 4. Deployment Failures
369
+ **Solution:** Check HuggingFace token and space configuration
370
+ - Verify HF_TOKEN secret is valid
371
+ - Check space permissions and settings
372
+ - Review deployment logs
373
+
374
+ ### Manual Overrides
375
+
376
+ #### Manual Promotion
377
+ Use the manual promotion workflow when automatic promotion fails:
378
+ 1. Go to Actions → Manual Promotion (Staging to Main)
379
+ 2. Click "Run workflow"
380
+ 3. Provide reason for manual promotion
381
+ 4. Monitor the workflow execution
382
+
383
+ #### Manual API Testing
384
+ Test specific environments manually:
385
+ 1. Go to Actions → API Endpoint Testing
386
+ 2. Click "Run workflow"
387
+ 3. Select environment (test/production)
388
+ 4. Optionally customize URL and wait time
389
+ 5. Review test results and reports
390
+
391
+ ## 📈 Workflow Metrics
392
+
393
+ The workflows provide comprehensive reporting:
394
+ - ✅ Success/failure notifications
395
+ - 📊 Test coverage reports
396
+ - 🕐 Deployment timing information
397
+ - 📋 Detailed error logs and debugging info
398
+ - 🔗 Direct links to relevant resources
399
+
400
+ All notifications are created as GitHub Issues with appropriate labels for easy filtering and management.
agent/agent_runner.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # agent_runner.py
2
+ import json
3
+ import logging
4
+ from typing import Any, Dict, List, Optional, Union
5
+
6
+ from pydantic import BaseModel, Field
7
+ from langchain_core.messages import SystemMessage, HumanMessage, AIMessage, BaseMessage
8
+ from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
9
+
10
+ from .llm import get_llm
11
+ from .maptool import search_places_tool # Tool object (LangChain)
12
+
13
+ logging.basicConfig(level=logging.INFO)
14
+ log = logging.getLogger("agent.runner")
15
+
16
+ SYSTEM_PROMPT = """You are Talk2Map — a concise trip & local-search assistant.
17
+
18
+ THINK PRIVATELY:
19
+ - First, silently decide whether a places search is truly needed.
20
+ - Normalize the query (strip proximity phrases like "near me/nearby/around here/close by/in my area").
21
+ - If user provided a bounding box via the API, prefer using it as a hard filter. Never alter or invent coordinates.
22
+ - Choose sane defaults: top_n=5 (clamp 1–20), region_code="IN", language_code="en".
23
+ - If the request is not a place search (greetings, self-questions, general knowledge), DO NOT call any tool.
24
+
25
+ CONVERSATION AWARENESS (no external memory; rely only on history in this chat):
26
+ - If the user previously told you their name in this conversation, you may use it.
27
+ - If they ask “what is my name?” and the name is not in the visible history context, say you’re not sure.
28
+
29
+ PLANNING OUTPUT (JSON ONLY):
30
+ Return a single JSON object with keys:
31
+ {
32
+ "should_call_tool": boolean,
33
+ "normalized_query": string | null,
34
+ "top_n": number | null,
35
+ "region_code": string | null,
36
+ "language_code": string | null,
37
+ "strict": boolean | null,
38
+ "require_viewport_fit": boolean | null,
39
+ "use_bbox_from_api": boolean | null,
40
+ "clarification": string | null
41
+ }
42
+
43
+ RULES:
44
+ - If you don't need to call the tool, set should_call_tool=false and put the concise reply in "clarification".
45
+ - If you call the tool, keep explanation out of the plan; the final message will be composed separately.
46
+ - Do NOT include your chain-of-thought or any extra keys.
47
+ """
48
+
49
+ PLANNER_PROMPT = ChatPromptTemplate.from_messages(
50
+ [
51
+ SystemMessage(content=SYSTEM_PROMPT),
52
+ MessagesPlaceholder(variable_name="history"), # ← critical: model sees prior turns
53
+ ("human",
54
+ "User says: {user_text}\n\n"
55
+ "Context:\n- bounding_box_available: {bbox_available}\n"
56
+ "- We already have the exact bounding box from API if available.\n\n"
57
+ "Return ONLY the JSON plan described above."),
58
+ ]
59
+ )
60
+
61
+ class Plan(BaseModel):
62
+ should_call_tool: bool
63
+ normalized_query: Optional[str] = None
64
+ top_n: Optional[int] = Field(default=5, ge=1, le=20)
65
+ region_code: Optional[str] = "IN"
66
+ language_code: Optional[str] = "en"
67
+ strict: Optional[bool] = True
68
+ require_viewport_fit: Optional[bool] = False
69
+ use_bbox_from_api: Optional[bool] = True
70
+ clarification: Optional[str] = None
71
+
72
+
73
+ def _coerce_json(s: str) -> Optional[Dict[str, Any]]:
74
+ if not s:
75
+ return None
76
+ raw = s.strip()
77
+ if raw.startswith("```"):
78
+ raw = raw.strip("`")
79
+ parts = raw.split("\n", 1)
80
+ raw = parts[1] if len(parts) > 1 and not parts[0].lstrip().startswith("{") else raw
81
+ start = raw.find("{")
82
+ end = raw.rfind("}")
83
+ if start == -1 or end == -1 or end <= start:
84
+ return None
85
+ try:
86
+ return json.loads(raw[start : end + 1])
87
+ except Exception:
88
+ return None
89
+
90
+
91
+ def _format_error_message(e: Exception, query: str = "", has_bbox: bool = False) -> str:
92
+ log.exception("Agent error: %s", e)
93
+
94
+ # More specific error messages based on context
95
+ if has_bbox and query:
96
+ return f"No {query} found in the specified area. This area might not have any {query} or try expanding the search boundary."
97
+ elif has_bbox:
98
+ return "No places found in the specified area. Try expanding the search boundary or searching in a different location."
99
+ elif query:
100
+ return f"No {query} found in this region. This area might not have any {query} or try searching in a nearby city."
101
+ else:
102
+ return "No matching places found. Try widening the area or share a clearer query."
103
+
104
+
105
+ def _coerce_history(history_msgs: Optional[List]) -> List[BaseMessage]:
106
+ """
107
+ Accepts:
108
+ - List[BaseMessage]
109
+ - List[{'role': 'user'|'assistant'|'system', 'content': str}]
110
+ - List[('user'|'assistant'|'system', str)]
111
+ """
112
+ if not history_msgs:
113
+ return []
114
+ out: List[BaseMessage] = []
115
+ for m in history_msgs:
116
+ if isinstance(m, BaseMessage):
117
+ out.append(m)
118
+ continue
119
+ role, content = None, None
120
+ if isinstance(m, dict):
121
+ role, content = m.get("role"), m.get("content")
122
+ elif isinstance(m, tuple) and len(m) >= 2:
123
+ role, content = m[0], m[1]
124
+ if not content:
125
+ continue
126
+ role = (role or "").lower()
127
+ if role in ("user", "human"):
128
+ out.append(HumanMessage(content=str(content)))
129
+ elif role in ("assistant", "ai", "bot"):
130
+ out.append(AIMessage(content=str(content)))
131
+ elif role == "system":
132
+ out.append(SystemMessage(content=str(content)))
133
+ else:
134
+ out.append(HumanMessage(content=str(content)))
135
+ return out
136
+
137
+
138
+ def run_agent(
139
+ user_input: str,
140
+ history_msgs: List,
141
+ bbox: Optional[Dict[str, Dict[str, float]]] = None,
142
+ *,
143
+ enable_name_hint: bool = False, # keep False to test pure LLM recall
144
+ name_hint_value: Optional[str] = None, # optional external memory if you ever want it
145
+ ) -> Dict[str, Optional[str]]:
146
+ """
147
+ Planner → (optional) tool → return {final_text, last_tool_json}
148
+ - final_text: concise message (may be empty; caller can auto-format places)
149
+ - last_tool_json: raw JSON string from search tool (if any)
150
+
151
+ Memory policy:
152
+ - By default, we pass only the conversation history. No hard-coded name or external hint.
153
+ - If enable_name_hint=True and name_hint_value is provided by YOUR app, we add a small system memory line.
154
+ """
155
+ llm = get_llm(temperature=0.15, max_tokens=1024)
156
+
157
+ coerced_history = _coerce_history(history_msgs)
158
+
159
+ # Optional: app-managed sticky memory (off by default)
160
+ if enable_name_hint and name_hint_value:
161
+ coerced_history = [
162
+ SystemMessage(content=f"Memory: The user's name is {name_hint_value}.")
163
+ ] + coerced_history
164
+
165
+ # 1) PLAN
166
+ try:
167
+ plan_text = (PLANNER_PROMPT | llm).invoke(
168
+ {
169
+ "history": coerced_history,
170
+ "user_text": (user_input or "").strip(),
171
+ "bbox_available": bool(bbox),
172
+ }
173
+ )
174
+ plan_obj = plan_text.content if hasattr(plan_text, "content") else str(plan_text)
175
+ plan_dict = _coerce_json(plan_obj) or {}
176
+ plan = Plan(**plan_dict)
177
+ except Exception as e:
178
+ log.exception("Planner LLM failed; falling back. %s", e)
179
+ plan = Plan(
180
+ should_call_tool=False,
181
+ clarification="Please share a city or a map bounding box to search inside.",
182
+ )
183
+
184
+ # 2) Decide action
185
+ if not plan.should_call_tool:
186
+ msg = (plan.clarification or "Please share a city or a map bounding box to search inside.").strip()
187
+ return {"final_text": msg, "last_tool_json": None}
188
+
189
+ # 3) Normalize params
190
+ query = (plan.normalized_query or "").strip()
191
+ if not query:
192
+ return {
193
+ "final_text": "I need a category or search text (e.g., “school”, “cafe”).",
194
+ "last_tool_json": None,
195
+ }
196
+
197
+ top_n = max(1, min(20, int(plan.top_n or 5)))
198
+ region_code = (plan.region_code or "IN").strip()
199
+ language_code = (plan.language_code or "en").strip()
200
+ strict = bool(plan.strict if plan.strict is not None else True)
201
+ require_viewport_fit = bool(plan.require_viewport_fit)
202
+ tool_bbox = bbox if (plan.use_bbox_from_api and bbox) else None
203
+
204
+ # 4) Tool call
205
+ try:
206
+ raw = search_places_tool.invoke(
207
+ {
208
+ "query": query,
209
+ "top_n": top_n,
210
+ "region_code": region_code,
211
+ "language_code": language_code,
212
+ "bounding_box": tool_bbox,
213
+ "strict": strict,
214
+ "require_viewport_fit": require_viewport_fit,
215
+ }
216
+ )
217
+ if not isinstance(raw, str):
218
+ raw = json.dumps(raw, ensure_ascii=False)
219
+
220
+ # Check if the tool returned empty results
221
+ try:
222
+ parsed_results = json.loads(raw) if raw else []
223
+ if isinstance(parsed_results, list) and len(parsed_results) == 0:
224
+ # No places found - return contextual message
225
+ has_bbox = bool(tool_bbox)
226
+ error_msg = _format_error_message(Exception("No results"), query, has_bbox)
227
+ return {"final_text": error_msg, "last_tool_json": raw}
228
+ except json.JSONDecodeError:
229
+ pass # If we can't parse, just return the raw result
230
+
231
+ return {"final_text": "", "last_tool_json": raw}
232
+ except Exception as e:
233
+ has_bbox = bool(tool_bbox)
234
+ return {"final_text": _format_error_message(e, query, has_bbox), "last_tool_json": None}
agent/llm.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # llm.py
2
+ from dotenv import load_dotenv
3
+ from langchain_groq import ChatGroq
4
+
5
+ load_dotenv()
6
+
7
+
8
+ def get_llm(temperature: float = 0.2, max_tokens: int = 8064) -> ChatGroq:
9
+ return ChatGroq(
10
+ model="meta-llama/llama-4-maverick-17b-128e-instruct",
11
+ temperature=temperature,
12
+ max_tokens=max_tokens,
13
+ streaming=False,
14
+ )
agent/maptool.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # maptool.py
2
+ import os
3
+ import json
4
+ import time
5
+ import logging
6
+ from typing import List, Dict, Optional, Literal
7
+
8
+ import requests
9
+ from dotenv import load_dotenv
10
+ from langchain_core.tools import tool
11
+
12
+ load_dotenv()
13
+ PLACES_API_KEY = os.getenv("PLACES_API_KEY")
14
+ PLACES_SEARCH_URL = "https://places.googleapis.com/v1/places:searchText"
15
+
16
+ log = logging.getLogger(__name__)
17
+ logging.basicConfig(level=logging.INFO)
18
+
19
+ # ──────────────────────────────────────────────────────────────────────────────
20
+ # Helpers: geometry & filtering
21
+ # ──────────────────────────────────────────────────────────────────────────────
22
+ def _inside_box(lat: float, lng: float, sw: Dict, ne: Dict) -> bool:
23
+ if lat is None or lng is None:
24
+ return False
25
+
26
+ south, west = float(sw["lat"]), float(sw["lon"])
27
+ north, east = float(ne["lat"]), float(ne["lon"])
28
+
29
+ if south > north: # auto-fix latitude order if caller flipped
30
+ south, north = north, south
31
+
32
+ in_lat = (south <= lat <= north)
33
+
34
+ # Normal case or antimeridian
35
+ if west <= east:
36
+ in_lng = (west <= lng <= east)
37
+ else:
38
+ in_lng = (lng >= west) or (lng <= east)
39
+
40
+ return in_lat and in_lng
41
+
42
+
43
+ def _viewport_inside_box(vp: Dict, sw: Dict, ne: Dict) -> bool:
44
+ if not vp:
45
+ return False
46
+ low = vp.get("low", {})
47
+ high = vp.get("high", {})
48
+ return _inside_box(low.get("latitude"), low.get("longitude"), sw, ne) and _inside_box(
49
+ high.get("latitude"), high.get("longitude"), sw, ne
50
+ )
51
+
52
+
53
+ def _to_bounding_box_from_viewport(vp: Optional[Dict]) -> Optional[Dict]:
54
+ if not vp:
55
+ return None
56
+ low = vp.get("low")
57
+ high = vp.get("high")
58
+ if not low or not high:
59
+ return None
60
+ return {
61
+ "north_east": {"lat": high.get("latitude"), "lon": high.get("longitude")},
62
+ "south_west": {"lat": low.get("latitude"), "lon": low.get("longitude")},
63
+ }
64
+
65
+
66
+ def _valid_bbox(bbox: Optional[Dict]) -> Optional[Dict]:
67
+ if not bbox:
68
+ return None
69
+ try:
70
+ ne = bbox.get("north_east") or {}
71
+ sw = bbox.get("south_west") or {}
72
+ ne_lat, ne_lon = float(ne["lat"]), float(ne["lon"])
73
+ sw_lat, sw_lon = float(sw["lat"]), float(sw["lon"])
74
+ # Basic sanity (Google requires lat in [-90, 90], lon in [-180, 180])
75
+ for v in (ne_lat, sw_lat):
76
+ if v < -90 or v > 90:
77
+ return None
78
+ for v in (ne_lon, sw_lon):
79
+ if v < -180 or v > 180:
80
+ return None
81
+ return {"north_east": {"lat": ne_lat, "lon": ne_lon}, "south_west": {"lat": sw_lat, "lon": sw_lon}}
82
+ except Exception:
83
+ return None
84
+
85
+
86
+ # ──────────────────────────────────────────────────────────────────────────────
87
+ # HTTP with retries
88
+ # ──────────────────────────────────────────────────────────────────────────────
89
+ def _places_request(*, query: str, page_token: Optional[str], page_size: int,
90
+ region_code: str, language_code: str, location_bias: Optional[Dict] = None) -> Dict:
91
+ if not PLACES_API_KEY:
92
+ raise RuntimeError("PLACES_API_KEY is not set in environment.")
93
+
94
+ headers = {
95
+ "Content-Type": "application/json",
96
+ "X-Goog-Api-Key": PLACES_API_KEY,
97
+ # Request only needed fields (faster/cheaper)
98
+ "X-Goog-FieldMask": (
99
+ "places.displayName,places.formattedAddress,places.location,places.viewport,"
100
+ "places.rating,places.userRatingCount,places.priceLevel,places.googleMapsUri,nextPageToken"
101
+ ),
102
+ }
103
+
104
+ payload = {
105
+ "textQuery": query,
106
+ "pageSize": int(page_size),
107
+ "regionCode": region_code,
108
+ "languageCode": language_code,
109
+ }
110
+ if page_token:
111
+ payload["pageToken"] = page_token
112
+ if location_bias:
113
+ payload["locationBias"] = location_bias
114
+
115
+ # lightweight exponential backoff on 429/5xx
116
+ for attempt in range(4):
117
+ resp = requests.post(PLACES_SEARCH_URL, headers=headers, json=payload, timeout=30)
118
+ if resp.status_code == 200:
119
+ data = resp.json()
120
+ if "error" in data:
121
+ raise RuntimeError(f"Places API error: {data['error'].get('message','Unknown error')}")
122
+ return data
123
+
124
+ if resp.status_code in (429, 500, 502, 503, 504):
125
+ sleep_s = 0.8 * (2 ** attempt)
126
+ time.sleep(sleep_s)
127
+ continue
128
+
129
+ # Other errors → raise with body for logs
130
+ raise RuntimeError(f"Places API error {resp.status_code}: {resp.text}")
131
+
132
+ raise RuntimeError("Places API: exhausted retries.")
133
+
134
+
135
+ # ──────────────────────────────────────────────────────────────────────────────
136
+ # Core search + optional strict filtering
137
+ # ──────────────────────────────────────────────────────────────────────────────
138
+ def search_places(
139
+ *,
140
+ query: str,
141
+ top_n: int = 5,
142
+ region_code: str = "IN",
143
+ language_code: str = "en",
144
+ location_bias: Optional[Dict] = None,
145
+ bbox: Optional[Dict] = None, # {"north_east":{"lat","lon"},"south_west":{"lat","lon"}}
146
+ strict_mode: Optional[Literal["point", "viewport"]] = None,
147
+ ) -> List[Dict]:
148
+ results: List[Dict] = []
149
+ token: Optional[str] = None
150
+
151
+ # Clamp & sanitize
152
+ top_n = max(1, min(20, int(top_n)))
153
+ query = (query or "").strip()
154
+ if not query:
155
+ return []
156
+
157
+ # Bias only if valid bbox is provided
158
+ location_bias = None
159
+ valid = _valid_bbox(bbox)
160
+ if valid:
161
+ ne, sw = valid["north_east"], valid["south_west"]
162
+ location_bias = {"rectangle": {"low": {"latitude": sw["lat"], "longitude": sw["lon"]},
163
+ "high": {"latitude": ne["lat"], "longitude": ne["lon"]}}}
164
+
165
+ while len(results) < top_n:
166
+ page_size = min(20, top_n - len(results))
167
+ page = _places_request(
168
+ query=query,
169
+ page_token=token,
170
+ page_size=page_size,
171
+ region_code=region_code,
172
+ language_code=language_code,
173
+ location_bias=location_bias,
174
+ )
175
+
176
+ for p in page.get("places", []) or []:
177
+ display_name = (p.get("displayName") or {}).get("text")
178
+ address = p.get("formattedAddress")
179
+ loc = p.get("location") or {}
180
+ lat = loc.get("latitude")
181
+ lng = loc.get("longitude")
182
+ viewport = p.get("viewport")
183
+
184
+ # Strict filtering if requested
185
+ if valid and strict_mode:
186
+ ne = valid["north_east"]
187
+ sw = valid["south_west"]
188
+ if strict_mode == "point" and not _inside_box(lat, lng, sw, ne):
189
+ continue
190
+ if strict_mode == "viewport" and not _viewport_inside_box(viewport, sw, ne):
191
+ continue
192
+
193
+ results.append(
194
+ {
195
+ "name": display_name,
196
+ "address": address,
197
+ "lat": lat,
198
+ "lng": lng,
199
+ "viewport": viewport,
200
+ "bounding_box": _to_bounding_box_from_viewport(viewport),
201
+ "rating": p.get("rating"),
202
+ "userRatingCount": p.get("userRatingCount"),
203
+ "priceLevel": p.get("priceLevel"),
204
+ "mapsUrl": p.get("googleMapsUri"),
205
+ }
206
+ )
207
+ if len(results) >= top_n:
208
+ break
209
+
210
+ token = page.get("nextPageToken")
211
+ if not token or not page.get("places"):
212
+ break
213
+
214
+ return results
215
+
216
+
217
+ @tool("search_places", return_direct=True)
218
+ def search_places_tool(
219
+ query: str,
220
+ top_n: int = 5,
221
+ region_code: str = "IN",
222
+ language_code: str = "en",
223
+ bounding_box: Optional[Dict] = None,
224
+ strict: bool = True,
225
+ require_viewport_fit: bool = False,
226
+ ) -> str:
227
+ """
228
+ Search for places using Places API v1 Text Search (New).
229
+
230
+ Args:
231
+ query: Free-text query ("school", "best coffee", "hotels", ...)
232
+ top_n: 1–20
233
+ region_code: CLDR (e.g., "IN")
234
+ language_code: BCP-47 (e.g., "en")
235
+ bounding_box: optional {"north_east":{"lat","lon"},"south_west":{"lat","lon"}}
236
+ strict: True → point-in-rectangle filter
237
+ require_viewport_fit: True → viewport must fully fit in rectangle
238
+
239
+ Returns:
240
+ JSON string of array[Place]
241
+ """
242
+ strict_mode: Optional[Literal["point", "viewport"]] = None
243
+ if require_viewport_fit:
244
+ strict_mode = "viewport"
245
+ elif strict:
246
+ strict_mode = "point"
247
+
248
+ data = search_places(
249
+ query=query,
250
+ top_n=top_n,
251
+ region_code=region_code,
252
+ language_code=language_code,
253
+ location_bias=None, # set inside search_places when bbox is valid
254
+ bbox=bounding_box,
255
+ strict_mode=strict_mode,
256
+ )
257
+ return json.dumps(data, ensure_ascii=False, separators=(",", ":"))
agent/models.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # models.py
2
+ from typing import Optional, List, Dict, Any, Union
3
+ from pydantic import BaseModel, Field
4
+
5
+
6
+ class LLMMessage(BaseModel):
7
+ """Validated final output from the LLM (always Markdown text)."""
8
+
9
+ message: str
10
+
11
+
12
+ class LatLon(BaseModel):
13
+ lat: float
14
+ lon: float
15
+
16
+
17
+ class BoundingBox(BaseModel):
18
+ north_east: LatLon
19
+ south_west: LatLon
20
+
21
+
22
+ class Place(BaseModel):
23
+ name: Optional[str] = None
24
+ address: Optional[str] = None
25
+ latitude: Optional[float] = None
26
+ longitude: Optional[float] = None
27
+ bounding_box: Optional[BoundingBox] = None
28
+ rating: Optional[float] = None
29
+ user_rating_count: Optional[int] = None
30
+ maps_url: Optional[str] = None
31
+
32
+
33
+ class AgentReply(BaseModel):
34
+ message: str
35
+ places: List[Place] = Field(default_factory=list)
36
+
37
+
38
+ class Turn(BaseModel):
39
+ human: str
40
+ ai: Optional[Union[str, Dict[str, Any]]] = None
41
+
42
+
43
+ class ChatRequest(BaseModel):
44
+ user_input: str
45
+ conversation_history: List[Turn] = Field(default_factory=list)
46
+ bounding_box: BoundingBox
47
+
48
+
49
+ class ChatResponse(BaseModel):
50
+ agent_reply: AgentReply
51
+ conversation_history: List[Turn]
api/app.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import re
6
+ from typing import List, Optional
7
+
8
+ from fastapi import FastAPI
9
+ from fastapi.middleware.cors import CORSMiddleware
10
+ from fastapi.responses import HTMLResponse
11
+ import uvicorn
12
+
13
+ from agent.agent_runner import run_agent
14
+ from agent.models import (
15
+ LatLon,
16
+ BoundingBox,
17
+ Place,
18
+ AgentReply,
19
+ Turn,
20
+ ChatRequest,
21
+ ChatResponse,
22
+ )
23
+
24
+ app = FastAPI(title="Talk2Map API", version="1.0.0")
25
+ app.add_middleware(
26
+ CORSMiddleware,
27
+ allow_origins=["*"],
28
+ allow_credentials=True,
29
+ allow_methods=["*"],
30
+ allow_headers=["*"],
31
+ )
32
+
33
+ def _sanitize_text(s: Optional[str]) -> str:
34
+ if not s:
35
+ return ""
36
+ s = re.sub(r"<\|header_start\|>.*?<\|header_end\|>", "", s, flags=re.S | re.I)
37
+ s = re.sub(r"<\|im_start\|>.*?<\|im_end\|>", "", s, flags=re.S | re.I)
38
+ s = re.sub(r"<\|[^>]*\|>", "", s)
39
+ return s.strip()
40
+
41
+ def _looks_like_tool_json(s: Optional[str]) -> bool:
42
+ if not s or not isinstance(s, str):
43
+ return False
44
+ s = s.strip()
45
+ if not s or s[0] not in "[{":
46
+ return False
47
+ try:
48
+ obj = json.loads(s)
49
+ return isinstance(obj, list) and (len(obj) == 0 or isinstance(obj[0], dict))
50
+ except Exception:
51
+ return False
52
+
53
+ def _tool_json_to_places(raw_json: Optional[str]) -> List[Place]:
54
+ if not raw_json:
55
+ return []
56
+ try:
57
+ data = json.loads(raw_json)
58
+ except Exception:
59
+ return []
60
+ if not isinstance(data, list):
61
+ return []
62
+ out: List[Place] = []
63
+ for p in data:
64
+ vp = p.get("viewport") or {}
65
+ low = vp.get("low") or {}
66
+ high = vp.get("high") or {}
67
+ out.append(
68
+ Place(
69
+ name=p.get("name"),
70
+ address=p.get("address"),
71
+ latitude=p.get("lat"),
72
+ longitude=p.get("lng"),
73
+ bounding_box=(
74
+ BoundingBox(
75
+ north_east=LatLon(lat=high.get("latitude"), lon=high.get("longitude")),
76
+ south_west=LatLon(lat=low.get("latitude"), lon=low.get("longitude")),
77
+ )
78
+ if vp
79
+ else None
80
+ ),
81
+ rating=p.get("rating"),
82
+ user_rating_count=p.get("userRatingCount"),
83
+ maps_url=p.get("mapsUrl"),
84
+ )
85
+ )
86
+ return out
87
+
88
+ def _fmt_places_md(places: List[Place]) -> str:
89
+ lines = []
90
+ for i, p in enumerate(places, 1):
91
+ rating = f" (Rating ★ {p.rating}, Reviews {p.user_rating_count})" if p.rating is not None else ""
92
+ url = f" — {p.maps_url}" if p.maps_url else ""
93
+ latlng = f"\nlat,lng: {p.latitude},{p.longitude}"
94
+ box = ""
95
+ if p.bounding_box and p.bounding_box.north_east and p.bounding_box.south_west:
96
+ ne, sw = p.bounding_box.north_east, p.bounding_box.south_west
97
+ box = f"\nSW: ({sw.lat}, {sw.lon}), NE: ({ne.lat}, {ne.lon})"
98
+ lines.append(f"{i}. {p.name} — {p.address}{rating}{url}{latlng}{box}")
99
+ return "\n".join(lines)
100
+
101
+ @app.post("/chat", response_model=ChatResponse)
102
+ def chat(req: ChatRequest) -> ChatResponse:
103
+ lc_history = []
104
+ for t in (req.conversation_history or [])[-8:]:
105
+ if t.human:
106
+ lc_history.append({"type": "human", "content": str(t.human)[:2000]})
107
+ if t.ai is not None:
108
+ ai_text = t.ai["message"] if isinstance(t.ai, dict) and "message" in t.ai else str(t.ai)
109
+ lc_history.append({"type": "ai", "content": ai_text[:2000]})
110
+
111
+ bbox = None
112
+ if req.bounding_box and req.bounding_box.north_east and req.bounding_box.south_west:
113
+ bbox = {
114
+ "north_east": {"lat": req.bounding_box.north_east.lat, "lon": req.bounding_box.north_east.lon},
115
+ "south_west": {"lat": req.bounding_box.south_west.lat, "lon": req.bounding_box.south_west.lon},
116
+ }
117
+
118
+ result = run_agent(req.user_input or "", lc_history, bbox=bbox)
119
+
120
+ message_text = result.get("final_text") or ""
121
+ last_tool_json = result.get("last_tool_json")
122
+
123
+ if _looks_like_tool_json(message_text):
124
+ last_tool_json = message_text
125
+ message_text = ""
126
+
127
+ places = _tool_json_to_places(last_tool_json)
128
+
129
+ if not message_text and places:
130
+ message_text = _fmt_places_md(places)
131
+
132
+ # Provide more contextual fallback message
133
+ if not message_text:
134
+ if bbox and req.user_input:
135
+ 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."
136
+ elif bbox:
137
+ message_text = "No places found in the specified area. Try expanding the search boundary or searching in a different location."
138
+ elif req.user_input:
139
+ 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."
140
+ else:
141
+ message_text = "I couldn't find anything for that request."
142
+
143
+ message_text = _sanitize_text(message_text)
144
+
145
+ agent_reply = AgentReply(message=message_text, places=places)
146
+ updated_history: List[Turn] = list(req.conversation_history or [])
147
+ updated_history.append(Turn(human=req.user_input or "", ai=agent_reply.model_dump()))
148
+
149
+ return ChatResponse(agent_reply=agent_reply, conversation_history=updated_history)
150
+
151
+ @app.get("/", response_class=HTMLResponse)
152
+ def index():
153
+ try:
154
+ with open("api/static/index.html", "r", encoding="utf-8") as f:
155
+ return f.read()
156
+ except Exception:
157
+ return HTMLResponse(
158
+ "<!doctype html><html><head><meta charset='utf-8'><title>Talk2Map</title></head>"
159
+ "<body><h1>Talk2Map API</h1><p>POST to <code>/chat</code> to use the assistant.</p></body></html>"
160
+ )
161
+
162
+ @app.get("/health")
163
+ def health():
164
+ return {"status": "ok"}
165
+
166
+ if __name__ == "__main__":
167
+ uvicorn.run("app:app", host="127.0.0.1", port=8000, reload=True)
api/static/index.html ADDED
@@ -0,0 +1,406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <title>MapMate — Chat + Places</title>
6
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
7
+
8
+ <!-- Tailwind theme (brand + accent) — must be defined BEFORE the CDN script -->
9
+ <script>
10
+ tailwind = {}; // ensure object exists
11
+ tailwind.config = {
12
+ theme: {
13
+ extend: {
14
+ colors: { brand: '#0A2647', accent: '#FF6B00' },
15
+ },
16
+ },
17
+ };
18
+ </script>
19
+ <script src="https://cdn.tailwindcss.com"></script>
20
+
21
+ <!-- Markdown renderer + sanitizer -->
22
+ <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
23
+ <script src="https://cdn.jsdelivr.net/npm/dompurify@3.0.9/dist/purify.min.js"></script>
24
+
25
+ <!-- Optional code highlighting -->
26
+ <link
27
+ rel="stylesheet"
28
+ href="https://cdn.jsdelivr.net/npm/highlight.js@11.9.0/styles/github.min.css"
29
+ />
30
+ <script src="https://cdn.jsdelivr.net/npm/highlight.js@11.9.0/lib/common.min.js"></script>
31
+
32
+ <style>
33
+ .md :is(pre, code) {
34
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;
35
+ }
36
+ .md pre { background: rgba(15,23,42,.05); padding: .75rem; border-radius: .5rem; overflow: auto; }
37
+ .md code:not(pre code) { background: rgba(15,23,42,.05); padding: .15rem .35rem; border-radius: .35rem; }
38
+ .md a { color: #2563eb; text-decoration: underline; }
39
+ .md ul, .md ol { margin-left: 1.25rem; list-style: revert; }
40
+ .md h1, .md h2, .md h3 { font-weight: 600; margin-top: .75rem; }
41
+ .md p { margin: .4rem 0; }
42
+ kbd { border: 1px solid rgba(100,116,139,.4); border-bottom-width: 2px; padding: 0 .35rem; border-radius: .35rem; font-size: .75rem; background: #fff; }
43
+ :focus-visible { outline: 2px dashed #FF6B00; outline-offset: 2px; }
44
+ </style>
45
+ </head>
46
+
47
+ <body class="min-h-screen bg-slate-50 text-slate-900">
48
+ <!-- Header -->
49
+ <header class="bg-brand text-white sticky top-0 z-40">
50
+ <div class="max-w-6xl mx-auto px-4 py-3 flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
51
+ <h1 class="text-xl font-semibold tracking-tight">🗺️ MapMate</h1>
52
+ <div class="flex flex-wrap items-center gap-2">
53
+ <label class="text-sm/none opacity-80">API Base URL</label>
54
+ <input id="baseUrl" class="px-3 py-2 rounded-lg border bg-white/95 text-slate-900 text-sm w-72" placeholder="http://localhost:8000" />
55
+ <button id="saveBaseUrl" class="px-3 py-2 rounded-lg bg-accent text-white text-sm hover:brightness-110">Save</button>
56
+ <button id="clearHistory" class="px-3 py-2 rounded-lg border border-white/30 text-sm hover:bg-white/10">Clear History</button>
57
+ </div>
58
+ </div>
59
+ </header>
60
+
61
+ <!-- Main -->
62
+ <main class="max-w-6xl mx-auto p-4 grid grid-cols-1 lg:grid-cols-3 gap-4">
63
+ <!-- Chat + BBox panel -->
64
+ <section class="lg:col-span-2 flex flex-col bg-white rounded-2xl shadow-sm border">
65
+ <div class="p-4 border-b">
66
+ <h2 class="font-semibold">Chat</h2>
67
+ <p class="text-sm text-slate-500">
68
+ Use one <em>Send</em> button. If a bounding box is filled, it’s included automatically. If you send with empty text + filled bbox, we’ll explore places inside that rectangle.
69
+ </p>
70
+ </div>
71
+
72
+ <!-- Messages -->
73
+ <div id="messages" class="p-4 space-y-4 overflow-auto" style="max-height: 44vh"></div>
74
+
75
+ <!-- Divider -->
76
+ <div class="px-4"><div class="h-px bg-slate-200"></div></div>
77
+
78
+ <!-- Bounding Box inputs (no separate button) -->
79
+ <div class="p-4 border-t">
80
+ <div class="flex items-center justify-between mb-3">
81
+ <h3 class="font-semibold">Bounding Box (optional)</h3>
82
+ <span class="text-xs text-slate-500">Will be sent with your message (or alone if message is empty)</span>
83
+ </div>
84
+ <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
85
+ <div class="p-3 border rounded-xl">
86
+ <div class="font-medium text-sm mb-2">North-East</div>
87
+ <div class="grid grid-cols-2 gap-2">
88
+ <input id="neLat" type="number" step="any" placeholder="NE lat" class="px-3 py-2 rounded-lg border bg-white text-sm" value="13.111864" />
89
+ <input id="neLon" type="number" step="any" placeholder="NE lon" class="px-3 py-2 rounded-lg border bg-white text-sm" value="80.243246" />
90
+ </div>
91
+ </div>
92
+ <div class="p-3 border rounded-xl">
93
+ <div class="font-medium text-sm mb-2">South-West</div>
94
+ <div class="grid grid-cols-2 gap-2">
95
+ <input id="swLat" type="number" step="any" placeholder="SW lat" class="px-3 py-2 rounded-lg border bg-white text-sm" value="13.105112" />
96
+ <input id="swLon" type="number" step="any" placeholder="SW lon" class="px-3 py-2 rounded-lg border bg-white text-sm" value="80.236375" />
97
+ </div>
98
+ </div>
99
+ </div>
100
+ <p class="text-xs text-slate-500 mt-2">
101
+ Backend defaults to “points of interest” when message is empty (bbox-only).
102
+ </p>
103
+ </div>
104
+
105
+ <!-- Composer (single send) -->
106
+ <div class="p-4 border-t">
107
+ <form id="chatForm" class="flex items-end gap-2">
108
+ <textarea id="userInput" rows="2" class="flex-1 px-3 py-2 rounded-xl border bg-white"
109
+ placeholder="Type your message… (e.g., best 5 hotels in Chennai)"></textarea>
110
+ <button id="sendBtn" type="submit" class="px-4 py-2 rounded-xl bg-accent text-white font-medium hover:brightness-110">
111
+ Send
112
+ </button>
113
+ </form>
114
+ <p class="text-xs text-slate-500 mt-2">
115
+ Tip: Press <kbd>Enter</kbd> to send, <kbd>Shift+Enter</kbd> for a new line.
116
+ </p>
117
+ </div>
118
+ </section>
119
+
120
+ <!-- Results panel -->
121
+ <section class="bg-white rounded-2xl shadow-sm border">
122
+ <div class="p-4 border-b flex items-center justify-between">
123
+ <h2 class="font-semibold">Places</h2>
124
+ <label class="text-xs text-slate-500 flex items-center gap-2">
125
+ <input type="checkbox" id="toggleRaw" class="rounded border" />
126
+ Show raw JSON
127
+ </label>
128
+ </div>
129
+ <div id="places" class="p-4 space-y-4 overflow-auto" style="max-height: 60vh">
130
+ <p class="text-sm text-slate-500">No places yet — try “best hotel in Chennai” or fill a bounding box and press Send.</p>
131
+ </div>
132
+ <div id="rawJsonWrap" class="hidden border-t">
133
+ <pre id="rawJson" class="p-4 text-xs overflow-auto"></pre>
134
+ </div>
135
+ </section>
136
+ </main>
137
+
138
+ <!-- Toast -->
139
+ <div id="toast" class="fixed bottom-4 right-4 hidden px-4 py-2 rounded-xl bg-rose-600 text-white shadow-lg"></div>
140
+
141
+ <script>
142
+ // Elements
143
+ const baseUrlInput = document.getElementById("baseUrl");
144
+ const saveBaseUrlBtn = document.getElementById("saveBaseUrl");
145
+ const clearHistoryBtn = document.getElementById("clearHistory");
146
+ const messagesEl = document.getElementById("messages");
147
+ const placesEl = document.getElementById("places");
148
+ const toggleRaw = document.getElementById("toggleRaw");
149
+ const rawJsonWrap = document.getElementById("rawJsonWrap");
150
+ const rawJsonEl = document.getElementById("rawJson");
151
+ const chatForm = document.getElementById("chatForm");
152
+ const userInput = document.getElementById("userInput");
153
+ const sendBtn = document.getElementById("sendBtn");
154
+ const toast = document.getElementById("toast");
155
+
156
+ // BBox inputs
157
+ const neLat = document.getElementById("neLat");
158
+ const neLon = document.getElementById("neLon");
159
+ const swLat = document.getElementById("swLat");
160
+ const swLon = document.getElementById("swLon");
161
+
162
+ // State
163
+ let conversation_history = [];
164
+ let lastResponseRaw = null;
165
+
166
+ // Base URL init
167
+ const DEFAULT_BASE = window.location.origin;
168
+ baseUrlInput.value = localStorage.getItem("mapmate_base") || DEFAULT_BASE;
169
+
170
+ saveBaseUrlBtn.addEventListener("click", () => {
171
+ localStorage.setItem("mapmate_base", baseUrlInput.value.trim() || DEFAULT_BASE);
172
+ showToast("Base URL saved");
173
+ });
174
+
175
+ clearHistoryBtn.addEventListener("click", () => {
176
+ conversation_history = [];
177
+ messagesEl.innerHTML = "";
178
+ placesEl.innerHTML = '<p class="text-sm text-slate-500">No places yet — try “best hotel in Chennai” or fill a bounding box and press Send.</p>';
179
+ rawJsonEl.textContent = "";
180
+ lastResponseRaw = null;
181
+ showToast("History cleared");
182
+ });
183
+
184
+ toggleRaw.addEventListener("change", () => {
185
+ rawJsonWrap.classList.toggle("hidden", !toggleRaw.checked);
186
+ });
187
+
188
+ // Enter-to-send
189
+ userInput.addEventListener("keydown", (e) => {
190
+ if (e.key === "Enter" && !e.shiftKey) {
191
+ e.preventDefault();
192
+ chatForm.requestSubmit();
193
+ }
194
+ });
195
+
196
+ // ---------- Helpers ----------
197
+ function fmt(n) {
198
+ if (n === null || n === undefined || n === "") return "—";
199
+ return Number(n).toFixed(6);
200
+ }
201
+
202
+ // Strip ChatML / header tokens the model might emit
203
+ function stripHeaders(s = "") {
204
+ return (s || "")
205
+ .replace(/<\|header_start\|>.*?<\|header_end\|>/gs, "")
206
+ .replace(/<\|im_start\|>.*?<\|im_end\|>/gs, "")
207
+ .replace(/<\|[^>]*\|>/g, "")
208
+ .trim();
209
+ }
210
+
211
+ // Rendering
212
+ function renderMessage(role, text) {
213
+ const isUser = role === "user";
214
+ const wrapper = document.createElement("div");
215
+ wrapper.className = `flex ${isUser ? "justify-end" : "justify-start"}`;
216
+
217
+ const bubble = document.createElement("div");
218
+ bubble.className = `max-w-[85%] rounded-2xl px-4 py-3 shadow-sm ${
219
+ isUser
220
+ // User bubble: black text
221
+ ? "bg-accent/10 text-black border border-accent/30 rounded-br-md"
222
+ // Assistant bubble: markdown styled
223
+ : "bg-slate-100 text-slate-900 rounded-bl-md md"
224
+ }`;
225
+
226
+ if (isUser) {
227
+ bubble.textContent = text;
228
+ } else {
229
+ bubble.classList.add("md");
230
+ const safe = DOMPurify.sanitize(marked.parse(stripHeaders(text || "")));
231
+ bubble.innerHTML = safe;
232
+ if (window.hljs) bubble.querySelectorAll("pre code").forEach((el) => hljs.highlightElement(el));
233
+ }
234
+
235
+ wrapper.appendChild(bubble);
236
+ messagesEl.appendChild(wrapper);
237
+ messagesEl.scrollTop = messagesEl.scrollHeight;
238
+ }
239
+
240
+ function renderPlaces(places, raw) {
241
+ placesEl.innerHTML = "";
242
+ if (!places || places.length === 0) {
243
+ placesEl.innerHTML = '<p class="text-sm text-slate-500">No places returned.</p>';
244
+ } else {
245
+ places.forEach((p, idx) => {
246
+ const ne = p.bounding_box?.north_east || {};
247
+ const sw = p.bounding_box?.south_west || {};
248
+ const mapsUrl =
249
+ p.maps_url || (p.latitude && p.longitude ? `https://www.google.com/maps?q=${p.latitude},${p.longitude}` : null);
250
+
251
+ const card = document.createElement("div");
252
+ card.className = "rounded-xl border p-4 hover:shadow-sm transition";
253
+
254
+ card.innerHTML = `
255
+ <div class="flex items-start justify-between gap-2">
256
+ <div>
257
+ <div class="text-sm text-slate-500">#${idx + 1}</div>
258
+ <h3 class="font-semibold">${p.name || "Unknown"}</h3>
259
+ <p class="text-sm text-slate-600">${p.address || "—"}</p>
260
+ </div>
261
+ ${
262
+ mapsUrl
263
+ ? `<a href="${mapsUrl}" target="_blank" class="text-sm text-accent hover:underline">Open in Maps ↗</a>`
264
+ : ""
265
+ }
266
+ </div>
267
+ <div class="grid grid-cols-2 gap-3 mt-3 text-sm">
268
+ <div class="space-y-1">
269
+ <div><span class="text-slate-500">lat,lng:</span> ${fmt(p.latitude)}, ${fmt(p.longitude)}</div>
270
+ <div><span class="text-slate-500">Rating:</span> ${p.rating ?? "—"}</div>
271
+ <div><span class="text-slate-500">Reviews:</span> ${p.user_rating_count ?? "—"}</div>
272
+ </div>
273
+ <div class="space-y-1">
274
+ <div class="text-slate-500">Bounding Box</div>
275
+ <div>NE: ${fmt(ne.lat)}, ${fmt(ne.lon)}</div>
276
+ <div>SW: ${fmt(sw.lat)}, ${fmt(sw.lon)}</div>
277
+ </div>
278
+ </div>`;
279
+ placesEl.appendChild(card);
280
+ });
281
+ }
282
+
283
+ lastResponseRaw = raw || null;
284
+ rawJsonEl.textContent = lastResponseRaw ? JSON.stringify(lastResponseRaw, null, 2) : "";
285
+ }
286
+
287
+ function showToast(msg) {
288
+ toast.textContent = msg;
289
+ toast.classList.remove("hidden");
290
+ setTimeout(() => toast.classList.add("hidden"), 1400);
291
+ }
292
+
293
+ function getBase() {
294
+ return (baseUrlInput.value || "").trim() || DEFAULT_BASE;
295
+ }
296
+
297
+ function getBoundingBoxFromInputs() {
298
+ const neLatVal = parseFloat(neLat.value);
299
+ const neLonVal = parseFloat(neLon.value);
300
+ const swLatVal = parseFloat(swLat.value);
301
+ const swLonVal = parseFloat(swLon.value);
302
+ if ([neLatVal, neLonVal, swLatVal, swLonVal].some((v) => Number.isNaN(v))) return null;
303
+ if (swLatVal > neLatVal) return null;
304
+ if (swLonVal > neLonVal) return null;
305
+ return { north_east: { lat: neLatVal, lon: neLonVal }, south_west: { lat: swLatVal, lon: swLonVal } };
306
+ }
307
+
308
+ // Single-send API call (includes bbox if present; supports bbox-only)
309
+ async function sendSingle() {
310
+ const base = getBase();
311
+ const text = userInput.value.trim();
312
+ const bbox = getBoundingBoxFromInputs();
313
+
314
+ if (!text && !bbox) {
315
+ showToast("Type a message or fill a bounding box.");
316
+ return;
317
+ }
318
+
319
+ // Local echo - never show bbox info in user messages
320
+ if (text) {
321
+ renderMessage("user", text);
322
+ } else {
323
+ renderMessage(
324
+ "user",
325
+ `Search within **Bounding Box**\nNE: ${fmt(bbox.north_east.lat)}, ${fmt(
326
+ bbox.north_east.lon
327
+ )} | SW: ${fmt(bbox.south_west.lat)}, ${fmt(bbox.south_west.lon)}\n(_message empty → bbox-only mode_)`
328
+ );
329
+ }
330
+
331
+ const body = { user_input: text, conversation_history, bounding_box: bbox };
332
+
333
+ // Typing indicator
334
+ const typing = document.createElement("div");
335
+ typing.className = "flex justify-start";
336
+ typing.innerHTML = `<div class="max-w-[85%] rounded-2xl px-4 py-3 shadow-sm bg-slate-100 text-slate-900 rounded-bl-md">
337
+ <span class="inline-flex items-center gap-2 text-sm">
338
+ <span class="w-2 h-2 rounded-full bg-slate-400 animate-pulse"></span> thinking…
339
+ </span></div>`;
340
+ messagesEl.appendChild(typing);
341
+ messagesEl.scrollTop = messagesEl.scrollHeight;
342
+
343
+ sendBtn.disabled = true;
344
+ sendBtn.classList.add("opacity-60", "cursor-not-allowed");
345
+
346
+ try {
347
+ const res = await fetch(`${base}/chat`, {
348
+ method: "POST",
349
+ headers: { "Content-Type": "application/json" },
350
+ body: JSON.stringify(body),
351
+ });
352
+ if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
353
+
354
+ const data = await res.json();
355
+ typing.remove();
356
+
357
+ // Defensive: if backend returns raw JSON in message, recompose from places.
358
+ let msg = data?.agent_reply?.message || "";
359
+ if (msg.trim().startsWith("[")) {
360
+ const places = data?.agent_reply?.places || [];
361
+ msg = places.length
362
+ ? places
363
+ .map(
364
+ (p, i) =>
365
+ `${i + 1}. ${p.name || "—"} — ${p.address || "—"}${
366
+ p.rating != null ? ` (Rating ★ ${p.rating}, Reviews ${p.user_rating_count ?? "—"})` : ""
367
+ }${p.maps_url ? ` — ${p.maps_url}` : ""}\nlat,lng: ${p.latitude}, ${p.longitude}\n${
368
+ p.bounding_box
369
+ ? `SW: (${p.bounding_box.south_west.lat}, ${p.bounding_box.south_west.lon}), NE: (${p.bounding_box.north_east.lat}, ${p.bounding_box.north_east.lon})`
370
+ : ""
371
+ }`
372
+ )
373
+ .join("\n\n")
374
+ : "No places found.";
375
+ }
376
+
377
+ msg = stripHeaders(msg); // strip ChatML/header tokens
378
+ renderMessage("assistant", msg);
379
+ renderPlaces(data?.agent_reply?.places || [], data);
380
+ conversation_history = data?.conversation_history || conversation_history;
381
+ } catch (err) {
382
+ console.error(err);
383
+ typing.remove();
384
+ renderMessage("assistant", `**Error:** ${err?.message || err}`);
385
+ showToast("Request failed — check console & CORS");
386
+ } finally {
387
+ sendBtn.disabled = false;
388
+ sendBtn.classList.remove("opacity-60", "cursor-not-allowed");
389
+ userInput.value = "";
390
+ }
391
+ }
392
+
393
+ // Handlers
394
+ chatForm.addEventListener("submit", (e) => {
395
+ e.preventDefault();
396
+ sendSingle();
397
+ });
398
+
399
+ // Welcome
400
+ renderMessage(
401
+ "assistant",
402
+ "Hi! I'm **Talk2Map**. One button does it all 👋\n\nTry:\n1. **best 5 hotels in Chennai**\n2. Fill a bounding box and press **Send** (no message) to list POIs inside.\n3. Fill both message + bbox to constrain results to that rectangle."
403
+ );
404
+ </script>
405
+ </body>
406
+ </html>
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ fastapi==0.115.11
2
+ uvicorn==0.34.0
3
+ pydantic==2.10.6
4
+ python-dotenv==1.0.0
5
+ langchain-groq==0.3.2
6
+ langchain==0.3.26
7
+ pytest==7.4.2
test_no_places.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Test script to verify improved error messages when no places are found.
4
+ """
5
+
6
+ import json
7
+ from agent.agent_runner import run_agent
8
+
9
+ def test_no_places_scenarios():
10
+ """Test different scenarios where no places are found."""
11
+
12
+ print("Testing improved error messages for no places found...\n")
13
+
14
+ # Test 1: Query with bounding box but no places found
15
+ print("Test 1: Query with bounding box (should say area doesn't have requested places)")
16
+ bbox = {
17
+ "north_east": {"lat": 0.001, "lon": 0.001}, # Very small area with no places
18
+ "south_west": {"lat": 0.0, "lon": 0.0}
19
+ }
20
+ result1 = run_agent("restaurants", [], bbox=bbox)
21
+ print(f"Result: {result1['final_text']}")
22
+ print()
23
+
24
+ # Test 2: Query without bounding box
25
+ print("Test 2: Query without bounding box (should suggest nearby city)")
26
+ result2 = run_agent("nonexistent_place_type_xyz", [])
27
+ print(f"Result: {result2['final_text']}")
28
+ print()
29
+
30
+ # Test 3: Bounding box only (no query)
31
+ print("Test 3: Bounding box only, no query")
32
+ result3 = run_agent("", [], bbox=bbox)
33
+ print(f"Result: {result3['final_text']}")
34
+ print()
35
+
36
+ print("All tests completed!")
37
+
38
+ if __name__ == "__main__":
39
+ test_no_places_scenarios()
tests/e2e/test_e2e_app.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import time
3
+ import requests
4
+
5
+ BBOX = {
6
+ "north_east": {"lat": 40.0, "lon": -73.0},
7
+ "south_west": {"lat": 39.0, "lon": -74.0},
8
+ }
9
+
10
+
11
+ def start_server():
12
+ proc = subprocess.Popen(
13
+ ["uvicorn", "api.app:app", "--port", "8001", "--host", "127.0.0.1"],
14
+ stdout=subprocess.PIPE,
15
+ stderr=subprocess.PIPE,
16
+ )
17
+ # give uvicorn a moment to boot
18
+ time.sleep(2)
19
+ return proc
20
+
21
+
22
+ def test_e2e_health_and_chat():
23
+ proc = start_server()
24
+ try:
25
+ # health check
26
+ r = requests.get("http://127.0.0.1:8001/health")
27
+ assert r.status_code == 200
28
+ assert r.json()["status"] == "ok"
29
+
30
+ finally:
31
+ proc.terminate()
tests/integration/test_api_endpoints.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi.testclient import TestClient
2
+ from api.app import app
3
+
4
+ client = TestClient(app)
5
+
6
+ # Shared bounding box payload for all chat requests
7
+ BBOX = {
8
+ "north_east": {"lat": 40.0, "lon": -73.0},
9
+ "south_west": {"lat": 39.0, "lon": -74.0},
10
+ }
11
+
12
+
13
+ def test_health_check():
14
+ r = client.get("/health")
15
+ assert r.status_code == 200
16
+ assert r.json()["status"] == "ok"
17
+
18
+
19
+ def test_chat_with_empty_body():
20
+ r = client.post("/chat", json={
21
+ "user_input": "",
22
+ "conversation_history": [],
23
+ "bounding_box": BBOX,
24
+ })
25
+ assert r.status_code == 200
26
+ data = r.json()
27
+ assert "agent_reply" in data
28
+
29
+
30
+ def test_chat_with_text_only():
31
+ r = client.post("/chat", json={
32
+ "user_input": "Find cafes",
33
+ "conversation_history": [],
34
+ "bounding_box": BBOX,
35
+ })
36
+ assert r.status_code == 200
37
+ data = r.json()
38
+ assert "agent_reply" in data
39
+
40
+
41
+ def test_chat_with_bbox_and_text():
42
+ r = client.post("/chat", json={
43
+ "user_input": "parks",
44
+ "conversation_history": [],
45
+ "bounding_box": BBOX,
46
+ })
47
+ assert r.status_code == 200
48
+ data = r.json()
49
+ assert "agent_reply" in data
50
+
51
+
52
+ def test_chat_with_conversation_history():
53
+ history = [
54
+ {"human": "hello", "ai": {"message": "Hi there!"}},
55
+ {"human": "find restaurants", "ai": {"message": "Here are some places."}},
56
+ ]
57
+ r = client.post("/chat", json={
58
+ "user_input": "any cafes?",
59
+ "conversation_history": history,
60
+ "bounding_box": BBOX,
61
+ })
62
+ assert r.status_code == 200
63
+ data = r.json()
64
+ assert len(data["conversation_history"]) >= 3
tests/unit/test_utils.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from api.app import _sanitize_text, _looks_like_tool_json, _tool_json_to_places, _fmt_places_md
3
+ from agent.models import Place, BoundingBox, LatLon
4
+
5
+ def test_sanitize_text_removes_headers():
6
+ raw = "Hello <|header_start|>SECRET<|header_end|> World"
7
+ cleaned = _sanitize_text(raw)
8
+ assert "SECRET" not in cleaned
9
+ assert cleaned.startswith("Hello")
10
+
11
+ def test_sanitize_text_handles_none():
12
+ assert _sanitize_text(None) == ""
13
+
14
+ def test_looks_like_tool_json_valid():
15
+ s = '[{"name":"Test","lat":1.23,"lng":4.56}]'
16
+ assert _looks_like_tool_json(s) is True
17
+
18
+ def test_looks_like_tool_json_invalid():
19
+ assert _looks_like_tool_json("not json") is False
20
+ assert _looks_like_tool_json(123) is False
21
+
22
+ def test_tool_json_to_places_and_fmt():
23
+ raw = '[{"name":"Cafe","address":"123 St","lat":1.0,"lng":2.0,"viewport":{"low":{"latitude":0,"longitude":0},"high":{"latitude":2,"longitude":2}}}]'
24
+ places = _tool_json_to_places(raw)
25
+ assert len(places) == 1
26
+ p = places[0]
27
+ assert isinstance(p, Place)
28
+ assert p.name == "Cafe"
29
+ md = _fmt_places_md(places)
30
+ assert "Cafe" in md
31
+ assert "lat,lng" in md
32
+
33
+ def test_tool_json_to_places_invalid_returns_empty():
34
+ assert _tool_json_to_places("not json") == []
35
+ assert _tool_json_to_places("{}") == []