agenticearth 0.1.0__tar.gz
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.
- agenticearth-0.1.0/.gitignore +64 -0
- agenticearth-0.1.0/PKG-INFO +16 -0
- agenticearth-0.1.0/agenticearth/__init__.py +40 -0
- agenticearth-0.1.0/agenticearth/cli.py +703 -0
- agenticearth-0.1.0/agenticearth/client.py +295 -0
- agenticearth-0.1.0/agenticearth/config.py +46 -0
- agenticearth-0.1.0/pyproject.toml +30 -0
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
|
|
2
|
+
# ── Python ────────────────────────────────────────────────────────────────────
|
|
3
|
+
__pycache__/
|
|
4
|
+
*.py[cod]
|
|
5
|
+
*.pyo
|
|
6
|
+
*.pyd
|
|
7
|
+
*.egg-info/
|
|
8
|
+
dist/
|
|
9
|
+
build/
|
|
10
|
+
.eggs/
|
|
11
|
+
|
|
12
|
+
# ── Virtual environments ──────────────────────────────────────────────────────
|
|
13
|
+
.venv/
|
|
14
|
+
venv/
|
|
15
|
+
env/
|
|
16
|
+
xyzeus-env/
|
|
17
|
+
|
|
18
|
+
# ── Environment & secrets ─────────────────────────────────────────────────────
|
|
19
|
+
.env
|
|
20
|
+
.env.local
|
|
21
|
+
.env.*.local
|
|
22
|
+
data/secrets.toml
|
|
23
|
+
|
|
24
|
+
# ── Data & cache ──────────────────────────────────────────────────────────────
|
|
25
|
+
/data/
|
|
26
|
+
/cache/
|
|
27
|
+
*.parquet
|
|
28
|
+
*.las
|
|
29
|
+
*.laz
|
|
30
|
+
|
|
31
|
+
# ── Static bundled datasets (must deploy to Railway) ──────────────────────────
|
|
32
|
+
!xyzeus/services/fetch/static/*.parquet
|
|
33
|
+
|
|
34
|
+
# ── Generated outputs ─────────────────────────────────────────────────────────
|
|
35
|
+
*.log
|
|
36
|
+
/*.html
|
|
37
|
+
/pmtiles/
|
|
38
|
+
|
|
39
|
+
# ── Test & tooling caches ─────────────────────────────────────────────────────
|
|
40
|
+
.pytest_cache/
|
|
41
|
+
.mypy_cache/
|
|
42
|
+
.ruff_cache/
|
|
43
|
+
|
|
44
|
+
# ── OS ────────────────────────────────────────────────────────────────────────
|
|
45
|
+
.DS_Store
|
|
46
|
+
Thumbs.db
|
|
47
|
+
|
|
48
|
+
# ── Editors ───────────────────────────────────────────────────────────────────
|
|
49
|
+
.idea/
|
|
50
|
+
.vscode/
|
|
51
|
+
*.iml
|
|
52
|
+
|
|
53
|
+
# ── Claude Code ───────────────────────────────────────────────────────────────
|
|
54
|
+
.claude/
|
|
55
|
+
|
|
56
|
+
# ── Notebooks (local scratch) ─────────────────────────────────────────────────
|
|
57
|
+
xyzeus_testing.ipynb
|
|
58
|
+
|
|
59
|
+
# ── Frontend ──────────────────────────────────────────────────────────────────
|
|
60
|
+
frontend/node_modules/
|
|
61
|
+
frontend/dist/
|
|
62
|
+
frontend/.env
|
|
63
|
+
frontend/.env.local
|
|
64
|
+
frontend/.env.*.local
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: agenticearth
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python SDK and CLI for Agentic Earth — 150+ live geospatial datasets via natural language
|
|
5
|
+
Project-URL: Homepage, https://agenticearth.app
|
|
6
|
+
Project-URL: Documentation, https://docs.agenticearth.app
|
|
7
|
+
Project-URL: Repository, https://github.com/ajpaladi/xyzeus
|
|
8
|
+
License: MIT
|
|
9
|
+
Keywords: ai,cli,geospatial,gis,maps
|
|
10
|
+
Requires-Python: >=3.9
|
|
11
|
+
Requires-Dist: click>=8.1
|
|
12
|
+
Requires-Dist: httpx>=0.27
|
|
13
|
+
Requires-Dist: rich>=13.0
|
|
14
|
+
Provides-Extra: geo
|
|
15
|
+
Requires-Dist: geopandas>=0.14; extra == 'geo'
|
|
16
|
+
Requires-Dist: pandas>=2.0; extra == 'geo'
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Agentic Earth Python SDK."""
|
|
2
|
+
from .client import AgenticEarth, AgenticEarthError, AuthError, InsufficientCreditsError, QueryResult, StreamEvent
|
|
3
|
+
from .config import get_api_key, get_base_url, save_credentials
|
|
4
|
+
|
|
5
|
+
_default_client: AgenticEarth | None = None
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _get_client() -> AgenticEarth:
|
|
9
|
+
global _default_client
|
|
10
|
+
if _default_client is None:
|
|
11
|
+
_default_client = AgenticEarth()
|
|
12
|
+
return _default_client
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def query(prompt: str, **kwargs) -> QueryResult:
|
|
16
|
+
"""Run an agent query with the default client.
|
|
17
|
+
|
|
18
|
+
Example:
|
|
19
|
+
import agenticearth as ae
|
|
20
|
+
result = ae.query("conflict events in Sudan last 30 days")
|
|
21
|
+
result.save("sudan.geojson")
|
|
22
|
+
"""
|
|
23
|
+
return _get_client().query(prompt, **kwargs)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def upload(file_path: str, **kwargs) -> dict:
|
|
27
|
+
"""Upload a file to ZeusLM."""
|
|
28
|
+
return _get_client().upload(file_path, **kwargs)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"AgenticEarth",
|
|
33
|
+
"AgenticEarthError",
|
|
34
|
+
"AuthError",
|
|
35
|
+
"InsufficientCreditsError",
|
|
36
|
+
"QueryResult",
|
|
37
|
+
"StreamEvent",
|
|
38
|
+
"query",
|
|
39
|
+
"upload",
|
|
40
|
+
]
|
|
@@ -0,0 +1,703 @@
|
|
|
1
|
+
"""Agentic Earth CLI — ae ask / ae chat / ae resume / ae upload / ae login."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import secrets
|
|
6
|
+
import sys
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import click
|
|
11
|
+
|
|
12
|
+
try:
|
|
13
|
+
from rich.console import Console
|
|
14
|
+
from rich.panel import Panel
|
|
15
|
+
from rich.text import Text
|
|
16
|
+
from rich import print as rprint
|
|
17
|
+
_rich = True
|
|
18
|
+
except ImportError:
|
|
19
|
+
_rich = False
|
|
20
|
+
|
|
21
|
+
_MAX_WIDTH = 100
|
|
22
|
+
console = Console(width=min((Console().width or _MAX_WIDTH), _MAX_WIDTH)) if _rich else None
|
|
23
|
+
|
|
24
|
+
_SESSIONS_DIR = Path.home() / ".agenticearth" / "sessions"
|
|
25
|
+
_LAST_SESSION = _SESSIONS_DIR / ".last"
|
|
26
|
+
|
|
27
|
+
_GOLD = "#C4A46B"
|
|
28
|
+
_MUTED = "#8A7455"
|
|
29
|
+
_DIM = "#5C4F3A"
|
|
30
|
+
|
|
31
|
+
# ── Helpers ───────────────────────────────────────────────────────────────────
|
|
32
|
+
|
|
33
|
+
def _print_banner() -> None:
|
|
34
|
+
if not _rich or not console:
|
|
35
|
+
print("\n Agentic Earth — 150+ live geospatial datasets\n")
|
|
36
|
+
return
|
|
37
|
+
from rich.text import Text
|
|
38
|
+
gold = _GOLD
|
|
39
|
+
base_col = _DIM
|
|
40
|
+
peak_pad = 12
|
|
41
|
+
num_rows = 10
|
|
42
|
+
globe_row = 6
|
|
43
|
+
console.print()
|
|
44
|
+
for i in range(num_rows - 1):
|
|
45
|
+
inner = i * 2
|
|
46
|
+
t = Text(" " * (peak_pad - i))
|
|
47
|
+
t.append("╱", style=f"bold {gold}")
|
|
48
|
+
if i == globe_row:
|
|
49
|
+
side = (inner - 2) // 2
|
|
50
|
+
t.append(" " * side + "🌍" + " " * side)
|
|
51
|
+
else:
|
|
52
|
+
t.append(" " * inner)
|
|
53
|
+
t.append("╲", style=f"bold {gold}")
|
|
54
|
+
console.print(t)
|
|
55
|
+
# base
|
|
56
|
+
t = Text(" " * (peak_pad - num_rows + 1))
|
|
57
|
+
t.append("╱", style=f"bold {gold}")
|
|
58
|
+
t.append("─" * ((num_rows - 1) * 2), style=base_col)
|
|
59
|
+
t.append("╲", style=f"bold {gold}")
|
|
60
|
+
console.print(t)
|
|
61
|
+
console.print()
|
|
62
|
+
console.print(Text.from_markup(f" [bold {gold}]A G E N T I C E A R T H[/bold {gold}]"))
|
|
63
|
+
console.print(Text.from_markup(f" [{base_col}]150+ live datasets · clustering · hotspots · SQL · natural language[/{base_col}]"))
|
|
64
|
+
console.print()
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _print(msg: str, style: str = "") -> None:
|
|
68
|
+
if _rich and console:
|
|
69
|
+
console.print(msg, style=style)
|
|
70
|
+
else:
|
|
71
|
+
print(msg)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _print_tool_event(event) -> None:
|
|
75
|
+
"""Print thinking / tool_start / tool_done events. Text delta handled separately."""
|
|
76
|
+
if event.type == "thinking":
|
|
77
|
+
_print(f" [dim]● thinking…[/dim]" if _rich else " ● thinking…")
|
|
78
|
+
elif event.type == "tool_start":
|
|
79
|
+
args_str = json.dumps(event.args or {})
|
|
80
|
+
if len(args_str) > 80:
|
|
81
|
+
args_str = args_str[:80] + "…"
|
|
82
|
+
_print(f" [cyan]▶ {event.tool}[/cyan] [dim]{args_str}[/dim]" if _rich
|
|
83
|
+
else f" ▶ {event.tool} {args_str}")
|
|
84
|
+
elif event.type == "tool_done":
|
|
85
|
+
count = f" ({event.count} features)" if event.count else ""
|
|
86
|
+
key = f" key={event.result_key}" if event.result_key else ""
|
|
87
|
+
_print(f" [green]✓ {event.tool}{count}[/green][dim]{key}[/dim]" if _rich
|
|
88
|
+
else f" ✓ {event.tool}{count}{key}")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _live_query(client, prompt: str, history: list | None = None, on_result_key=None):
|
|
92
|
+
"""Run a query, streaming text live and collecting result keys. Returns QueryResult."""
|
|
93
|
+
from .client import InsufficientCreditsError
|
|
94
|
+
|
|
95
|
+
streaming = [False]
|
|
96
|
+
|
|
97
|
+
def on_event(event):
|
|
98
|
+
if event.type == "text_delta" and event.text:
|
|
99
|
+
if not streaming[0]:
|
|
100
|
+
print()
|
|
101
|
+
streaming[0] = True
|
|
102
|
+
print(event.text, end="", flush=True)
|
|
103
|
+
else:
|
|
104
|
+
_print_tool_event(event)
|
|
105
|
+
if on_result_key and event.type == "tool_done" and event.result_key:
|
|
106
|
+
on_result_key(event.result_key)
|
|
107
|
+
|
|
108
|
+
result = client.query(prompt, history=history, on_event=on_event)
|
|
109
|
+
|
|
110
|
+
if streaming[0]:
|
|
111
|
+
print()
|
|
112
|
+
elif result.answer:
|
|
113
|
+
# no text_delta — render answer formatted
|
|
114
|
+
print()
|
|
115
|
+
if _rich and console:
|
|
116
|
+
from rich.markdown import Markdown as Md
|
|
117
|
+
console.print(Md(result.answer))
|
|
118
|
+
else:
|
|
119
|
+
print(result.answer)
|
|
120
|
+
|
|
121
|
+
return result
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _plotly_html(plotly_json: dict) -> str:
|
|
125
|
+
"""Wrap a Plotly JSON spec in a minimal self-contained HTML page."""
|
|
126
|
+
import json as _json
|
|
127
|
+
spec = _json.dumps(plotly_json)
|
|
128
|
+
return f"""<!DOCTYPE html>
|
|
129
|
+
<html>
|
|
130
|
+
<head>
|
|
131
|
+
<meta charset="utf-8">
|
|
132
|
+
<title>Agentic Earth Chart</title>
|
|
133
|
+
<script src="https://cdn.plot.ly/plotly-2.32.0.min.js"></script>
|
|
134
|
+
<style>body{{margin:0;background:#0d0d1a}}#chart{{width:100vw;height:100vh}}</style>
|
|
135
|
+
</head>
|
|
136
|
+
<body>
|
|
137
|
+
<div id="chart"></div>
|
|
138
|
+
<script>Plotly.newPlot('chart',{spec}.data,{spec}.layout,{{responsive:true,displayModeBar:true}})</script>
|
|
139
|
+
</body>
|
|
140
|
+
</html>"""
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _save_session(session_id: str, history: list[dict]) -> None:
|
|
144
|
+
_SESSIONS_DIR.mkdir(parents=True, exist_ok=True)
|
|
145
|
+
path = _SESSIONS_DIR / f"{session_id}.json"
|
|
146
|
+
path.write_text(json.dumps({
|
|
147
|
+
"id": session_id,
|
|
148
|
+
"updated_at": datetime.now(timezone.utc).isoformat(),
|
|
149
|
+
"history": history,
|
|
150
|
+
}, indent=2))
|
|
151
|
+
_LAST_SESSION.write_text(session_id)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _load_session(session_id: str | None) -> tuple[str, list[dict]]:
|
|
155
|
+
if not session_id:
|
|
156
|
+
if _LAST_SESSION.exists():
|
|
157
|
+
session_id = _LAST_SESSION.read_text().strip()
|
|
158
|
+
else:
|
|
159
|
+
raise click.ClickException("No previous session found. Start one with `ae chat`.")
|
|
160
|
+
path = _SESSIONS_DIR / f"{session_id}.json"
|
|
161
|
+
if not path.exists():
|
|
162
|
+
raise click.ClickException(f"Session '{session_id}' not found.")
|
|
163
|
+
data = json.loads(path.read_text())
|
|
164
|
+
return session_id, data["history"]
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _run_chat_loop(client, history: list[dict], session_id: str) -> None:
|
|
168
|
+
"""Core interactive loop shared by `ae chat` and `ae resume`."""
|
|
169
|
+
from .client import InsufficientCreditsError
|
|
170
|
+
|
|
171
|
+
_print(
|
|
172
|
+
f"\n[bold]Agentic Earth[/bold] [dim]session {session_id}[/dim]\n"
|
|
173
|
+
f"[dim]Commands: /view <key> /save <file> /upload <file> /credits /datasets /sessions /clear /history /exit[/dim]\n"
|
|
174
|
+
f"[dim]150+ live datasets · clustering · hotspots · SQL · enrichment[/dim]\n"
|
|
175
|
+
if _rich else
|
|
176
|
+
f"\nAgentic Earth session {session_id}\n"
|
|
177
|
+
f"Commands: /view <key> /save <file> /upload <file> /credits /datasets /sessions /clear /history /exit\n"
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
last_result_keys: list[str] = []
|
|
181
|
+
|
|
182
|
+
while True:
|
|
183
|
+
try:
|
|
184
|
+
user_input = input(" > ").strip()
|
|
185
|
+
except (EOFError, KeyboardInterrupt):
|
|
186
|
+
_print("\n")
|
|
187
|
+
break
|
|
188
|
+
|
|
189
|
+
if not user_input:
|
|
190
|
+
continue
|
|
191
|
+
|
|
192
|
+
# ── In-session slash commands ────────────────────────────────────────
|
|
193
|
+
if user_input.startswith("/"):
|
|
194
|
+
parts = user_input.split(None, 1)
|
|
195
|
+
cmd = parts[0].lower()
|
|
196
|
+
arg = parts[1].strip() if len(parts) > 1 else ""
|
|
197
|
+
|
|
198
|
+
if cmd in ("/exit", "/quit", "/q"):
|
|
199
|
+
break
|
|
200
|
+
|
|
201
|
+
elif cmd == "/clear":
|
|
202
|
+
history.clear()
|
|
203
|
+
last_result_keys.clear()
|
|
204
|
+
_print("[dim]Conversation cleared.[/dim]" if _rich else "Conversation cleared.")
|
|
205
|
+
|
|
206
|
+
elif cmd == "/history":
|
|
207
|
+
if not history:
|
|
208
|
+
_print("[dim]No history yet.[/dim]" if _rich else "No history yet.")
|
|
209
|
+
for msg in history:
|
|
210
|
+
role = "You" if msg["role"] == "user" else " AE"
|
|
211
|
+
preview = msg["content"][:100].replace("\n", " ")
|
|
212
|
+
_print(f"[dim]{role}:[/dim] {preview}…" if _rich else f"{role}: {preview}…")
|
|
213
|
+
|
|
214
|
+
elif cmd == "/save":
|
|
215
|
+
if not arg:
|
|
216
|
+
_print("[yellow]Usage: /save <filename.geojson|.csv|.parquet>[/yellow]" if _rich
|
|
217
|
+
else "Usage: /save <filename>")
|
|
218
|
+
elif not last_result_keys:
|
|
219
|
+
_print("[yellow]No result available to save yet.[/yellow]" if _rich
|
|
220
|
+
else "No result available yet.")
|
|
221
|
+
else:
|
|
222
|
+
ext = Path(arg).suffix.lstrip(".") or "geojson"
|
|
223
|
+
try:
|
|
224
|
+
saved = client.save_result(last_result_keys[0], Path(arg), format=ext)
|
|
225
|
+
_print(f"[green]✓ Saved → {saved}[/green]" if _rich else f"✓ Saved → {saved}")
|
|
226
|
+
except Exception as exc:
|
|
227
|
+
_print(f"[red]✗ Save failed: {exc}[/red]" if _rich else f"✗ Save failed: {exc}")
|
|
228
|
+
|
|
229
|
+
elif cmd == "/upload":
|
|
230
|
+
if not arg:
|
|
231
|
+
_print("[yellow]Usage: /upload <filepath>[/yellow]" if _rich
|
|
232
|
+
else "Usage: /upload <filepath>")
|
|
233
|
+
else:
|
|
234
|
+
p = Path(arg)
|
|
235
|
+
if not p.exists():
|
|
236
|
+
_print(f"[red]File not found: {p}[/red]" if _rich else f"File not found: {p}")
|
|
237
|
+
else:
|
|
238
|
+
_print(f" [cyan]↑ Uploading {p.name}…[/cyan]" if _rich else f" ↑ Uploading {p.name}…")
|
|
239
|
+
try:
|
|
240
|
+
meta = client.upload(str(p))
|
|
241
|
+
dk = meta.get("dataset_key", "?")
|
|
242
|
+
_print(f" [green]✓ Uploaded[/green] [dim]dataset_key={dk}[/dim]" if _rich
|
|
243
|
+
else f" ✓ Uploaded dataset_key={dk}")
|
|
244
|
+
history.append({"role": "user", "content": f"I have uploaded a dataset with key '{dk}'."})
|
|
245
|
+
history.append({"role": "assistant", "content": f"Got it — dataset key `{dk}` is loaded and ready. What would you like to do with it?"})
|
|
246
|
+
_save_session(session_id, history)
|
|
247
|
+
except Exception as exc:
|
|
248
|
+
_print(f"[red]✗ Upload failed: {exc}[/red]" if _rich else f"✗ Upload failed: {exc}")
|
|
249
|
+
|
|
250
|
+
elif cmd == "/credits":
|
|
251
|
+
try:
|
|
252
|
+
b = client.balance()
|
|
253
|
+
tier = b.get("tier", "?")
|
|
254
|
+
remaining = b.get("credits_remaining", "?")
|
|
255
|
+
monthly = b.get("credits_monthly", "?")
|
|
256
|
+
used = b.get("credits_used", "?")
|
|
257
|
+
pct = int(remaining / monthly * 100) if monthly else 0
|
|
258
|
+
bar_fill = int(pct / 5)
|
|
259
|
+
bar = "█" * bar_fill + "░" * (20 - bar_fill)
|
|
260
|
+
_print(
|
|
261
|
+
f"\n Tier: [bold]{tier}[/bold]\n"
|
|
262
|
+
f" Credits: [green]{remaining:,}[/green] / {monthly:,} [{pct}%]\n"
|
|
263
|
+
f" [{bar}]\n"
|
|
264
|
+
f" Used: {used:,} this cycle\n"
|
|
265
|
+
if _rich else
|
|
266
|
+
f"\n Tier: {tier} Credits: {remaining}/{monthly} ({pct}%) Used: {used}\n"
|
|
267
|
+
)
|
|
268
|
+
except Exception as exc:
|
|
269
|
+
_print(f"[red]✗ {exc}[/red]" if _rich else f"✗ {exc}")
|
|
270
|
+
|
|
271
|
+
elif cmd == "/datasets":
|
|
272
|
+
try:
|
|
273
|
+
items = client.datasets()
|
|
274
|
+
if not items:
|
|
275
|
+
_print("[dim]No datasets. Use /upload <file> to add one.[/dim]" if _rich
|
|
276
|
+
else "No datasets. Use /upload <file> to add one.")
|
|
277
|
+
else:
|
|
278
|
+
_print(f"\n [dim]{'DATASET KEY':<18} {'FILE':<30} ROWS[/dim]" if _rich
|
|
279
|
+
else f"\n {'DATASET KEY':<18} {'FILE':<30} ROWS")
|
|
280
|
+
for d in items:
|
|
281
|
+
key = d.get("dataset_key", "?")[:18]
|
|
282
|
+
name = (d.get("filename") or d.get("name") or "?")[:30]
|
|
283
|
+
rows = d.get("row_count", "?")
|
|
284
|
+
_print(f" [cyan]{key:<18}[/cyan] {name:<30} {rows}" if _rich
|
|
285
|
+
else f" {key:<18} {name:<30} {rows}")
|
|
286
|
+
_print("")
|
|
287
|
+
except Exception as exc:
|
|
288
|
+
_print(f"[red]✗ {exc}[/red]" if _rich else f"✗ {exc}")
|
|
289
|
+
|
|
290
|
+
elif cmd == "/view":
|
|
291
|
+
if not arg:
|
|
292
|
+
keys_hint = last_result_keys[0] if last_result_keys else "<result_key>"
|
|
293
|
+
_print(f"[yellow]Usage: /view {keys_hint}[/yellow]" if _rich
|
|
294
|
+
else f"Usage: /view <result_key>")
|
|
295
|
+
else:
|
|
296
|
+
try:
|
|
297
|
+
raw = client.fetch_raw(arg)
|
|
298
|
+
plotly_json = raw.get("plotly") or (raw.get("data", {}) or {}).get("plotly")
|
|
299
|
+
if plotly_json:
|
|
300
|
+
import tempfile, webbrowser
|
|
301
|
+
html = _plotly_html(plotly_json)
|
|
302
|
+
tmp = Path(tempfile.mktemp(suffix=".html", prefix="ae_chart_"))
|
|
303
|
+
tmp.write_text(html)
|
|
304
|
+
webbrowser.open(tmp.as_uri())
|
|
305
|
+
_print(f"[green]✓ Chart opened in browser[/green] [dim]{tmp}[/dim]" if _rich
|
|
306
|
+
else f"✓ Chart opened in browser {tmp}")
|
|
307
|
+
else:
|
|
308
|
+
_print("[yellow]Not a chart result. Use /save <file.geojson> instead.[/yellow]" if _rich
|
|
309
|
+
else "Not a chart result. Use /save <file.geojson> instead.")
|
|
310
|
+
except Exception as exc:
|
|
311
|
+
_print(f"[red]✗ {exc}[/red]" if _rich else f"✗ {exc}")
|
|
312
|
+
|
|
313
|
+
elif cmd == "/sessions":
|
|
314
|
+
if not _SESSIONS_DIR.exists():
|
|
315
|
+
_print("[dim]No saved sessions.[/dim]" if _rich else "No saved sessions.")
|
|
316
|
+
else:
|
|
317
|
+
files = sorted(_SESSIONS_DIR.glob("ae_sess_*.json"), key=lambda p: p.stat().st_mtime, reverse=True)
|
|
318
|
+
if not files:
|
|
319
|
+
_print("[dim]No saved sessions.[/dim]" if _rich else "No saved sessions.")
|
|
320
|
+
else:
|
|
321
|
+
_print(f"\n [dim]{'SESSION ID':<22} {'UPDATED':<22} TURNS[/dim]" if _rich
|
|
322
|
+
else f"\n {'SESSION ID':<22} {'UPDATED':<22} TURNS")
|
|
323
|
+
for p in files[:10]:
|
|
324
|
+
try:
|
|
325
|
+
import json as _json
|
|
326
|
+
data = _json.loads(p.read_text())
|
|
327
|
+
sid = data.get("id", p.stem)
|
|
328
|
+
turns = len(data.get("history", [])) // 2
|
|
329
|
+
updated = data.get("updated_at", "")[:16].replace("T", " ")
|
|
330
|
+
marker = " ← current" if sid == session_id else ""
|
|
331
|
+
_print(f" [cyan]{sid}[/cyan] [dim]{updated}[/dim] {turns} turns[green]{marker}[/green]"
|
|
332
|
+
if _rich else f" {sid} {updated} {turns} turns{marker}")
|
|
333
|
+
except Exception:
|
|
334
|
+
pass
|
|
335
|
+
_print("")
|
|
336
|
+
|
|
337
|
+
else:
|
|
338
|
+
_print(f"[yellow]Unknown command '{cmd}'. Try /view, /credits, /datasets, /sessions, /save, /upload, /clear, /history, /exit.[/yellow]"
|
|
339
|
+
if _rich else f"Unknown command: {cmd}")
|
|
340
|
+
continue
|
|
341
|
+
|
|
342
|
+
# ── Agent turn ────────────────────────────────────────────────────────
|
|
343
|
+
turn_result_keys: list[str] = []
|
|
344
|
+
|
|
345
|
+
try:
|
|
346
|
+
result = _live_query(
|
|
347
|
+
client, user_input, history=history,
|
|
348
|
+
on_result_key=turn_result_keys.append,
|
|
349
|
+
)
|
|
350
|
+
except InsufficientCreditsError:
|
|
351
|
+
_print("[red]✗ Insufficient credits. Visit agenticearth.io to upgrade.[/red]" if _rich
|
|
352
|
+
else "✗ Insufficient credits.")
|
|
353
|
+
continue
|
|
354
|
+
except Exception as exc:
|
|
355
|
+
_print(f"[red]✗ {exc}[/red]" if _rich else f"✗ {exc}")
|
|
356
|
+
continue
|
|
357
|
+
|
|
358
|
+
if result.result_keys:
|
|
359
|
+
last_result_keys[:] = result.result_keys
|
|
360
|
+
_print(f"\n[dim]Result keys: {', '.join(result.result_keys)} · /save <file> to export[/dim]\n"
|
|
361
|
+
if _rich else f"\nResult keys: {', '.join(result.result_keys)}\n")
|
|
362
|
+
|
|
363
|
+
history.append({"role": "user", "content": user_input})
|
|
364
|
+
history.append({"role": "assistant", "content": result.answer})
|
|
365
|
+
_save_session(session_id, history)
|
|
366
|
+
|
|
367
|
+
_save_session(session_id, history)
|
|
368
|
+
turns = len(history) // 2
|
|
369
|
+
_print(f"\n[dim]Session saved ({turns} turn{'s' if turns != 1 else ''}). "
|
|
370
|
+
f"Resume with: ae resume {session_id}[/dim]"
|
|
371
|
+
if _rich else
|
|
372
|
+
f"\nSession saved ({turns} turns). Resume with: ae resume {session_id}")
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
# ── Commands ──────────────────────────────────────────────────────────────────
|
|
376
|
+
|
|
377
|
+
@click.group()
|
|
378
|
+
@click.version_option(package_name="agenticearth")
|
|
379
|
+
def main():
|
|
380
|
+
"""Agentic Earth CLI — 150+ live geospatial datasets via natural language.\n\nGet started: ae login"""
|
|
381
|
+
pass
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
@main.command()
|
|
385
|
+
@click.option("--key", prompt="API key (from agenticearth.io/settings)", help="Your ae_sk_* API key.")
|
|
386
|
+
@click.option("--url", default=None, help="Custom API base URL (default: https://api.agenticearth.app).")
|
|
387
|
+
def login(key: str, url: str | None):
|
|
388
|
+
"""Save your API key to ~/.agenticearth/config.json."""
|
|
389
|
+
from .config import save_credentials
|
|
390
|
+
save_credentials(key.strip(), base_url=url)
|
|
391
|
+
_print(f"[green]✓ Logged in. Key saved to ~/.agenticearth/config.json[/green]" if _rich
|
|
392
|
+
else "✓ Logged in.")
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
@main.command()
|
|
396
|
+
def logout():
|
|
397
|
+
"""Clear saved credentials."""
|
|
398
|
+
from .config import clear_credentials
|
|
399
|
+
clear_credentials()
|
|
400
|
+
_print("Credentials cleared.")
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
@main.command(name="ask")
|
|
404
|
+
@click.argument("prompt", nargs=-1, required=True)
|
|
405
|
+
@click.option("--output", "-o", default=None, help="Save result to file (e.g. result.geojson, result.csv, result.parquet).")
|
|
406
|
+
@click.option("--file", "-f", default=None, type=click.Path(exists=True), help="Upload a file and analyse it (CSV, GeoJSON, Parquet, Shapefile zip, TIFF).")
|
|
407
|
+
@click.option("--url", default=None, envvar="AE_BASE_URL", help="API base URL override.")
|
|
408
|
+
def ask(prompt: tuple, output: str | None, file: str | None, url: str | None):
|
|
409
|
+
"""Ask the agent a one-shot question and stream the response.
|
|
410
|
+
|
|
411
|
+
\b
|
|
412
|
+
Examples:
|
|
413
|
+
ae ask "conflict events in Sudan last 30 days"
|
|
414
|
+
ae ask "cluster WiFi APs in Belarus" --output clusters.geojson
|
|
415
|
+
ae ask "NDBC buoys in Gulf of Mexico" -o buoys.csv
|
|
416
|
+
ae ask "what is this file" --file my_data.csv
|
|
417
|
+
"""
|
|
418
|
+
from .client import AgenticEarth, InsufficientCreditsError
|
|
419
|
+
|
|
420
|
+
full_prompt = " ".join(prompt)
|
|
421
|
+
try:
|
|
422
|
+
client = AgenticEarth(base_url=url)
|
|
423
|
+
except Exception as exc:
|
|
424
|
+
_print(f"[red]Error: {exc}[/red]" if _rich else f"Error: {exc}")
|
|
425
|
+
sys.exit(1)
|
|
426
|
+
|
|
427
|
+
if file:
|
|
428
|
+
_print(f" [cyan]↑ Uploading {file}…[/cyan]" if _rich else f" ↑ Uploading {file}…")
|
|
429
|
+
try:
|
|
430
|
+
meta = client.upload(file)
|
|
431
|
+
dataset_key = meta.get("dataset_key")
|
|
432
|
+
if not dataset_key:
|
|
433
|
+
raise ValueError(f"Upload succeeded but no dataset_key returned: {meta}")
|
|
434
|
+
_print(f" [green]✓ Uploaded[/green] [dim]dataset_key={dataset_key}[/dim]" if _rich
|
|
435
|
+
else f" ✓ Uploaded dataset_key={dataset_key}")
|
|
436
|
+
full_prompt = f"I have uploaded a dataset with key '{dataset_key}'. {full_prompt}"
|
|
437
|
+
except Exception as exc:
|
|
438
|
+
_print(f"[red]✗ Upload failed: {exc}[/red]" if _rich else f"✗ Upload failed: {exc}")
|
|
439
|
+
sys.exit(1)
|
|
440
|
+
|
|
441
|
+
_print(f"\n[bold]Agentic Earth[/bold] [dim]{' '.join(prompt)}[/dim]\n" if _rich
|
|
442
|
+
else f"\nAgentic Earth: {' '.join(prompt)}\n")
|
|
443
|
+
|
|
444
|
+
try:
|
|
445
|
+
result = _live_query(client, full_prompt)
|
|
446
|
+
except InsufficientCreditsError:
|
|
447
|
+
_print("[red]✗ Insufficient credits. Visit agenticearth.io to upgrade.[/red]" if _rich
|
|
448
|
+
else "✗ Insufficient credits.")
|
|
449
|
+
sys.exit(1)
|
|
450
|
+
except Exception as exc:
|
|
451
|
+
_print(f"[red]✗ {exc}[/red]" if _rich else f"✗ {exc}")
|
|
452
|
+
sys.exit(1)
|
|
453
|
+
|
|
454
|
+
if output and result.result_keys:
|
|
455
|
+
ext = Path(output).suffix.lstrip(".") or "geojson"
|
|
456
|
+
try:
|
|
457
|
+
saved = client.save_result(result.result_keys[0], Path(output), format=ext)
|
|
458
|
+
_print(f"\n[green]✓ Saved → {saved}[/green]" if _rich else f"\n✓ Saved → {saved}")
|
|
459
|
+
except Exception as exc:
|
|
460
|
+
_print(f"[red]✗ Save failed: {exc}[/red]" if _rich else f"✗ Save failed: {exc}")
|
|
461
|
+
elif result.result_keys:
|
|
462
|
+
_print(f"\n[dim]Result keys: {', '.join(result.result_keys)}[/dim]" if _rich
|
|
463
|
+
else f"\nResult keys: {', '.join(result.result_keys)}")
|
|
464
|
+
_print("[dim]Use --output result.geojson to save.[/dim]" if _rich
|
|
465
|
+
else "Use --output result.geojson to save.")
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
@main.command(name="chat")
|
|
469
|
+
@click.option("--url", default=None, envvar="AE_BASE_URL", help="API base URL override.")
|
|
470
|
+
def chat(url: str | None):
|
|
471
|
+
"""Start an interactive multi-turn session.
|
|
472
|
+
|
|
473
|
+
\b
|
|
474
|
+
In-session commands:
|
|
475
|
+
/save <file> export last result to geojson, csv, or parquet
|
|
476
|
+
/upload <file> upload a file mid-session
|
|
477
|
+
/clear reset conversation history
|
|
478
|
+
/history show conversation so far
|
|
479
|
+
/exit end session (also ctrl+c)
|
|
480
|
+
|
|
481
|
+
Example:
|
|
482
|
+
ae chat
|
|
483
|
+
> NDBC buoys in Gulf of Mexico
|
|
484
|
+
> now cluster them by wave height
|
|
485
|
+
> /save clusters.geojson
|
|
486
|
+
"""
|
|
487
|
+
from .client import AgenticEarth
|
|
488
|
+
|
|
489
|
+
try:
|
|
490
|
+
client = AgenticEarth(base_url=url)
|
|
491
|
+
except Exception as exc:
|
|
492
|
+
_print(f"[red]Error: {exc}[/red]" if _rich else f"Error: {exc}")
|
|
493
|
+
sys.exit(1)
|
|
494
|
+
|
|
495
|
+
_print_banner()
|
|
496
|
+
session_id = "ae_sess_" + secrets.token_hex(4)
|
|
497
|
+
_run_chat_loop(client, [], session_id)
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
@main.command(name="resume")
|
|
501
|
+
@click.argument("session_id", required=False, default=None)
|
|
502
|
+
@click.option("--url", default=None, envvar="AE_BASE_URL", help="API base URL override.")
|
|
503
|
+
def resume(session_id: str | None, url: str | None):
|
|
504
|
+
"""Resume a previous session.
|
|
505
|
+
|
|
506
|
+
\b
|
|
507
|
+
Examples:
|
|
508
|
+
ae resume # resumes last session
|
|
509
|
+
ae resume ae_sess_a1b2c3d4 # resumes specific session
|
|
510
|
+
"""
|
|
511
|
+
from .client import AgenticEarth
|
|
512
|
+
|
|
513
|
+
try:
|
|
514
|
+
client = AgenticEarth(base_url=url)
|
|
515
|
+
except Exception as exc:
|
|
516
|
+
_print(f"[red]Error: {exc}[/red]" if _rich else f"Error: {exc}")
|
|
517
|
+
sys.exit(1)
|
|
518
|
+
|
|
519
|
+
try:
|
|
520
|
+
sid, history = _load_session(session_id)
|
|
521
|
+
except click.ClickException as exc:
|
|
522
|
+
_print(f"[red]✗ {exc.format_message()}[/red]" if _rich else f"✗ {exc.format_message()}")
|
|
523
|
+
sys.exit(1)
|
|
524
|
+
|
|
525
|
+
_print_banner()
|
|
526
|
+
turns = len(history) // 2
|
|
527
|
+
_print(f"[dim]Resuming session {sid} ({turns} previous turn{'s' if turns != 1 else ''}).[/dim]"
|
|
528
|
+
if _rich else f"Resuming session {sid} ({turns} previous turns).")
|
|
529
|
+
_run_chat_loop(client, history, sid)
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
@main.command(name="view")
|
|
533
|
+
@click.argument("result_key")
|
|
534
|
+
@click.option("--url", default=None, envvar="AE_BASE_URL")
|
|
535
|
+
def view_cmd(result_key: str, url: str | None):
|
|
536
|
+
"""Open a chart result in the browser, or print the raw result.
|
|
537
|
+
|
|
538
|
+
\b
|
|
539
|
+
Example:
|
|
540
|
+
ae view create_chart_e8d1
|
|
541
|
+
"""
|
|
542
|
+
from .client import AgenticEarth
|
|
543
|
+
try:
|
|
544
|
+
client = AgenticEarth(base_url=url)
|
|
545
|
+
raw = client.fetch_raw(result_key)
|
|
546
|
+
plotly_json = raw.get("plotly") or (raw.get("data", {}) or {}).get("plotly")
|
|
547
|
+
if plotly_json:
|
|
548
|
+
import tempfile, webbrowser
|
|
549
|
+
html = _plotly_html(plotly_json)
|
|
550
|
+
tmp = Path(tempfile.mktemp(suffix=".html", prefix="ae_chart_"))
|
|
551
|
+
tmp.write_text(html)
|
|
552
|
+
webbrowser.open(tmp.as_uri())
|
|
553
|
+
_print(f"[green]✓ Chart opened in browser[/green] [dim]{tmp}[/dim]" if _rich
|
|
554
|
+
else f"✓ Chart opened in browser {tmp}")
|
|
555
|
+
else:
|
|
556
|
+
_print("[yellow]Not a chart result. Use `ae export` for geo data.[/yellow]" if _rich
|
|
557
|
+
else "Not a chart result. Use `ae export` for geo data.")
|
|
558
|
+
except Exception as exc:
|
|
559
|
+
_print(f"[red]✗ {exc}[/red]" if _rich else f"✗ {exc}")
|
|
560
|
+
sys.exit(1)
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
@main.command(name="export")
|
|
564
|
+
@click.argument("result_key")
|
|
565
|
+
@click.option("--output", "-o", required=True, help="Output file path (e.g. result.geojson).")
|
|
566
|
+
@click.option("--url", default=None, envvar="AE_BASE_URL")
|
|
567
|
+
def export(result_key: str, output: str, url: str | None):
|
|
568
|
+
"""Download a result by key to a file.
|
|
569
|
+
|
|
570
|
+
\b
|
|
571
|
+
Example:
|
|
572
|
+
ae export get_conflict_events_a1b2 --output events.geojson
|
|
573
|
+
"""
|
|
574
|
+
from .client import AgenticEarth
|
|
575
|
+
ext = Path(output).suffix.lstrip(".") or "geojson"
|
|
576
|
+
try:
|
|
577
|
+
client = AgenticEarth(base_url=url)
|
|
578
|
+
saved = client.save_result(result_key, Path(output), format=ext)
|
|
579
|
+
_print(f"[green]✓ Saved → {saved}[/green]" if _rich else f"✓ Saved → {saved}")
|
|
580
|
+
except Exception as exc:
|
|
581
|
+
_print(f"[red]✗ {exc}[/red]" if _rich else f"✗ {exc}")
|
|
582
|
+
sys.exit(1)
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
@main.command(name="upload")
|
|
586
|
+
@click.argument("file_path", type=click.Path(exists=True))
|
|
587
|
+
@click.option("--url", default=None, envvar="AE_BASE_URL")
|
|
588
|
+
def upload_cmd(file_path: str, url: str | None):
|
|
589
|
+
"""Upload a file to ZeusLM for analysis.
|
|
590
|
+
|
|
591
|
+
\b
|
|
592
|
+
Supported formats: CSV, GeoJSON, GeoPackage, Parquet, Shapefile (zip), TIFF.
|
|
593
|
+
|
|
594
|
+
Example:
|
|
595
|
+
ae upload my_data.csv
|
|
596
|
+
"""
|
|
597
|
+
from .client import AgenticEarth
|
|
598
|
+
try:
|
|
599
|
+
client = AgenticEarth(base_url=url)
|
|
600
|
+
_print(f"Uploading [cyan]{file_path}[/cyan]…" if _rich else f"Uploading {file_path}…")
|
|
601
|
+
meta = client.upload(file_path)
|
|
602
|
+
_print(f"[green]✓ Uploaded[/green] dataset_key=[cyan]{meta.get('dataset_key','?')}[/cyan] "
|
|
603
|
+
f"rows=[dim]{meta.get('row_count','?')}[/dim]" if _rich
|
|
604
|
+
else f"✓ Uploaded key={meta.get('dataset_key','?')} rows={meta.get('row_count','?')}")
|
|
605
|
+
except Exception as exc:
|
|
606
|
+
_print(f"[red]✗ {exc}[/red]" if _rich else f"✗ {exc}")
|
|
607
|
+
sys.exit(1)
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
@main.command(name="credits")
|
|
611
|
+
@click.option("--url", default=None, envvar="AE_BASE_URL")
|
|
612
|
+
def credits_cmd(url: str | None):
|
|
613
|
+
"""Show current credit balance and tier."""
|
|
614
|
+
from .client import AgenticEarth
|
|
615
|
+
try:
|
|
616
|
+
client = AgenticEarth(base_url=url)
|
|
617
|
+
b = client.balance()
|
|
618
|
+
tier = b.get("tier", "?")
|
|
619
|
+
remaining = b.get("credits_remaining", "?")
|
|
620
|
+
monthly = b.get("credits_monthly", "?")
|
|
621
|
+
used = b.get("credits_used", "?")
|
|
622
|
+
pct = int(remaining / monthly * 100) if monthly else 0
|
|
623
|
+
bar_fill = int(pct / 5)
|
|
624
|
+
bar = "█" * bar_fill + "░" * (20 - bar_fill)
|
|
625
|
+
_print(
|
|
626
|
+
f"\n Tier: [bold]{tier}[/bold]\n"
|
|
627
|
+
f" Credits: [green]{remaining:,}[/green] / {monthly:,} remaining [{pct}%]\n"
|
|
628
|
+
f" [{bar}]\n"
|
|
629
|
+
f" Used: {used:,} this cycle\n"
|
|
630
|
+
if _rich else
|
|
631
|
+
f"\n Tier: {tier}\n Credits: {remaining}/{monthly} ({pct}%)\n Used: {used}\n"
|
|
632
|
+
)
|
|
633
|
+
except Exception as exc:
|
|
634
|
+
_print(f"[red]✗ {exc}[/red]" if _rich else f"✗ {exc}")
|
|
635
|
+
sys.exit(1)
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
@main.command(name="sessions")
|
|
639
|
+
def sessions_cmd():
|
|
640
|
+
"""List saved chat sessions."""
|
|
641
|
+
if not _SESSIONS_DIR.exists():
|
|
642
|
+
_print("No sessions found." )
|
|
643
|
+
return
|
|
644
|
+
files = sorted(_SESSIONS_DIR.glob("ae_sess_*.json"), key=lambda p: p.stat().st_mtime, reverse=True)
|
|
645
|
+
if not files:
|
|
646
|
+
_print("No sessions found.")
|
|
647
|
+
return
|
|
648
|
+
last = _LAST_SESSION.read_text().strip() if _LAST_SESSION.exists() else ""
|
|
649
|
+
_print(f"\n {'SESSION ID':<22} {'UPDATED':<22} TURNS" if not _rich else
|
|
650
|
+
f"\n [dim]{'SESSION ID':<22} {'UPDATED':<22} TURNS[/dim]")
|
|
651
|
+
for p in files:
|
|
652
|
+
import json as _json
|
|
653
|
+
try:
|
|
654
|
+
data = _json.loads(p.read_text())
|
|
655
|
+
sid = data.get("id", p.stem)
|
|
656
|
+
turns = len(data.get("history", [])) // 2
|
|
657
|
+
updated = data.get("updated_at", "")[:16].replace("T", " ")
|
|
658
|
+
marker = " ←" if sid == last else ""
|
|
659
|
+
_print(f" [cyan]{sid}[/cyan] [dim]{updated}[/dim] {turns} turns[green]{marker}[/green]"
|
|
660
|
+
if _rich else f" {sid} {updated} {turns} turns{marker}")
|
|
661
|
+
except Exception:
|
|
662
|
+
pass
|
|
663
|
+
_print("")
|
|
664
|
+
|
|
665
|
+
|
|
666
|
+
@main.command(name="datasets")
|
|
667
|
+
@click.option("--url", default=None, envvar="AE_BASE_URL")
|
|
668
|
+
def datasets_cmd(url: str | None):
|
|
669
|
+
"""List uploaded ZeusLM datasets."""
|
|
670
|
+
from .client import AgenticEarth
|
|
671
|
+
try:
|
|
672
|
+
client = AgenticEarth(base_url=url)
|
|
673
|
+
items = client.datasets()
|
|
674
|
+
if not items:
|
|
675
|
+
_print("No datasets found. Use `ae upload <file>` or `/upload` in ae chat.")
|
|
676
|
+
return
|
|
677
|
+
_print(f"\n {'DATASET KEY':<18} {'FILE':<30} ROWS" if not _rich else
|
|
678
|
+
f"\n [dim]{'DATASET KEY':<18} {'FILE':<30} ROWS[/dim]")
|
|
679
|
+
for d in items:
|
|
680
|
+
key = d.get("dataset_key", "?")[:18]
|
|
681
|
+
name = (d.get("filename") or d.get("name") or "?")[:30]
|
|
682
|
+
rows = d.get("row_count", "?")
|
|
683
|
+
_print(f" [cyan]{key:<18}[/cyan] {name:<30} {rows}" if _rich
|
|
684
|
+
else f" {key:<18} {name:<30} {rows}")
|
|
685
|
+
_print("")
|
|
686
|
+
except Exception as exc:
|
|
687
|
+
_print(f"[red]✗ {exc}[/red]" if _rich else f"✗ {exc}")
|
|
688
|
+
sys.exit(1)
|
|
689
|
+
|
|
690
|
+
|
|
691
|
+
@main.command(name="whoami")
|
|
692
|
+
@click.option("--url", default=None, envvar="AE_BASE_URL")
|
|
693
|
+
def whoami(url: str | None):
|
|
694
|
+
"""Show current API key and base URL."""
|
|
695
|
+
from .config import get_api_key, get_base_url
|
|
696
|
+
key = get_api_key()
|
|
697
|
+
base = url or get_base_url()
|
|
698
|
+
if key:
|
|
699
|
+
masked = key[:10] + "…" + key[-4:]
|
|
700
|
+
_print(f"API key: [cyan]{masked}[/cyan]\nBase URL: [dim]{base}[/dim]" if _rich
|
|
701
|
+
else f"API key: {masked}\nBase URL: {base}")
|
|
702
|
+
else:
|
|
703
|
+
_print("[yellow]Not logged in. Run `ae login`.[/yellow]" if _rich else "Not logged in.")
|
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
"""Agentic Earth Python SDK client."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, Callable, Generator, Iterator
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
|
|
11
|
+
from .config import get_api_key, get_base_url
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class AgenticEarthError(Exception):
|
|
15
|
+
pass
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class AuthError(AgenticEarthError):
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class InsufficientCreditsError(AgenticEarthError):
|
|
23
|
+
pass
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class StreamEvent:
|
|
27
|
+
def __init__(self, data: dict):
|
|
28
|
+
self.type = data.get("type", "")
|
|
29
|
+
self.tool = data.get("tool")
|
|
30
|
+
self.args = data.get("args")
|
|
31
|
+
self.result_key = data.get("result_key")
|
|
32
|
+
self.count = data.get("count")
|
|
33
|
+
self.answer = data.get("answer")
|
|
34
|
+
self.turns = data.get("turns")
|
|
35
|
+
self.message = data.get("message")
|
|
36
|
+
self.result_type = data.get("result_type")
|
|
37
|
+
self.text = data.get("text") # text_delta chunks
|
|
38
|
+
self._raw = data
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class QueryResult:
|
|
42
|
+
"""Returned by client.query() after the stream completes."""
|
|
43
|
+
|
|
44
|
+
def __init__(self, answer: str, result_keys: list[str], client: "AgenticEarth"):
|
|
45
|
+
self.answer = answer
|
|
46
|
+
self.result_keys = result_keys
|
|
47
|
+
self._client = client
|
|
48
|
+
|
|
49
|
+
def __repr__(self) -> str:
|
|
50
|
+
return f"<QueryResult answer={self.answer[:60]!r} result_keys={self.result_keys}>"
|
|
51
|
+
|
|
52
|
+
def fetch(self, result_key: str | None = None, format: str = "geojson") -> Any:
|
|
53
|
+
"""Download a result as GeoDataFrame (requires geopandas) or raw dict."""
|
|
54
|
+
key = result_key or (self.result_keys[0] if self.result_keys else None)
|
|
55
|
+
if not key:
|
|
56
|
+
raise AgenticEarthError("No result_key available.")
|
|
57
|
+
return self._client.fetch_result(key, format=format)
|
|
58
|
+
|
|
59
|
+
def save(self, path: str, result_key: str | None = None) -> Path:
|
|
60
|
+
"""Save result to file. Format inferred from extension (.geojson, .csv, .parquet)."""
|
|
61
|
+
p = Path(path)
|
|
62
|
+
ext = p.suffix.lstrip(".") or "geojson"
|
|
63
|
+
key = result_key or (self.result_keys[0] if self.result_keys else None)
|
|
64
|
+
if not key:
|
|
65
|
+
raise AgenticEarthError("No result_key available.")
|
|
66
|
+
return self._client.save_result(key, path=p, format=ext)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class AgenticEarth:
|
|
70
|
+
"""Agentic Earth SDK client.
|
|
71
|
+
|
|
72
|
+
Usage:
|
|
73
|
+
import agenticearth as ae
|
|
74
|
+
result = ae.query("conflict events in Sudan last 30 days")
|
|
75
|
+
result.save("sudan.geojson")
|
|
76
|
+
"""
|
|
77
|
+
|
|
78
|
+
def __init__(
|
|
79
|
+
self,
|
|
80
|
+
api_key: str | None = None,
|
|
81
|
+
base_url: str | None = None,
|
|
82
|
+
timeout: float = 120.0,
|
|
83
|
+
):
|
|
84
|
+
self.api_key = api_key or get_api_key()
|
|
85
|
+
self.base_url = (base_url or get_base_url()).rstrip("/")
|
|
86
|
+
self.timeout = timeout
|
|
87
|
+
|
|
88
|
+
if not self.api_key:
|
|
89
|
+
raise AuthError(
|
|
90
|
+
"No API key found. Run `ae login` or set AE_API_KEY environment variable."
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
def _headers(self) -> dict:
|
|
94
|
+
return {
|
|
95
|
+
"Authorization": f"Bearer {self.api_key}",
|
|
96
|
+
"Content-Type": "application/json",
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
def _get_user_id(self) -> str:
|
|
100
|
+
"""Resolve and cache user_id from the current API key."""
|
|
101
|
+
if not hasattr(self, "_user_id_cache"):
|
|
102
|
+
with httpx.Client(timeout=10) as client:
|
|
103
|
+
resp = client.get(f"{self.base_url}/auth/whoami", headers=self._headers())
|
|
104
|
+
resp.raise_for_status()
|
|
105
|
+
self._user_id_cache: str = resp.json()["user_id"]
|
|
106
|
+
return self._user_id_cache
|
|
107
|
+
|
|
108
|
+
def _stream_agent(
|
|
109
|
+
self,
|
|
110
|
+
prompt: str,
|
|
111
|
+
history: list[dict] | None = None,
|
|
112
|
+
on_event: Callable[[StreamEvent], None] | None = None,
|
|
113
|
+
user_id: str = "",
|
|
114
|
+
) -> Generator[StreamEvent, None, None]:
|
|
115
|
+
"""Stream agent events from /agent/stream."""
|
|
116
|
+
payload = {
|
|
117
|
+
"query": prompt,
|
|
118
|
+
"user_id": user_id,
|
|
119
|
+
"zeus_model": "ZeusStandard",
|
|
120
|
+
"history": history or [],
|
|
121
|
+
"max_turns": 10,
|
|
122
|
+
"mode": "sdk",
|
|
123
|
+
}
|
|
124
|
+
with httpx.Client(timeout=self.timeout) as client:
|
|
125
|
+
with client.stream(
|
|
126
|
+
"POST",
|
|
127
|
+
f"{self.base_url}/agent/stream",
|
|
128
|
+
headers=self._headers(),
|
|
129
|
+
json=payload,
|
|
130
|
+
) as resp:
|
|
131
|
+
if resp.status_code == 401:
|
|
132
|
+
raise AuthError("Invalid API key.")
|
|
133
|
+
if resp.status_code != 200:
|
|
134
|
+
raise AgenticEarthError(f"Stream failed: {resp.status_code} {resp.text}")
|
|
135
|
+
|
|
136
|
+
buffer = ""
|
|
137
|
+
for chunk in resp.iter_text():
|
|
138
|
+
buffer += chunk
|
|
139
|
+
while "\n\n" in buffer:
|
|
140
|
+
block, buffer = buffer.split("\n\n", 1)
|
|
141
|
+
for line in block.splitlines():
|
|
142
|
+
if line.startswith("data: "):
|
|
143
|
+
raw = line[6:]
|
|
144
|
+
try:
|
|
145
|
+
event = StreamEvent(json.loads(raw))
|
|
146
|
+
if event.type == "error" and event.message == "insufficient_credits":
|
|
147
|
+
raise InsufficientCreditsError("Insufficient credits.")
|
|
148
|
+
if on_event:
|
|
149
|
+
on_event(event)
|
|
150
|
+
yield event
|
|
151
|
+
except (json.JSONDecodeError, InsufficientCreditsError):
|
|
152
|
+
raise
|
|
153
|
+
except Exception:
|
|
154
|
+
pass
|
|
155
|
+
|
|
156
|
+
def query(
|
|
157
|
+
self,
|
|
158
|
+
prompt: str,
|
|
159
|
+
history: list[dict] | None = None,
|
|
160
|
+
on_event: Callable[[StreamEvent], None] | None = None,
|
|
161
|
+
) -> QueryResult:
|
|
162
|
+
"""Run an agent query. Returns QueryResult with answer + result_keys.
|
|
163
|
+
|
|
164
|
+
Example:
|
|
165
|
+
result = ae.query("conflict events in Sudan last 30 days")
|
|
166
|
+
result.save("sudan.geojson")
|
|
167
|
+
"""
|
|
168
|
+
answer = ""
|
|
169
|
+
result_keys: list[str] = []
|
|
170
|
+
|
|
171
|
+
for event in self._stream_agent(prompt, history=history, on_event=on_event):
|
|
172
|
+
if event.type == "tool_done" and event.result_key:
|
|
173
|
+
result_keys.append(event.result_key)
|
|
174
|
+
elif event.type == "done":
|
|
175
|
+
answer = event.answer or ""
|
|
176
|
+
|
|
177
|
+
return QueryResult(answer=answer, result_keys=result_keys, client=self)
|
|
178
|
+
|
|
179
|
+
def fetch_raw(self, result_key: str) -> dict:
|
|
180
|
+
"""Fetch the raw stored result dict (no post-processing)."""
|
|
181
|
+
url = f"{self.base_url}/agent/results/{result_key}"
|
|
182
|
+
with httpx.Client(timeout=60) as client:
|
|
183
|
+
resp = client.get(url, headers=self._headers(), params={"geometry": "true"})
|
|
184
|
+
resp.raise_for_status()
|
|
185
|
+
return resp.json()
|
|
186
|
+
|
|
187
|
+
def fetch_result(self, result_key: str, format: str = "geojson") -> Any:
|
|
188
|
+
"""Fetch a stored result by key. Returns GeoDataFrame if geopandas available, else dict."""
|
|
189
|
+
url = f"{self.base_url}/agent/results/{result_key}"
|
|
190
|
+
params: dict = {"geometry": "true"}
|
|
191
|
+
if format == "parquet":
|
|
192
|
+
params["format"] = "parquet"
|
|
193
|
+
|
|
194
|
+
with httpx.Client(timeout=60) as client:
|
|
195
|
+
resp = client.get(url, headers=self._headers(), params=params)
|
|
196
|
+
resp.raise_for_status()
|
|
197
|
+
|
|
198
|
+
if format == "parquet":
|
|
199
|
+
try:
|
|
200
|
+
import geopandas as gpd
|
|
201
|
+
import io
|
|
202
|
+
return gpd.read_parquet(io.BytesIO(resp.content))
|
|
203
|
+
except ImportError:
|
|
204
|
+
raise AgenticEarthError("Install geopandas to use format='parquet': pip install agenticearth[geo]")
|
|
205
|
+
|
|
206
|
+
data = resp.json()
|
|
207
|
+
geojson = data.get("geojson") or data.get("data")
|
|
208
|
+
|
|
209
|
+
if geojson and isinstance(geojson, dict) and "features" in geojson:
|
|
210
|
+
try:
|
|
211
|
+
import geopandas as gpd
|
|
212
|
+
return gpd.GeoDataFrame.from_features(geojson["features"], crs="EPSG:4326")
|
|
213
|
+
except ImportError:
|
|
214
|
+
return geojson
|
|
215
|
+
|
|
216
|
+
return data
|
|
217
|
+
|
|
218
|
+
def save_result(self, result_key: str, path: Path, format: str = "geojson") -> Path:
|
|
219
|
+
"""Download result and write to file."""
|
|
220
|
+
if format in ("geojson", "json"):
|
|
221
|
+
url = f"{self.base_url}/agent/results/{result_key}"
|
|
222
|
+
with httpx.Client(timeout=60) as client:
|
|
223
|
+
resp = client.get(url, headers=self._headers(), params={"geometry": "true"})
|
|
224
|
+
resp.raise_for_status()
|
|
225
|
+
data = resp.json()
|
|
226
|
+
geojson = data.get("geojson") or data.get("data")
|
|
227
|
+
path.write_text(json.dumps(geojson, indent=2))
|
|
228
|
+
elif format == "csv":
|
|
229
|
+
url = f"{self.base_url}/agent/results/{result_key}"
|
|
230
|
+
with httpx.Client(timeout=60) as client:
|
|
231
|
+
resp = client.get(url, headers=self._headers(), params={"geometry": "false"})
|
|
232
|
+
resp.raise_for_status()
|
|
233
|
+
data = resp.json()
|
|
234
|
+
geojson = data.get("geojson") or data.get("data")
|
|
235
|
+
if geojson and "features" in geojson:
|
|
236
|
+
import csv, io
|
|
237
|
+
rows = [f.get("properties", {}) for f in geojson["features"]]
|
|
238
|
+
if rows:
|
|
239
|
+
out = io.StringIO()
|
|
240
|
+
w = csv.DictWriter(out, fieldnames=list(rows[0].keys()))
|
|
241
|
+
w.writeheader()
|
|
242
|
+
w.writerows(rows)
|
|
243
|
+
path.write_text(out.getvalue())
|
|
244
|
+
elif format == "parquet":
|
|
245
|
+
url = f"{self.base_url}/agent/results/{result_key}"
|
|
246
|
+
with httpx.Client(timeout=60) as client:
|
|
247
|
+
resp = client.get(url, headers=self._headers(), params={"format": "parquet"})
|
|
248
|
+
resp.raise_for_status()
|
|
249
|
+
path.write_bytes(resp.content)
|
|
250
|
+
else:
|
|
251
|
+
raise AgenticEarthError(f"Unknown format: {format}. Use geojson, csv, or parquet.")
|
|
252
|
+
|
|
253
|
+
return path
|
|
254
|
+
|
|
255
|
+
def balance(self) -> dict:
|
|
256
|
+
"""Return current credit balance and tier."""
|
|
257
|
+
user_id = self._get_user_id()
|
|
258
|
+
with httpx.Client(timeout=30) as client:
|
|
259
|
+
resp = client.get(
|
|
260
|
+
f"{self.base_url}/usage/balance",
|
|
261
|
+
headers=self._headers(),
|
|
262
|
+
params={"user_id": user_id},
|
|
263
|
+
)
|
|
264
|
+
resp.raise_for_status()
|
|
265
|
+
return resp.json()
|
|
266
|
+
|
|
267
|
+
def datasets(self) -> list:
|
|
268
|
+
"""List uploaded ZeusLM datasets for the current user."""
|
|
269
|
+
user_id = self._get_user_id()
|
|
270
|
+
with httpx.Client(timeout=30) as client:
|
|
271
|
+
resp = client.get(
|
|
272
|
+
f"{self.base_url}/zeusLM/datasets",
|
|
273
|
+
headers=self._headers(),
|
|
274
|
+
params={"user_id": user_id},
|
|
275
|
+
)
|
|
276
|
+
resp.raise_for_status()
|
|
277
|
+
return resp.json()
|
|
278
|
+
|
|
279
|
+
def upload(self, file_path: str | Path, filename: str | None = None) -> dict:
|
|
280
|
+
"""Upload a file to ZeusLM. Returns dataset metadata dict."""
|
|
281
|
+
p = Path(file_path)
|
|
282
|
+
if not p.exists():
|
|
283
|
+
raise AgenticEarthError(f"File not found: {p}")
|
|
284
|
+
name = filename or p.name
|
|
285
|
+
headers = {k: v for k, v in self._headers().items() if k != "Content-Type"}
|
|
286
|
+
with httpx.Client(timeout=120) as client:
|
|
287
|
+
with open(p, "rb") as f:
|
|
288
|
+
resp = client.post(
|
|
289
|
+
f"{self.base_url}/zeusLM/upload",
|
|
290
|
+
headers=headers,
|
|
291
|
+
files={"file": (name, f)},
|
|
292
|
+
data={"user_id": ""},
|
|
293
|
+
)
|
|
294
|
+
resp.raise_for_status()
|
|
295
|
+
return resp.json()
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Config file management — stores API key and base URL in ~/.agenticearth/config.json."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
_CONFIG_DIR = Path.home() / ".agenticearth"
|
|
9
|
+
_CONFIG_FILE = _CONFIG_DIR / "config.json"
|
|
10
|
+
|
|
11
|
+
DEFAULT_BASE_URL = "https://api.agenticearth.app"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _load() -> dict:
|
|
15
|
+
if _CONFIG_FILE.exists():
|
|
16
|
+
try:
|
|
17
|
+
return json.loads(_CONFIG_FILE.read_text())
|
|
18
|
+
except Exception:
|
|
19
|
+
pass
|
|
20
|
+
return {}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _save(data: dict) -> None:
|
|
24
|
+
_CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
|
25
|
+
_CONFIG_FILE.write_text(json.dumps(data, indent=2))
|
|
26
|
+
_CONFIG_FILE.chmod(0o600)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def get_api_key() -> str | None:
|
|
30
|
+
return os.environ.get("AE_API_KEY") or _load().get("api_key")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def get_base_url() -> str:
|
|
34
|
+
return os.environ.get("AE_BASE_URL") or _load().get("base_url") or DEFAULT_BASE_URL
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def save_credentials(api_key: str, base_url: str | None = None) -> None:
|
|
38
|
+
data = _load()
|
|
39
|
+
data["api_key"] = api_key
|
|
40
|
+
if base_url:
|
|
41
|
+
data["base_url"] = base_url
|
|
42
|
+
_save(data)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def clear_credentials() -> None:
|
|
46
|
+
_save({})
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "agenticearth"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Python SDK and CLI for Agentic Earth — 150+ live geospatial datasets via natural language"
|
|
9
|
+
requires-python = ">=3.9"
|
|
10
|
+
license = { text = "MIT" }
|
|
11
|
+
keywords = ["geospatial", "gis", "ai", "maps", "cli"]
|
|
12
|
+
dependencies = [
|
|
13
|
+
"httpx>=0.27",
|
|
14
|
+
"rich>=13.0",
|
|
15
|
+
"click>=8.1",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
[project.optional-dependencies]
|
|
19
|
+
geo = ["geopandas>=0.14", "pandas>=2.0"]
|
|
20
|
+
|
|
21
|
+
[project.scripts]
|
|
22
|
+
ae = "agenticearth.cli:main"
|
|
23
|
+
|
|
24
|
+
[project.urls]
|
|
25
|
+
Homepage = "https://agenticearth.app"
|
|
26
|
+
Documentation = "https://docs.agenticearth.app"
|
|
27
|
+
Repository = "https://github.com/ajpaladi/xyzeus"
|
|
28
|
+
|
|
29
|
+
[tool.hatch.build.targets.wheel]
|
|
30
|
+
packages = ["agenticearth"]
|