gotsimplified 0.1.0__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.
@@ -0,0 +1,6 @@
1
+ """Got Simplified Python client (test version)."""
2
+ from .client import Client
3
+ from .errors import GSError
4
+
5
+ __all__ = ["Client", "GSError"]
6
+ __version__ = "0.1.0"
gotsimplified/ask.py ADDED
@@ -0,0 +1,226 @@
1
+ """Plain-language requests, one app at a time: c.notes.ask(), c.files.ask(), c.datalake.ask().
2
+
3
+ The model only sees the tools of the app it is asked about, taken from the live server list,
4
+ so a new tool on the server is picked up without a client update.
5
+
6
+ Any tool whose name says it changes data (manage, mutate, share) waits for your confirmation.
7
+ Without a confirmation, the change is not run and the model is told so.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import re
14
+ import sys
15
+ import time
16
+ from dataclasses import dataclass, field
17
+ from typing import Callable, Optional
18
+
19
+ from .errors import GSError
20
+
21
+ WRITE_MARKERS = ("manage", "mutate", "share")
22
+ MAX_STEPS_DEFAULT = 8
23
+ MAX_RESULT_CHARS = 4000
24
+
25
+ Confirm = Callable[[str, dict], bool]
26
+
27
+
28
+ @dataclass
29
+ class Step:
30
+ tool: str
31
+ arguments: dict
32
+ result: str
33
+ is_error: bool = False
34
+
35
+
36
+ @dataclass
37
+ class AskResult:
38
+ answer: str
39
+ steps: list = field(default_factory=list)
40
+
41
+
42
+ def is_write(tool_name: str) -> bool:
43
+ return any(marker in tool_name for marker in WRITE_MARKERS)
44
+
45
+
46
+ def terminal_confirm(tool: str, arguments: dict) -> bool:
47
+ """Asks in the terminal. Refuses when there is no terminal to ask in."""
48
+ if not sys.stdin.isatty():
49
+ return False
50
+ print(f"\nThe assistant wants to run {tool} with:")
51
+ for key, value in arguments.items():
52
+ print(f" {key}: {value}")
53
+ return input("Run this? [y/N] ").strip().lower() in ("y", "yes")
54
+
55
+
56
+ def fetch_tools(client, server: str) -> list:
57
+ out = client._rpc(server, "tools/list", {})
58
+ if "error" in out:
59
+ raise GSError(f"Could not read the tool list for {server}.")
60
+ tools = out.get("result", {}).get("tools", [])
61
+ return [
62
+ {
63
+ "type": "function",
64
+ "function": {
65
+ "name": t["name"],
66
+ "description": t.get("description", ""),
67
+ "parameters": t.get("inputSchema") or {"type": "object", "properties": {}},
68
+ },
69
+ }
70
+ for t in tools
71
+ ]
72
+
73
+
74
+ def build_system(label: str, client, table: Optional[str]) -> str:
75
+ text = (
76
+ f"You help the user with their Got Simplified {label}. "
77
+ "Use only the tools you are given. If you are not sure of a name, look it up with a read tool first. "
78
+ "Call a tool once. When a tool returns a result, answer from that result; do not call the same tool "
79
+ "again unless its last call returned an error. Keep the answer short and plain. Say a change was made "
80
+ "only when a tool result confirms it. Some changes start a background job: the package waits for it "
81
+ "and returns the final result, so do not check its status yourself. Always pass the table name when "
82
+ "a tool takes one."
83
+ )
84
+ if table:
85
+ columns = client.datalake_query(f"DESCRIBE {table}", limit=200)
86
+ text += f"\n\nThe table {table} has these columns (from the data lake):\n{columns}"
87
+ return text
88
+
89
+
90
+ MAX_WRITE_ATTEMPTS = 3
91
+
92
+ # A tool that starts a background job says so, and gives its id. The package waits for the job
93
+ # itself, so the model never has to check it.
94
+ JOB_ID = re.compile(r"\b((?:mljob|job)[_-][A-Za-z0-9_-]+)")
95
+ STILL_RUNNING = ("still running", "has started", "continues in the background", "taking a while")
96
+ POLL_SECONDS = 15
97
+ MAX_POLLS = 40 # about 10 minutes
98
+ _sleep = time.sleep # replaced in tests
99
+
100
+
101
+ def _check_job(client, server: str, job: str) -> str:
102
+ if server == "ml":
103
+ return client._call("ml", "ml_query", {"action": "job", "job_id": job})
104
+ if server == "graph":
105
+ return client._call("graph", "graph_query", {"job_id": job})
106
+ if server == "files":
107
+ return client._call("files", "file_query", {"job_id": job})
108
+ if server == "datalake":
109
+ return client._call("datalake", "datalake_query", {"sql": f"SHOW JOB {job}"})
110
+ return ""
111
+
112
+
113
+ def wait_for_job(client, server: str, text: str) -> str:
114
+ """If the reply starts a background job, waits for it and returns its final result."""
115
+ match = JOB_ID.search(text)
116
+ if not match or not any(p in text.lower() for p in STILL_RUNNING):
117
+ return text
118
+ job = match.group(1)
119
+ previous = getattr(client, "_polling", False)
120
+ client._polling = True # the status checks must not wait on themselves
121
+ try:
122
+ for _ in range(MAX_POLLS):
123
+ _sleep(POLL_SECONDS)
124
+ latest = _check_job(client, server, job)
125
+ if latest and not any(p in latest.lower() for p in STILL_RUNNING):
126
+ return latest
127
+ finally:
128
+ client._polling = previous
129
+ return (f"{text}\n\n(The job did not finish within about 10 minutes. "
130
+ f"Check it later with job id {job}.)")
131
+
132
+
133
+ def _write_key(name: str, arguments: dict) -> str:
134
+ target = (arguments.get("model") or arguments.get("graph") or arguments.get("table_name")
135
+ or arguments.get("note_id") or arguments.get("file_id") or "")
136
+ return f"{name}:{arguments.get('action', '')}:{target}:{arguments.get('table', '')}"
137
+
138
+
139
+ def run_tool(client, server: str, name: str, arguments: dict, confirm: Optional[Confirm],
140
+ state: Optional[dict] = None) -> Step:
141
+ state = state if state is not None else {"done": set(), "attempts": 0}
142
+ if is_write(name):
143
+ key = _write_key(name, arguments)
144
+ if key in state["done"]:
145
+ return Step(name, arguments, "Not run: this change was already made in this request. "
146
+ "Do not repeat it; answer from the result.", is_error=True)
147
+ if state["attempts"] >= MAX_WRITE_ATTEMPTS:
148
+ return Step(name, arguments, f"Not run: at most {MAX_WRITE_ATTEMPTS} changes per request.",
149
+ is_error=True)
150
+ state["attempts"] += 1
151
+ approve = confirm if confirm is not None else terminal_confirm
152
+ if not approve(name, arguments):
153
+ return Step(name, arguments, "Not run: this change was not confirmed by the user.", is_error=True)
154
+ try:
155
+ text = client._call(server, name, arguments)
156
+ text = wait_for_job(client, server, text)
157
+ except GSError as e:
158
+ return Step(name, arguments, str(e), is_error=True)
159
+ if is_write(name):
160
+ state["done"].add(_write_key(name, arguments))
161
+ return Step(name, arguments, text[:MAX_RESULT_CHARS])
162
+
163
+
164
+ def ask_app(client, server: str, label: str, prompt: str, *, table: Optional[str] = None,
165
+ max_steps: int = MAX_STEPS_DEFAULT, confirm: Optional[Confirm] = None) -> AskResult:
166
+ provider = client._provider()
167
+ tools = fetch_tools(client, server)
168
+ system = build_system(label, client, table)
169
+ messages = [{"role": "system", "content": system}, {"role": "user", "content": prompt}]
170
+ steps: list = []
171
+ state = {"done": set(), "attempts": 0} # per request: no repeated successful change
172
+
173
+ for _ in range(max_steps):
174
+ reply = provider.send(messages, tools)
175
+ calls = reply["tool_calls"]
176
+ if not calls:
177
+ return AskResult(answer=reply["text"].strip(), steps=steps)
178
+
179
+ messages.append({
180
+ "role": "assistant",
181
+ "content": reply["text"] or None,
182
+ "tool_calls": [
183
+ {"id": c["id"], "type": "function",
184
+ "function": {"name": c["name"], "arguments": json.dumps(c["arguments"])}}
185
+ for c in calls
186
+ ],
187
+ })
188
+ for c in calls:
189
+ if c.get("error"):
190
+ step = Step(c["name"], {}, c["error"], is_error=True)
191
+ else:
192
+ step = run_tool(client, server, c["name"], c["arguments"], confirm, state)
193
+ steps.append(step)
194
+ messages.append({"role": "tool", "tool_call_id": c["id"], "content": step.result})
195
+
196
+ error = GSError(f"Stopped after {max_steps} steps without an answer. Ask a smaller question.")
197
+ error.steps = steps # what was tried, so the caller can see it
198
+ raise error
199
+
200
+
201
+ class Scope:
202
+ """One app's plain-language entry point. Created by Client as c.notes, c.files, c.datalake."""
203
+
204
+ def __init__(self, client, server: str, label: str):
205
+ self._client = client
206
+ self._server = server
207
+ self._label = label
208
+
209
+ def ask(self, prompt: str, table: Optional[str] = None, max_steps: int = MAX_STEPS_DEFAULT,
210
+ confirm: Optional[Confirm] = None) -> AskResult:
211
+ """Ask in plain words. Uses your model key (llm_token) and only this app's tools.
212
+
213
+ Args:
214
+ prompt: the request, in plain words.
215
+ table: data lake only. "namespace.table" whose columns are shown to the model.
216
+ max_steps: most tool calls before stopping. Default 8.
217
+ confirm: function(tool_name, arguments) -> bool that approves a change. Default asks in the
218
+ terminal; without a terminal, changes are refused.
219
+
220
+ The model name is checked against your provider's list before the call. To see the names,
221
+ run c.llm_models().
222
+ Returns: AskResult with .answer (text) and .steps (each tool call, its result and any error).
223
+ Raises: GSError when the key is missing, the model cannot be reached, or the step limit is reached.
224
+ """
225
+ return ask_app(self._client, self._server, self._label, prompt,
226
+ table=table, max_steps=max_steps, confirm=confirm)
@@ -0,0 +1,261 @@
1
+ """Got Simplified Python client.
2
+
3
+ Calls the same tools the chat uses, over HTTPS with your Got Simplified token.
4
+ Standard library only. Tokens are never printed and never written to disk.
5
+
6
+ Grouped functions: c.notes, c.files, c.datalake. Each has ask() for plain-language requests.
7
+ Writes go to the account the token belongs to. Default host is production.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import difflib
13
+ import json
14
+ import os
15
+ import re
16
+ import uuid
17
+ import urllib.error
18
+ import urllib.request
19
+ from typing import Iterable, Optional
20
+
21
+ from .errors import GSError
22
+ from .llm import (DEFAULT_MODEL, DEFAULT_OLLAMA_URL, DEFAULT_PROVIDER, MODEL_LIST_PROVIDERS,
23
+ LiteLLMProvider, is_chat_model, list_models)
24
+
25
+ DEFAULT_HOST = "https://mcp.gotsimplified.com"
26
+ UPLOAD_LIMIT_BYTES = 200 * 1024 * 1024 # the Files app accepts up to 200 MB per upload
27
+ TIMEOUT_SECONDS = 60
28
+
29
+
30
+ class Client:
31
+ """One client per script.
32
+
33
+ Tokens come from arguments or environment variables:
34
+ - ``GS_API_TOKEN``: your Got Simplified API token (required)
35
+ - ``LLM_API_KEY``: your model key, used only by ``ask()``
36
+ - ``LLM_PROVIDER``: ``anthropic`` (the only provider for now)
37
+ - ``LLM_MODEL``: model name, default ``claude-sonnet-5-5``
38
+ """
39
+
40
+ def __init__(
41
+ self,
42
+ gs_token: Optional[str] = None,
43
+ llm_token: Optional[str] = None,
44
+ llm_provider: Optional[str] = None,
45
+ llm_model: Optional[str] = None,
46
+ llm_base_url: Optional[str] = None,
47
+ host: str = DEFAULT_HOST,
48
+ wait_for_jobs: bool = True,
49
+ ):
50
+ self._gs_token = gs_token or os.environ.get("GS_API_TOKEN")
51
+ if not self._gs_token:
52
+ raise GSError("No Got Simplified token. Pass gs_token= or set GS_API_TOKEN.")
53
+ self._llm_token = llm_token or os.environ.get("LLM_API_KEY")
54
+ self.llm_provider = llm_provider or os.environ.get("LLM_PROVIDER")
55
+ self.llm_model = llm_model or os.environ.get("LLM_MODEL")
56
+ self.llm_base_url = llm_base_url or os.environ.get("LLM_BASE_URL")
57
+ self.host = host.rstrip("/")
58
+ self.wait_for_jobs = wait_for_jobs # True: calls that start a background job wait for its result
59
+ self._polling = False
60
+ self._model_cache: dict = {} # provider -> list of model ids, read once per client
61
+
62
+ from .ml_graph import ML, Graph # imported here to avoid a cycle
63
+ from .resources import DataLake, Files, Notes
64
+
65
+ self.notes = Notes(self)
66
+ self.files = Files(self)
67
+ self.datalake = DataLake(self)
68
+ self.ml = ML(self)
69
+ self.graph = Graph(self)
70
+
71
+ def __repr__(self) -> str:
72
+ llm = "set" if self._llm_token else "not set"
73
+ return f"Client(host={self.host!r}, gs_token=***, llm_provider={self.llm_provider!r}, llm_token={llm})"
74
+
75
+ # ----- model connection (used by ask) ----------------------------------
76
+
77
+ def _connection(self) -> tuple:
78
+ """Provider, key and address for the model connection. Needs no model name."""
79
+ provider = (self.llm_provider or "").lower()
80
+ if not provider:
81
+ raise GSError("Set llm_provider, for example 'anthropic', 'openai' or 'ollama'.")
82
+ key = None
83
+ if provider not in ("ollama", "bedrock"):
84
+ if not self._llm_token:
85
+ raise GSError("No LLM key. Pass llm_token= or set LLM_API_KEY.")
86
+ key = self._llm_token
87
+ api_base = self.llm_base_url or (DEFAULT_OLLAMA_URL if provider == "ollama" else None)
88
+ return provider, key, api_base
89
+
90
+ def _settings(self) -> tuple:
91
+ """Provider, model, key and address for ask(). Errors name the fix."""
92
+ provider, key, api_base = self._connection()
93
+ if provider == DEFAULT_PROVIDER and not self.llm_model:
94
+ model = DEFAULT_MODEL
95
+ elif not self.llm_model:
96
+ raise GSError(f"Set llm_model for provider '{provider}'. Run c.llm_models() to see the names.")
97
+ else:
98
+ model = self.llm_model
99
+ return provider, model, key, api_base
100
+
101
+ def llm_models(self, chat_only: bool = True) -> list:
102
+ """Model names your provider and key can use, as dictionaries with 'id' and 'name'. Sorted by id.
103
+
104
+ Use an 'id' as llm_model. Needs llm_provider and the key, but not llm_model.
105
+ chat_only=True (default) hides audio, image, speech, embedding and moderation models,
106
+ which ask() cannot use. Pass chat_only=False to see every name.
107
+ """
108
+ provider, key, api_base = self._connection()
109
+ if provider not in MODEL_LIST_PROVIDERS:
110
+ raise GSError(f"Model lists are not available for '{provider}' yet. Check the provider's own list.")
111
+ models = list_models(provider, api_key=key, api_base=api_base)
112
+ self._model_cache[provider] = [m["id"] for m in models]
113
+ if chat_only:
114
+ models = [m for m in models if is_chat_model(m["id"])]
115
+ return sorted(models, key=lambda m: m["id"])
116
+
117
+ def _check_model(self, provider: str, model: str, key, api_base) -> None:
118
+ """Refuses a model name the provider does not list, with the closest names.
119
+
120
+ If the list cannot be read, the check is skipped and the provider decides when it's called.
121
+ """
122
+ if provider not in MODEL_LIST_PROVIDERS:
123
+ return
124
+ if provider not in self._model_cache:
125
+ try:
126
+ self._model_cache[provider] = [m["id"] for m in list_models(provider, key, api_base)]
127
+ except GSError:
128
+ return
129
+ ids = self._model_cache[provider]
130
+ name = model[len(provider) + 1:] if model.startswith(provider + "/") else model
131
+ if ids and name not in ids:
132
+ close = difflib.get_close_matches(name, ids, n=3)
133
+ hint = f" Did you mean: {', '.join(close)}?" if close else ""
134
+ raise GSError(f"'{name}' is not a {provider} model your key lists.{hint} "
135
+ "Run c.llm_models() to see all names.")
136
+
137
+ def _provider(self) -> LiteLLMProvider:
138
+ """The model connection for ask(). Built from llm_provider, llm_model and the key."""
139
+ provider, model, key, api_base = self._settings()
140
+ self._check_model(provider, model, key, api_base)
141
+ return LiteLLMProvider(provider, model, api_key=key, api_base=api_base)
142
+
143
+ # ----- transport -------------------------------------------------------
144
+
145
+ def _rpc(self, server: str, method: str, params: dict) -> dict:
146
+ body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": method, "params": params}).encode()
147
+ req = urllib.request.Request(
148
+ f"{self.host}/{server}",
149
+ data=body,
150
+ method="POST",
151
+ headers={
152
+ "Authorization": f"Bearer {self._gs_token}",
153
+ "Content-Type": "application/json",
154
+ "Accept": "application/json, text/event-stream",
155
+ },
156
+ )
157
+ try:
158
+ with urllib.request.urlopen(req, timeout=TIMEOUT_SECONDS) as resp:
159
+ return json.loads(resp.read().decode())
160
+ except urllib.error.HTTPError as e:
161
+ raise GSError(f"{server}: HTTP {e.code}") from None
162
+ except urllib.error.URLError as e:
163
+ raise GSError(f"{server}: cannot reach the server ({e.reason})") from None
164
+
165
+ def _call(self, server: str, tool: str, args: dict) -> str:
166
+ """Runs one tool and returns its Markdown text. Raises GSError on failure."""
167
+ args = {k: v for k, v in args.items() if v is not None}
168
+ out = self._rpc(server, "tools/call", {"name": tool, "arguments": args})
169
+ if "error" in out:
170
+ raise GSError(str(out["error"].get("message", out["error"])))
171
+ result = out.get("result", {})
172
+ text = "\n".join(c.get("text", "") for c in result.get("content", []))
173
+ if result.get("isError"):
174
+ raise GSError(text)
175
+ if self.wait_for_jobs and not self._polling:
176
+ from .ask import wait_for_job # imported here to avoid a cycle
177
+
178
+ text = wait_for_job(self, server, text)
179
+ return text
180
+
181
+ def _post_form(self, url: str, fields: Iterable[tuple], filename: str, data: bytes) -> None:
182
+ """Uploads bytes with a signed form post (the storage step of a Files upload)."""
183
+ boundary = uuid.uuid4().hex
184
+ chunks = []
185
+ for name, value in fields:
186
+ chunks.append(
187
+ f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n'.encode()
188
+ )
189
+ chunks.append(
190
+ (
191
+ f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="{filename}"\r\n'
192
+ "Content-Type: application/octet-stream\r\n\r\n"
193
+ ).encode()
194
+ + data
195
+ + b"\r\n"
196
+ )
197
+ chunks.append(f"--{boundary}--\r\n".encode())
198
+ req = urllib.request.Request(
199
+ url,
200
+ data=b"".join(chunks),
201
+ method="POST",
202
+ headers={"Content-Type": f"multipart/form-data; boundary={boundary}"},
203
+ )
204
+ try:
205
+ with urllib.request.urlopen(req, timeout=TIMEOUT_SECONDS):
206
+ pass
207
+ except urllib.error.HTTPError as e:
208
+ raise GSError(f"upload failed: HTTP {e.code}") from None
209
+
210
+ def _download(self, url: str) -> bytes:
211
+ """Downloads a file from a link the server returned (a presigned storage link, no token needed)."""
212
+ if not url.startswith("https://"):
213
+ raise GSError("Refusing to download from a link that is not https.")
214
+ try:
215
+ with urllib.request.urlopen(url, timeout=TIMEOUT_SECONDS) as resp:
216
+ return resp.read()
217
+ except urllib.error.HTTPError as e:
218
+ raise GSError(f"The download failed (HTTP {e.code}).") from None
219
+ except urllib.error.URLError:
220
+ raise GSError("The download failed: cannot reach the file store.") from None
221
+
222
+ def _upload_bytes(self, data: bytes, name: str, folder: str, replace: bool) -> str:
223
+ """Reserve, store and confirm one file in the Files app. Returns its path."""
224
+ if len(data) > UPLOAD_LIMIT_BYTES:
225
+ raise GSError(f"{name} is larger than the 200 MB upload limit.")
226
+ text = self._call("files", "file_manage",
227
+ {"action": "upload", "folder": folder, "name": name, "replace": replace})
228
+ fields = re.findall(r"-F '(key|AWSAccessKeyId|policy|signature)=([^']*)'", text)
229
+ url_match = re.search(r"'(https://[^']+)'\s*$", text, re.MULTILINE)
230
+ id_match = re.search(r"file_id='([^']+)'", text)
231
+ if len(fields) != 4 or not url_match or not id_match:
232
+ raise GSError("The Files app returned an upload slot this client cannot read.")
233
+ self._post_form(url_match.group(1), fields, name, data)
234
+ self._call("files", "file_manage", {"action": "finish_upload", "file_id": id_match.group(1)})
235
+ return f"{folder.rstrip('/')}/{name}"
236
+
237
+ # ----- flat names kept from the first test version (same behaviour) ----
238
+
239
+ def note_create(self, content: str, title: Optional[str] = None, tags: Optional[list] = None) -> str:
240
+ return self.notes.create(content, title=title, tags=tags)
241
+
242
+ def note_search(self, query: Optional[str] = None) -> str:
243
+ return self.notes.search(query) if query else self.notes.list()
244
+
245
+ def file_upload(self, local_path: str, folder: str = "/Uploads") -> str:
246
+ return self.files.upload(local_path, folder=folder)
247
+
248
+ def file_upload_bytes(self, data: bytes, name: str, folder: str = "/Uploads") -> str:
249
+ return self.files.upload_bytes(data, name, folder=folder)
250
+
251
+ def file_link(self, path: str) -> str:
252
+ return self.files.download_link(path)
253
+
254
+ def datalake_import(self, files_path: str, namespace: str, table: str) -> str:
255
+ return self.datalake.import_file(files_path, namespace, table)
256
+
257
+ def datalake_query(self, sql: str, limit: int = 10) -> str:
258
+ return self.datalake.query_text(sql, limit=limit)
259
+
260
+ def import_zip(self, zip_path: str, namespace: str) -> list:
261
+ return self.datalake.import_zip(zip_path, namespace)
@@ -0,0 +1,5 @@
1
+ """Errors raised by the Got Simplified client. Messages never contain a token."""
2
+
3
+
4
+ class GSError(Exception):
5
+ """A request or tool failed. The message is the tool's own text, or a fix to try."""
gotsimplified/llm.py ADDED
@@ -0,0 +1,126 @@
1
+ """Model connection for ask(), through LiteLLM. Optional extra: pip install 'gotsimplified[llm]'.
2
+
3
+ LiteLLM sends each request from your computer to the provider you chose. The model key goes only
4
+ to that provider. Nothing about the model call is sent to Got Simplified.
5
+
6
+ Providers: anthropic, openai, ollama, bedrock, and the others LiteLLM supports. Use the provider
7
+ name as LiteLLM spells it, and set llm_model to that provider's model name.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import urllib.error
14
+ import urllib.request
15
+ from typing import Callable, Optional
16
+
17
+ from .errors import GSError
18
+
19
+ DEFAULT_PROVIDER = "anthropic"
20
+ DEFAULT_MODEL = "claude-sonnet-5-5"
21
+ DEFAULT_OLLAMA_URL = "http://localhost:11434"
22
+ TIMEOUT_SECONDS = 120
23
+ ANTHROPIC_VERSION = "2023-06-01"
24
+ ANTHROPIC_MODELS_URL = "https://api.anthropic.com/v1/models?limit=1000"
25
+ OPENAI_MODELS_URL = "https://api.openai.com/v1/models"
26
+ MODEL_LIST_PROVIDERS = ("anthropic", "openai", "ollama")
27
+ # Names with these words are not chat models (audio, images, speech, embeddings, moderation).
28
+ NOT_CHAT_WORDS = ("transcribe", "tts", "whisper", "realtime", "audio", "image", "embed",
29
+ "moderation", "search", "live", "bge", "codex")
30
+
31
+
32
+ def is_chat_model(model_id: str) -> bool:
33
+ name = model_id.lower()
34
+ return not any(word in name for word in NOT_CHAT_WORDS)
35
+
36
+
37
+ def fetch_json(url: str, headers: dict) -> dict:
38
+ """GET a JSON document. Errors are turned into GSError without echoing the key."""
39
+ req = urllib.request.Request(url, headers=headers, method="GET")
40
+ try:
41
+ with urllib.request.urlopen(req, timeout=TIMEOUT_SECONDS) as resp:
42
+ return json.loads(resp.read().decode())
43
+ except urllib.error.HTTPError as e:
44
+ raise GSError(f"The model list could not be read (HTTP {e.code}). Check the LLM key.") from None
45
+ except urllib.error.URLError:
46
+ raise GSError("The model list could not be read: cannot reach the provider.") from None
47
+
48
+
49
+ def list_models(provider: str, api_key: Optional[str] = None, api_base: Optional[str] = None) -> list:
50
+ """Model names this key can use, as dictionaries with 'id' and 'name'. Raises GSError on failure."""
51
+ p = provider.lower()
52
+ if p == "anthropic":
53
+ if not api_key:
54
+ raise GSError("Listing Claude models needs an LLM key.")
55
+ data = fetch_json(ANTHROPIC_MODELS_URL, {"x-api-key": api_key, "anthropic-version": ANTHROPIC_VERSION})
56
+ return [{"id": m["id"], "name": m.get("display_name", m["id"])} for m in data.get("data", [])]
57
+ if p == "openai":
58
+ if not api_key:
59
+ raise GSError("Listing OpenAI models needs an LLM key.")
60
+ data = fetch_json(OPENAI_MODELS_URL, {"Authorization": f"Bearer {api_key}"})
61
+ return [{"id": m["id"], "name": m["id"]} for m in data.get("data", [])]
62
+ if p == "ollama":
63
+ base = (api_base or DEFAULT_OLLAMA_URL).rstrip("/")
64
+ data = fetch_json(f"{base}/api/tags", {})
65
+ return [{"id": m["name"], "name": m["name"]} for m in data.get("models", [])]
66
+ raise GSError(f"Model lists are not available for '{provider}' yet. Check the provider's own list.")
67
+
68
+
69
+ def litellm_model_name(provider: str, model: str) -> str:
70
+ """LiteLLM wants 'provider/model'. A name that already has a prefix is used as it is."""
71
+ return model if model.startswith(f"{provider}/") else f"{provider}/{model}"
72
+
73
+
74
+ class LiteLLMProvider:
75
+ """One model turn. send() returns the text and any tool calls, in one shape for every provider."""
76
+
77
+ def __init__(self, provider: str, model: str, api_key: Optional[str] = None,
78
+ api_base: Optional[str] = None, completion: Optional[Callable] = None):
79
+ self.provider = provider
80
+ self.model = model
81
+ self._api_key = api_key
82
+ self._api_base = api_base
83
+ self._completion = completion # injected by tests; None means LiteLLM itself
84
+
85
+ def _completion_fn(self) -> Callable:
86
+ if self._completion is not None:
87
+ return self._completion
88
+ try:
89
+ import litellm
90
+ except ImportError:
91
+ raise GSError("ask() needs the optional LLM support. Install it with: "
92
+ "pip install 'gotsimplified[llm]'") from None
93
+ return litellm.completion
94
+
95
+ def send(self, messages: list, tools: list) -> dict:
96
+ kwargs = {
97
+ "model": litellm_model_name(self.provider, self.model),
98
+ "messages": messages,
99
+ "timeout": TIMEOUT_SECONDS,
100
+ }
101
+ if tools:
102
+ kwargs["tools"] = tools
103
+ if self._api_key:
104
+ kwargs["api_key"] = self._api_key
105
+ if self._api_base:
106
+ kwargs["api_base"] = self._api_base
107
+ try:
108
+ response = self._completion_fn()(**kwargs)
109
+ except GSError:
110
+ raise
111
+ except Exception as e:
112
+ # Only the exception type is shown: provider messages can echo request details.
113
+ raise GSError(f"The model call failed ({type(e).__name__}). "
114
+ "Check the provider, the model name and the key.") from None
115
+
116
+ message = response.choices[0].message
117
+ calls = []
118
+ for tc in getattr(message, "tool_calls", None) or []:
119
+ raw = tc.function.arguments or "{}"
120
+ try:
121
+ arguments = json.loads(raw) if isinstance(raw, str) else dict(raw)
122
+ calls.append({"id": tc.id, "name": tc.function.name, "arguments": arguments})
123
+ except (json.JSONDecodeError, TypeError, ValueError):
124
+ calls.append({"id": tc.id, "name": tc.function.name, "arguments": {},
125
+ "error": "The model sent arguments that are not valid JSON."})
126
+ return {"text": message.content or "", "tool_calls": calls}