geomind-ai 1.0.0__py3-none-any.whl → 1.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
geomind/agent.py CHANGED
@@ -1,445 +1,441 @@
1
- """
2
- GeoMind Agent - Main agent class powered by OpenRouter.
3
-
4
- This module implements the AI agent that can understand natural language
5
- queries about satellite imagery and execute the appropriate tools.
6
- """
7
-
8
- import json
9
- from typing import Optional
10
- from datetime import datetime
11
-
12
- from openai import OpenAI
13
-
14
- from .config import OPENROUTER_API_KEY, OPENROUTER_API_URL, OPENROUTER_MODEL
15
- from .tools import (
16
- geocode_location,
17
- get_bbox_from_location,
18
- search_imagery,
19
- get_item_details,
20
- list_recent_imagery,
21
- create_rgb_composite,
22
- calculate_ndvi,
23
- get_band_statistics,
24
- )
25
-
26
-
27
- # Map tool names to functions
28
- TOOL_FUNCTIONS = {
29
- "geocode_location": geocode_location,
30
- "get_bbox_from_location": get_bbox_from_location,
31
- "search_imagery": search_imagery,
32
- "list_recent_imagery": list_recent_imagery,
33
- "get_item_details": get_item_details,
34
- "create_rgb_composite": create_rgb_composite,
35
- "calculate_ndvi": calculate_ndvi,
36
- "get_band_statistics": get_band_statistics,
37
- }
38
-
39
- # Tool definitions for the LLM
40
- TOOLS = [
41
- {
42
- "type": "function",
43
- "function": {
44
- "name": "geocode_location",
45
- "description": "Convert a place name to geographic coordinates (latitude, longitude). Use this when you need to find coordinates for a location.",
46
- "parameters": {
47
- "type": "object",
48
- "properties": {
49
- "place_name": {
50
- "type": "string",
51
- "description": "The name of the place to geocode (e.g., 'New York City', 'Paris, France')",
52
- }
53
- },
54
- "required": ["place_name"],
55
- },
56
- },
57
- },
58
- {
59
- "type": "function",
60
- "function": {
61
- "name": "get_bbox_from_location",
62
- "description": "Get a bounding box for a location, suitable for searching satellite imagery.",
63
- "parameters": {
64
- "type": "object",
65
- "properties": {
66
- "place_name": {
67
- "type": "string",
68
- "description": "The name of the place",
69
- },
70
- "buffer_km": {
71
- "type": "number",
72
- "description": "Buffer distance in kilometers (default: 10)",
73
- },
74
- },
75
- "required": ["place_name"],
76
- },
77
- },
78
- },
79
- {
80
- "type": "function",
81
- "function": {
82
- "name": "search_imagery",
83
- "description": "Search for Sentinel-2 satellite imagery in the EOPF catalog. Returns available scenes.",
84
- "parameters": {
85
- "type": "object",
86
- "properties": {
87
- "bbox": {
88
- "type": "array",
89
- "items": {"type": "number"},
90
- "description": "Bounding box as [min_lon, min_lat, max_lon, max_lat]",
91
- },
92
- "start_date": {
93
- "type": "string",
94
- "description": "Start date in YYYY-MM-DD format",
95
- },
96
- "end_date": {
97
- "type": "string",
98
- "description": "End date in YYYY-MM-DD format",
99
- },
100
- "max_cloud_cover": {
101
- "type": "number",
102
- "description": "Maximum cloud cover percentage (0-100)",
103
- },
104
- "max_items": {
105
- "type": "integer",
106
- "description": "Maximum number of results",
107
- },
108
- },
109
- "required": [],
110
- },
111
- },
112
- },
113
- {
114
- "type": "function",
115
- "function": {
116
- "name": "list_recent_imagery",
117
- "description": "List recent Sentinel-2 imagery for a location. Combines geocoding and search.",
118
- "parameters": {
119
- "type": "object",
120
- "properties": {
121
- "location_name": {
122
- "type": "string",
123
- "description": "Name of the location to search",
124
- },
125
- "days": {
126
- "type": "integer",
127
- "description": "Number of days to look back (default: 7)",
128
- },
129
- "max_cloud_cover": {
130
- "type": "number",
131
- "description": "Maximum cloud cover percentage",
132
- },
133
- "max_items": {
134
- "type": "integer",
135
- "description": "Maximum number of results",
136
- },
137
- },
138
- "required": [],
139
- },
140
- },
141
- },
142
- {
143
- "type": "function",
144
- "function": {
145
- "name": "get_item_details",
146
- "description": "Get detailed information about a specific Sentinel-2 scene by its ID.",
147
- "parameters": {
148
- "type": "object",
149
- "properties": {
150
- "item_id": {"type": "string", "description": "The STAC item ID"}
151
- },
152
- "required": ["item_id"],
153
- },
154
- },
155
- },
156
- {
157
- "type": "function",
158
- "function": {
159
- "name": "create_rgb_composite",
160
- "description": "Create an RGB true-color composite image from Sentinel-2 data.",
161
- "parameters": {
162
- "type": "object",
163
- "properties": {
164
- "zarr_url": {
165
- "type": "string",
166
- "description": "URL to the SR_10m Zarr asset from a STAC item",
167
- },
168
- "output_path": {
169
- "type": "string",
170
- "description": "Optional path to save the output image",
171
- },
172
- "subset_size": {
173
- "type": "integer",
174
- "description": "Size to subset the image (default: 1000 pixels)",
175
- },
176
- },
177
- "required": ["zarr_url"],
178
- },
179
- },
180
- },
181
- {
182
- "type": "function",
183
- "function": {
184
- "name": "calculate_ndvi",
185
- "description": "Calculate NDVI (vegetation index) from Sentinel-2 data.",
186
- "parameters": {
187
- "type": "object",
188
- "properties": {
189
- "zarr_url": {
190
- "type": "string",
191
- "description": "URL to the SR_10m Zarr asset",
192
- },
193
- "output_path": {
194
- "type": "string",
195
- "description": "Optional path to save the NDVI image",
196
- },
197
- "subset_size": {
198
- "type": "integer",
199
- "description": "Size to subset the image",
200
- },
201
- },
202
- "required": ["zarr_url"],
203
- },
204
- },
205
- },
206
- {
207
- "type": "function",
208
- "function": {
209
- "name": "get_band_statistics",
210
- "description": "Get statistics (min, max, mean) for spectral bands.",
211
- "parameters": {
212
- "type": "object",
213
- "properties": {
214
- "zarr_url": {
215
- "type": "string",
216
- "description": "URL to the Zarr asset",
217
- },
218
- "bands": {
219
- "type": "array",
220
- "items": {"type": "string"},
221
- "description": "List of band names to analyze",
222
- },
223
- },
224
- "required": ["zarr_url"],
225
- },
226
- },
227
- },
228
- ]
229
-
230
-
231
- class GeoMindAgent:
232
- """
233
- GeoMind - An AI agent for geospatial analysis with Sentinel-2 imagery.
234
-
235
- Uses OpenRouter API for access to multiple AI models.
236
- """
237
-
238
- def __init__(self, model: Optional[str] = None, api_key: Optional[str] = None):
239
- """
240
- Initialize the GeoMind agent.
241
-
242
- Args:
243
- model: Model name (default: xiaomi/mimo-v2-flash:free)
244
- api_key: OpenRouter API key. If not provided, looks for OPENROUTER_API_KEY env variable.
245
- """
246
- self.provider = "openrouter"
247
- self.api_key = api_key or OPENROUTER_API_KEY
248
- self.model_name = model or OPENROUTER_MODEL
249
- self.base_url = OPENROUTER_API_URL
250
-
251
- if not self.api_key:
252
- raise ValueError(
253
- "OpenRouter API key required.\n"
254
- "You can provide it in three ways:\n"
255
- "1. Pass it to the constructor: GeoMindAgent(api_key='your-key')\n"
256
- "2. Set OPENROUTER_API_KEY environment variable\n"
257
- "3. Create a .env file with OPENROUTER_API_KEY=your-key\n"
258
- "\nGet your API key at: https://openrouter.ai/settings/keys"
259
- )
260
-
261
- print(f"🚀 GeoMind Agent initialized with {self.model_name} (OpenRouter)")
262
- print(f" API URL: {self.base_url}")
263
-
264
- # Create OpenAI-compatible client
265
- self.client = OpenAI(base_url=self.base_url, api_key=self.api_key)
266
-
267
- # Chat history
268
- self.history = []
269
-
270
- # Add system message
271
- self.system_prompt = self._get_system_prompt()
272
-
273
- def _get_system_prompt(self) -> str:
274
- """Get the system prompt for the agent."""
275
- return f"""You are GeoMind, an expert AI assistant specialized in geospatial analysis
276
- and satellite imagery. You help users find, analyze, and visualize Sentinel-2 satellite data
277
- from the EOPF (ESA Earth Observation Processing Framework) catalog.
278
-
279
- Your capabilities include:
280
- 1. **Search**: Find Sentinel-2 L2A imagery by location, date, and cloud cover
281
- 2. **Geocoding**: Convert place names to coordinates for searching
282
- 3. **Visualization**: Create RGB composites and NDVI maps from imagery
283
- 4. **Analysis**: Calculate spectral indices and band statistics
284
-
285
- Key information:
286
- - Data source: EOPF STAC API (https://stac.core.eopf.eodc.eu)
287
- - Satellite: Sentinel-2 (L2A surface reflectance products)
288
- - Bands available: B01-B12 at 10m, 20m, or 60m resolution
289
- - Current date: {datetime.now().strftime('%Y-%m-%d')}
290
-
291
- When users ask for imagery:
292
- 1. First use get_bbox_from_location or list_recent_imagery to search
293
- 2. Present the results clearly with key metadata
294
- 3. Offer to create visualizations if data is found
295
-
296
- Always explain what you're doing and interpret results in a helpful way."""
297
-
298
- def _execute_function(self, name: str, args: dict) -> dict:
299
- """Execute a function call and return the result."""
300
- print(f" 🔧 Executing: {name}({args})")
301
-
302
- if name not in TOOL_FUNCTIONS:
303
- return {"error": f"Unknown function: {name}"}
304
-
305
- try:
306
- result = TOOL_FUNCTIONS[name](**args)
307
- return result
308
- except Exception as e:
309
- return {"error": str(e)}
310
-
311
- def chat(self, message: str, verbose: bool = True) -> str:
312
- """
313
- Send a message to the agent and get a response.
314
- """
315
- if verbose:
316
- print(f"\n💬 User: {message}")
317
- print("🤔 Processing...")
318
-
319
- # Add user message to history
320
- self.history.append({"role": "user", "content": message})
321
-
322
- # Build messages with system prompt
323
- messages = [{"role": "system", "content": self.system_prompt}] + self.history
324
-
325
- max_iterations = 10
326
- iteration = 0
327
-
328
- while iteration < max_iterations:
329
- iteration += 1
330
-
331
- # Call the model
332
- response = self.client.chat.completions.create(
333
- model=self.model_name,
334
- messages=messages,
335
- tools=TOOLS,
336
- tool_choice="auto",
337
- max_tokens=4096,
338
- )
339
-
340
- assistant_message = response.choices[0].message
341
-
342
- # Check if there are tool calls
343
- if assistant_message.tool_calls:
344
- # Add assistant message with tool calls to messages
345
- messages.append(
346
- {
347
- "role": "assistant",
348
- "content": assistant_message.content or "",
349
- "tool_calls": [
350
- {
351
- "id": tc.id,
352
- "type": "function",
353
- "function": {
354
- "name": tc.function.name,
355
- "arguments": tc.function.arguments,
356
- },
357
- }
358
- for tc in assistant_message.tool_calls
359
- ],
360
- }
361
- )
362
-
363
- # Execute each tool call
364
- for tool_call in assistant_message.tool_calls:
365
- func_name = tool_call.function.name
366
- func_args = json.loads(tool_call.function.arguments)
367
-
368
- result = self._execute_function(func_name, func_args)
369
-
370
- # Add tool result to messages
371
- messages.append(
372
- {
373
- "role": "tool",
374
- "tool_call_id": tool_call.id,
375
- "content": json.dumps(result, default=str),
376
- }
377
- )
378
- else:
379
- # No tool calls, we have a final response
380
- final_text = assistant_message.content or ""
381
-
382
- # Add to history
383
- self.history.append({"role": "assistant", "content": final_text})
384
-
385
- if verbose:
386
- print(f"\n🌍 GeoMind: {final_text}")
387
-
388
- return final_text
389
-
390
- return "Max iterations reached."
391
-
392
- def reset(self):
393
- """Reset the chat session."""
394
- self.history = []
395
- print("🔄 Chat session reset")
396
-
397
-
398
- def main(model: Optional[str] = None):
399
- """Main entry point for CLI usage."""
400
- import sys
401
-
402
- print("=" * 60)
403
- print("🌍 GeoMind - Geospatial AI Agent")
404
- print("=" * 60)
405
- print("Powered by OpenRouter | Sentinel-2 Imagery")
406
- print("Type 'quit' or 'exit' to end the session")
407
- print("Type 'reset' to start a new conversation")
408
- print("=" * 60)
409
-
410
- try:
411
- agent = GeoMindAgent(model=model)
412
- except ValueError as e:
413
- print(f"\n❌ Error: {e}")
414
- sys.exit(1)
415
- except Exception as e:
416
- print(f"\n❌ Error: {e}")
417
- print("\nPlease check your API key and internet connection.")
418
- sys.exit(1)
419
-
420
- while True:
421
- try:
422
- user_input = input("\n💬 You: ").strip()
423
-
424
- if not user_input:
425
- continue
426
-
427
- if user_input.lower() in ["quit", "exit", "q"]:
428
- print("\n👋 Goodbye!")
429
- break
430
-
431
- if user_input.lower() == "reset":
432
- agent.reset()
433
- continue
434
-
435
- agent.chat(user_input)
436
-
437
- except KeyboardInterrupt:
438
- print("\n\n👋 Goodbye!")
439
- break
440
- except Exception as e:
441
- print(f"\n❌ Error: {e}")
442
-
443
-
444
- if __name__ == "__main__":
445
- main()
1
+ """
2
+ GeoMind Agent - Main agent class powered by OpenRouter.
3
+
4
+ This module implements the AI agent that can understand natural language
5
+ queries about satellite imagery and execute the appropriate tools.
6
+ """
7
+
8
+ import json
9
+ import re
10
+ from typing import Optional, Callable, Any
11
+ from datetime import datetime
12
+
13
+ from openai import OpenAI
14
+
15
+ from .config import OPENROUTER_API_KEY, OPENROUTER_API_URL, OPENROUTER_MODEL
16
+ from .tools import (
17
+ geocode_location,
18
+ get_bbox_from_location,
19
+ search_imagery,
20
+ get_item_details,
21
+ list_recent_imagery,
22
+ create_rgb_composite,
23
+ calculate_ndvi,
24
+ get_band_statistics,
25
+ )
26
+
27
+
28
+ # Map tool names to functions
29
+ TOOL_FUNCTIONS = {
30
+ "geocode_location": geocode_location,
31
+ "get_bbox_from_location": get_bbox_from_location,
32
+ "search_imagery": search_imagery,
33
+ "list_recent_imagery": list_recent_imagery,
34
+ "get_item_details": get_item_details,
35
+ "create_rgb_composite": create_rgb_composite,
36
+ "calculate_ndvi": calculate_ndvi,
37
+ "get_band_statistics": get_band_statistics,
38
+ }
39
+
40
+ # Tool definitions for the LLM
41
+ TOOLS = [
42
+ {
43
+ "type": "function",
44
+ "function": {
45
+ "name": "geocode_location",
46
+ "description": "Convert a place name to geographic coordinates (latitude, longitude). Use this when you need to find coordinates for a location.",
47
+ "parameters": {
48
+ "type": "object",
49
+ "properties": {
50
+ "place_name": {
51
+ "type": "string",
52
+ "description": "The name of the place to geocode (e.g., 'New York City', 'Paris, France')",
53
+ }
54
+ },
55
+ "required": ["place_name"],
56
+ },
57
+ },
58
+ },
59
+ {
60
+ "type": "function",
61
+ "function": {
62
+ "name": "get_bbox_from_location",
63
+ "description": "Get a bounding box for a location, suitable for searching satellite imagery.",
64
+ "parameters": {
65
+ "type": "object",
66
+ "properties": {
67
+ "place_name": {
68
+ "type": "string",
69
+ "description": "The name of the place",
70
+ },
71
+ "buffer_km": {
72
+ "type": "number",
73
+ "description": "Buffer distance in kilometers (default: 10)",
74
+ },
75
+ },
76
+ "required": ["place_name"],
77
+ },
78
+ },
79
+ },
80
+ {
81
+ "type": "function",
82
+ "function": {
83
+ "name": "search_imagery",
84
+ "description": "Search for Sentinel-2 satellite imagery in the EOPF catalog. Returns available scenes.",
85
+ "parameters": {
86
+ "type": "object",
87
+ "properties": {
88
+ "bbox": {
89
+ "type": "array",
90
+ "items": {"type": "number"},
91
+ "description": "Bounding box as [min_lon, min_lat, max_lon, max_lat]",
92
+ },
93
+ "start_date": {
94
+ "type": "string",
95
+ "description": "Start date in YYYY-MM-DD format",
96
+ },
97
+ "end_date": {
98
+ "type": "string",
99
+ "description": "End date in YYYY-MM-DD format",
100
+ },
101
+ "max_cloud_cover": {
102
+ "type": "number",
103
+ "description": "Maximum cloud cover percentage (0-100)",
104
+ },
105
+ "max_items": {
106
+ "type": "integer",
107
+ "description": "Maximum number of results",
108
+ },
109
+ },
110
+ "required": [],
111
+ },
112
+ },
113
+ },
114
+ {
115
+ "type": "function",
116
+ "function": {
117
+ "name": "list_recent_imagery",
118
+ "description": "List recent Sentinel-2 imagery for a location. Combines geocoding and search.",
119
+ "parameters": {
120
+ "type": "object",
121
+ "properties": {
122
+ "location_name": {
123
+ "type": "string",
124
+ "description": "Name of the location to search",
125
+ },
126
+ "days": {
127
+ "type": "integer",
128
+ "description": "Number of days to look back (default: 7)",
129
+ },
130
+ "max_cloud_cover": {
131
+ "type": "number",
132
+ "description": "Maximum cloud cover percentage",
133
+ },
134
+ "max_items": {
135
+ "type": "integer",
136
+ "description": "Maximum number of results",
137
+ },
138
+ },
139
+ "required": [],
140
+ },
141
+ },
142
+ },
143
+ {
144
+ "type": "function",
145
+ "function": {
146
+ "name": "get_item_details",
147
+ "description": "Get detailed information about a specific Sentinel-2 scene by its ID.",
148
+ "parameters": {
149
+ "type": "object",
150
+ "properties": {
151
+ "item_id": {"type": "string", "description": "The STAC item ID"}
152
+ },
153
+ "required": ["item_id"],
154
+ },
155
+ },
156
+ },
157
+ {
158
+ "type": "function",
159
+ "function": {
160
+ "name": "create_rgb_composite",
161
+ "description": "Create an RGB true-color composite image from Sentinel-2 data.",
162
+ "parameters": {
163
+ "type": "object",
164
+ "properties": {
165
+ "zarr_url": {
166
+ "type": "string",
167
+ "description": "URL to the SR_10m Zarr asset from a STAC item",
168
+ },
169
+ "output_path": {
170
+ "type": "string",
171
+ "description": "Optional path to save the output image",
172
+ },
173
+ "subset_size": {
174
+ "type": "integer",
175
+ "description": "Size to subset the image (default: 1000 pixels)",
176
+ },
177
+ },
178
+ "required": ["zarr_url"],
179
+ },
180
+ },
181
+ },
182
+ {
183
+ "type": "function",
184
+ "function": {
185
+ "name": "calculate_ndvi",
186
+ "description": "Calculate NDVI (vegetation index) from Sentinel-2 data.",
187
+ "parameters": {
188
+ "type": "object",
189
+ "properties": {
190
+ "zarr_url": {
191
+ "type": "string",
192
+ "description": "URL to the SR_10m Zarr asset",
193
+ },
194
+ "output_path": {
195
+ "type": "string",
196
+ "description": "Optional path to save the NDVI image",
197
+ },
198
+ "subset_size": {
199
+ "type": "integer",
200
+ "description": "Size to subset the image",
201
+ },
202
+ },
203
+ "required": ["zarr_url"],
204
+ },
205
+ },
206
+ },
207
+ {
208
+ "type": "function",
209
+ "function": {
210
+ "name": "get_band_statistics",
211
+ "description": "Get statistics (min, max, mean) for spectral bands.",
212
+ "parameters": {
213
+ "type": "object",
214
+ "properties": {
215
+ "zarr_url": {
216
+ "type": "string",
217
+ "description": "URL to the Zarr asset",
218
+ },
219
+ "bands": {
220
+ "type": "array",
221
+ "items": {"type": "string"},
222
+ "description": "List of band names to analyze",
223
+ },
224
+ },
225
+ "required": ["zarr_url"],
226
+ },
227
+ },
228
+ },
229
+ ]
230
+
231
+
232
+ class GeoMindAgent:
233
+ """
234
+ GeoMind - An AI agent for geospatial analysis with Sentinel-2 imagery.
235
+
236
+ Uses OpenRouter API for access to multiple AI models.
237
+ """
238
+
239
+ def __init__(self, model: Optional[str] = None):
240
+ """
241
+ Initialize the GeoMind agent.
242
+
243
+ Args:
244
+ model: Model name (default: xiaomi/mimo-v2-flash:free)
245
+ """
246
+ self.provider = "openrouter"
247
+ self.api_key = OPENROUTER_API_KEY
248
+ self.model_name = model or OPENROUTER_MODEL
249
+ self.base_url = OPENROUTER_API_URL
250
+
251
+ if not self.api_key:
252
+ raise ValueError(
253
+ "OpenRouter API key required. Set OPENROUTER_API_KEY in .env file.\n"
254
+ "Get your API key at: https://openrouter.ai/settings/keys"
255
+ )
256
+
257
+ print(f"🚀 GeoMind Agent initialized with {self.model_name} (OpenRouter)")
258
+ print(f" API URL: {self.base_url}")
259
+
260
+ # Create OpenAI-compatible client
261
+ self.client = OpenAI(base_url=self.base_url, api_key=self.api_key)
262
+
263
+ # Chat history
264
+ self.history = []
265
+
266
+ # Add system message
267
+ self.system_prompt = self._get_system_prompt()
268
+
269
+ def _get_system_prompt(self) -> str:
270
+ """Get the system prompt for the agent."""
271
+ return f"""You are GeoMind, an expert AI assistant specialized in geospatial analysis
272
+ and satellite imagery. You help users find, analyze, and visualize Sentinel-2 satellite data
273
+ from the EOPF (ESA Earth Observation Processing Framework) catalog.
274
+
275
+ Your capabilities include:
276
+ 1. **Search**: Find Sentinel-2 L2A imagery by location, date, and cloud cover
277
+ 2. **Geocoding**: Convert place names to coordinates for searching
278
+ 3. **Visualization**: Create RGB composites and NDVI maps from imagery
279
+ 4. **Analysis**: Calculate spectral indices and band statistics
280
+
281
+ Key information:
282
+ - Data source: EOPF STAC API (https://stac.core.eopf.eodc.eu)
283
+ - Satellite: Sentinel-2 (L2A surface reflectance products)
284
+ - Bands available: B01-B12 at 10m, 20m, or 60m resolution
285
+ - Current date: {datetime.now().strftime('%Y-%m-%d')}
286
+
287
+ When users ask for imagery:
288
+ 1. First use get_bbox_from_location or list_recent_imagery to search
289
+ 2. Present the results clearly with key metadata
290
+ 3. Offer to create visualizations if data is found
291
+
292
+ Always explain what you're doing and interpret results in a helpful way."""
293
+
294
+ def _execute_function(self, name: str, args: dict) -> dict:
295
+ """Execute a function call and return the result."""
296
+ print(f" 🔧 Executing: {name}({args})")
297
+
298
+ if name not in TOOL_FUNCTIONS:
299
+ return {"error": f"Unknown function: {name}"}
300
+
301
+ try:
302
+ result = TOOL_FUNCTIONS[name](**args)
303
+ return result
304
+ except Exception as e:
305
+ return {"error": str(e)}
306
+
307
+ def chat(self, message: str, verbose: bool = True) -> str:
308
+ """
309
+ Send a message to the agent and get a response.
310
+ """
311
+ if verbose:
312
+ print(f"\n💬 User: {message}")
313
+ print("🤔 Processing...")
314
+
315
+ # Add user message to history
316
+ self.history.append({"role": "user", "content": message})
317
+
318
+ # Build messages with system prompt
319
+ messages = [{"role": "system", "content": self.system_prompt}] + self.history
320
+
321
+ max_iterations = 10
322
+ iteration = 0
323
+
324
+ while iteration < max_iterations:
325
+ iteration += 1
326
+
327
+ # Call the model
328
+ response = self.client.chat.completions.create(
329
+ model=self.model_name,
330
+ messages=messages,
331
+ tools=TOOLS,
332
+ tool_choice="auto",
333
+ max_tokens=4096,
334
+ )
335
+
336
+ assistant_message = response.choices[0].message
337
+
338
+ # Check if there are tool calls
339
+ if assistant_message.tool_calls:
340
+ # Add assistant message with tool calls to messages
341
+ messages.append(
342
+ {
343
+ "role": "assistant",
344
+ "content": assistant_message.content or "",
345
+ "tool_calls": [
346
+ {
347
+ "id": tc.id,
348
+ "type": "function",
349
+ "function": {
350
+ "name": tc.function.name,
351
+ "arguments": tc.function.arguments,
352
+ },
353
+ }
354
+ for tc in assistant_message.tool_calls
355
+ ],
356
+ }
357
+ )
358
+
359
+ # Execute each tool call
360
+ for tool_call in assistant_message.tool_calls:
361
+ func_name = tool_call.function.name
362
+ func_args = json.loads(tool_call.function.arguments)
363
+
364
+ result = self._execute_function(func_name, func_args)
365
+
366
+ # Add tool result to messages
367
+ messages.append(
368
+ {
369
+ "role": "tool",
370
+ "tool_call_id": tool_call.id,
371
+ "content": json.dumps(result, default=str),
372
+ }
373
+ )
374
+ else:
375
+ # No tool calls, we have a final response
376
+ final_text = assistant_message.content or ""
377
+
378
+ # Add to history
379
+ self.history.append({"role": "assistant", "content": final_text})
380
+
381
+ if verbose:
382
+ print(f"\n🌍 GeoMind: {final_text}")
383
+
384
+ return final_text
385
+
386
+ return "Max iterations reached."
387
+
388
+ def reset(self):
389
+ """Reset the chat session."""
390
+ self.history = []
391
+ print("🔄 Chat session reset")
392
+
393
+
394
+ def main(model: Optional[str] = None):
395
+ """Main entry point for CLI usage."""
396
+ import sys
397
+
398
+ print("=" * 60)
399
+ print("🌍 GeoMind - Geospatial AI Agent")
400
+ print("=" * 60)
401
+ print("Powered by OpenRouter | Sentinel-2 Imagery")
402
+ print("Type 'quit' or 'exit' to end the session")
403
+ print("Type 'reset' to start a new conversation")
404
+ print("=" * 60)
405
+
406
+ try:
407
+ agent = GeoMindAgent(model=model)
408
+ except ValueError as e:
409
+ print(f"\n❌ Error: {e}")
410
+ sys.exit(1)
411
+ except Exception as e:
412
+ print(f"\n❌ Error: {e}")
413
+ print("\nPlease check your API key and internet connection.")
414
+ sys.exit(1)
415
+
416
+ while True:
417
+ try:
418
+ user_input = input("\n💬 You: ").strip()
419
+
420
+ if not user_input:
421
+ continue
422
+
423
+ if user_input.lower() in ["quit", "exit", "q"]:
424
+ print("\n👋 Goodbye!")
425
+ break
426
+
427
+ if user_input.lower() == "reset":
428
+ agent.reset()
429
+ continue
430
+
431
+ agent.chat(user_input)
432
+
433
+ except KeyboardInterrupt:
434
+ print("\n\n👋 Goodbye!")
435
+ break
436
+ except Exception as e:
437
+ print(f"\n❌ Error: {e}")
438
+
439
+
440
+ if __name__ == "__main__":
441
+ main()