AskTim 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.
asktim/config.py ADDED
@@ -0,0 +1,316 @@
1
+ """Settings and API keys.
2
+
3
+ Settings come in layers; a later layer wins:
4
+
5
+ 1. the defaults below
6
+ 2. a site file an instructor can provide (/etc/asktim/config.json, or ASKTIM_SITE_CONFIG)
7
+ 3. the user's file (~/.config/asktim/config.json)
8
+ 4. environment variables (ASKTIM_PROVIDER, ASKTIM_MODEL, ASKTIM_PRIVACY ...)
9
+ 5. options given on the command line
10
+
11
+ A site file may list settings under "locked": those cannot be changed by layers 3-5
12
+ (for example a course that wants "privacy": "strict" on its lab machines).
13
+
14
+ Keys are kept apart from the settings, in ~/.config/asktim/keys.json, which only the owner
15
+ can read. Environment variables (ANTHROPIC_API_KEY, GEMINI_API_KEY, OPENAI_API_KEY) and,
16
+ in Google Colab, Colab's Secrets are used when no key has been stored.
17
+ """
18
+
19
+ import copy
20
+ import json
21
+ import os
22
+ import sys
23
+
24
+ from . import paths
25
+
26
+ PROVIDERS = ("claude", "gemini", "openai")
27
+
28
+ # what students may type for each service
29
+ PROVIDER_ALIASES = {
30
+ "claude": "claude",
31
+ "anthropic": "claude",
32
+ "gemini": "gemini",
33
+ "google": "gemini",
34
+ "openai": "openai",
35
+ "chatgpt": "openai",
36
+ "gpt": "openai",
37
+ "openai-compatible": "openai",
38
+ "local": "openai",
39
+ }
40
+
41
+ PROVIDER_NAMES = {"claude": "Anthropic (Claude)", "gemini": "Google Gemini", "openai": "OpenAI-compatible service"}
42
+
43
+ KEY_ENV = {
44
+ "claude": ("ASKTIM_CLAUDE_KEY", "ANTHROPIC_API_KEY"),
45
+ "gemini": ("ASKTIM_GEMINI_KEY", "GEMINI_API_KEY", "GOOGLE_API_KEY"),
46
+ "openai": ("ASKTIM_OPENAI_KEY", "OPENAI_API_KEY"),
47
+ }
48
+
49
+ DEFAULTS = {
50
+ "provider": "claude",
51
+ "models": {
52
+ "claude": "claude-sonnet-5-5",
53
+ "gemini": "gemini-3.8-flash",
54
+ "openai": "gpt-5-mini",
55
+ },
56
+ # When a Gemini model is busy, over its limit or retired, these are asked in turn
57
+ # (the list the practicals used on 6 October 2026).
58
+ "gemini_fallback_models": ["gemini-3.7-flash", "gemini-3.6-flash", "gemini-3.5-flash", "gemini-3.5-flash-lite", "gemini-3.1-flash-lite"],
59
+ "openai_base_url": "https://api.openai.com/v1",
60
+ "anthropic_base_url": "https://api.anthropic.com",
61
+ "gemini_base_url": "https://generativelanguage.googleapis.com",
62
+ "anthropic_version": "2026-10-21",
63
+ # Claude's effort level: lower is faster and cheaper. null leaves the model's default.
64
+ "effort": {"chat": "low", "agent": "medium"},
65
+ "max_tokens": {"chat": 16000, "agent": 32000},
66
+ # what goes with a question
67
+ "send_history": True,
68
+ "history_lines": 20,
69
+ "send_file_names": True,
70
+ # "standard": data are withheld; names of files and columns, help text, errors and summaries are sent.
71
+ # "strict": also no column names or file names, and of a command's output only errors and help text.
72
+ "privacy": "standard",
73
+ "agent": {
74
+ "max_steps": 25,
75
+ "command_timeout": 600,
76
+ "output_chars": 4000,
77
+ "allow_network": False,
78
+ "sandbox": "auto", # auto | on | off (bubblewrap on Linux, when it works)
79
+ "runs_dir": "asktim-runs",
80
+ },
81
+ # extra lines an instructor can add to what the AI is told (the course, the data, house rules)
82
+ "course": "",
83
+ "color": "auto", # auto | always | never
84
+ "chat_memory_minutes": 60,
85
+ "log": True,
86
+ "locked": [],
87
+ }
88
+
89
+ ENV_SETTINGS = {
90
+ "ASKTIM_PROVIDER": "provider",
91
+ "ASKTIM_PRIVACY": "privacy",
92
+ "ASKTIM_COURSE": "course",
93
+ "ASKTIM_COLOR": "color",
94
+ "ASKTIM_OPENAI_URL": "openai_base_url",
95
+ "ASKTIM_ANTHROPIC_URL": "anthropic_base_url",
96
+ "ASKTIM_GEMINI_URL": "gemini_base_url",
97
+ }
98
+
99
+
100
+ def _deep_update(base, extra):
101
+ for k, v in (extra or {}).items():
102
+ if isinstance(v, dict) and isinstance(base.get(k), dict):
103
+ _deep_update(base[k], v)
104
+ else:
105
+ base[k] = copy.deepcopy(v)
106
+ return base
107
+
108
+
109
+ def _read_json(path):
110
+ try:
111
+ with open(path, encoding="utf-8") as f:
112
+ data = json.load(f)
113
+ return data if isinstance(data, dict) else {}
114
+ except FileNotFoundError:
115
+ return {}
116
+ except (OSError, ValueError) as e:
117
+ sys.stderr.write("AskTim!: could not read %s (%s) - it is ignored.\n" % (path, e))
118
+ return {}
119
+
120
+
121
+ def config_file():
122
+ return os.path.join(paths.config_dir(), "config.json")
123
+
124
+
125
+ def keys_file():
126
+ return os.path.join(paths.config_dir(), "keys.json")
127
+
128
+
129
+ def get_path(d, dotted):
130
+ cur = d
131
+ for part in dotted.split("."):
132
+ if not isinstance(cur, dict) or part not in cur:
133
+ return None
134
+ cur = cur[part]
135
+ return cur
136
+
137
+
138
+ def _set_path(d, dotted, value):
139
+ parts = dotted.split(".")
140
+ cur = d
141
+ for part in parts[:-1]:
142
+ cur = cur.setdefault(part, {})
143
+ cur[parts[-1]] = value
144
+
145
+
146
+ class Config(object):
147
+ """The settings in force, with the layer each came from."""
148
+
149
+ def __init__(self, overrides=None):
150
+ self.site = _read_json(paths.site_config_file())
151
+ self.user = _read_json(config_file())
152
+ data = copy.deepcopy(DEFAULTS)
153
+ _deep_update(data, {k: v for k, v in self.site.items() if k != "locked"})
154
+ locked = list(self.site.get("locked") or [])
155
+ site_values = {k: get_path(data, k) for k in locked}
156
+ _deep_update(data, self.user)
157
+ for env, key in ENV_SETTINGS.items():
158
+ if os.environ.get(env):
159
+ _set_path(data, key, os.environ[env])
160
+ if os.environ.get("ASKTIM_MODEL"):
161
+ prov = normalise_provider(data.get("provider")) or "claude"
162
+ data["models"][prov] = os.environ["ASKTIM_MODEL"]
163
+ for k, v in (overrides or {}).items():
164
+ if v is not None:
165
+ _set_path(data, k, v)
166
+ # the instructor's locked values win over everything the student sets
167
+ for k, v in site_values.items():
168
+ if v is not None:
169
+ _set_path(data, k, v)
170
+ data["locked"] = locked
171
+ data["provider"] = normalise_provider(data.get("provider")) or "claude"
172
+ if data.get("privacy") not in ("standard", "strict"):
173
+ data["privacy"] = "standard"
174
+ self.data = data
175
+
176
+ def __getitem__(self, key):
177
+ return get_path(self.data, key)
178
+
179
+ def get(self, key, default=None):
180
+ v = get_path(self.data, key)
181
+ return default if v is None else v
182
+
183
+ @property
184
+ def provider(self):
185
+ return self.data["provider"]
186
+
187
+ def model(self, provider=None):
188
+ return self.data["models"].get(provider or self.provider) or DEFAULTS["models"].get(provider or self.provider)
189
+
190
+ @property
191
+ def strict(self):
192
+ return self.data.get("privacy") == "strict"
193
+
194
+ def is_locked(self, key):
195
+ return any(key == k or key.startswith(k + ".") for k in self.data.get("locked", []))
196
+
197
+
198
+ def normalise_provider(name):
199
+ if not name:
200
+ return None
201
+ return PROVIDER_ALIASES.get(str(name).strip().lower())
202
+
203
+
204
+ def save_user_setting(key, value):
205
+ """Change one setting in the user's config.json (dotted keys: "agent.max_steps")."""
206
+ data = _read_json(config_file())
207
+ _set_path(data, key, value)
208
+ paths.ensure(paths.config_dir(), private=True)
209
+ tmp = config_file() + ".tmp"
210
+ with open(tmp, "w", encoding="utf-8") as f:
211
+ json.dump(data, f, indent=2, sort_keys=True)
212
+ os.replace(tmp, config_file())
213
+
214
+
215
+ # ---------------------------------------------------------------------------------------------
216
+ # keys
217
+ # ---------------------------------------------------------------------------------------------
218
+
219
+
220
+ def _write_private(path, text):
221
+ paths.ensure(os.path.dirname(path), private=True)
222
+ tmp = path + ".tmp"
223
+ # create the file with owner-only permissions from the start, so a key is never readable by others
224
+ flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
225
+ fd = os.open(tmp, flags, 0o600)
226
+ try:
227
+ os.write(fd, text.encode("utf-8"))
228
+ finally:
229
+ os.close(fd)
230
+ if not sys.platform.startswith("win"):
231
+ os.chmod(tmp, 0o600)
232
+ os.replace(tmp, path)
233
+
234
+
235
+ def stored_keys():
236
+ return {k: v for k, v in _read_json(keys_file()).items() if isinstance(v, str) and v}
237
+
238
+
239
+ def save_key(provider, key):
240
+ keys = stored_keys()
241
+ keys[provider] = key.strip()
242
+ _write_private(keys_file(), json.dumps(keys, indent=2))
243
+ return keys_file()
244
+
245
+
246
+ def forget_key(provider=None):
247
+ """Delete a stored key (or all of them). Returns the providers removed."""
248
+ keys = stored_keys()
249
+ gone = [p for p in keys if provider in (None, p)]
250
+ for p in gone:
251
+ keys.pop(p, None)
252
+ if keys:
253
+ _write_private(keys_file(), json.dumps(keys, indent=2))
254
+ else:
255
+ try:
256
+ os.remove(keys_file())
257
+ except FileNotFoundError:
258
+ pass
259
+ return gone
260
+
261
+
262
+ def in_colab():
263
+ return "google.colab" in sys.modules
264
+
265
+
266
+ def _colab_secret(provider):
267
+ """A key from Colab's Secrets (the key icon in Colab's left bar). Colab asks the student first."""
268
+ if not in_colab():
269
+ return None
270
+ try:
271
+ from google.colab import userdata # type: ignore
272
+ except Exception:
273
+ return None
274
+ names = list(KEY_ENV[provider]) + ["ASKTIM_KEY"]
275
+ for name in names:
276
+ try:
277
+ v = userdata.get(name)
278
+ except Exception:
279
+ v = None
280
+ if v:
281
+ return v.strip()
282
+ return None
283
+
284
+
285
+ def find_key(provider):
286
+ """(key, where it came from) or (None, None)."""
287
+ keys = stored_keys()
288
+ if keys.get(provider):
289
+ return keys[provider], "saved in " + paths.pretty(keys_file())
290
+ for env in KEY_ENV[provider]:
291
+ if os.environ.get(env):
292
+ return os.environ[env].strip(), "the environment variable " + env
293
+ v = _colab_secret(provider)
294
+ if v:
295
+ return v, "Colab's Secrets"
296
+ return None, None
297
+
298
+
299
+ def mask(key):
300
+ if not key:
301
+ return ""
302
+ if len(key) <= 12:
303
+ return key[:2] + "…"
304
+ return key[:7] + "…" + key[-4:]
305
+
306
+
307
+ def looks_like_key(token):
308
+ """Is this command-line word an API key (rather than the start of a question)?"""
309
+ t = (token or "").strip()
310
+ if len(t) < 20 or any(c.isspace() for c in t):
311
+ return False
312
+ if t.startswith(("sk-", "AIza", "AQ.", "gsk_", "hf_", "xai-", "pplx-")):
313
+ return True
314
+ letters = sum(c.isalpha() for c in t)
315
+ digits = sum(c.isdigit() for c in t)
316
+ return letters > 4 and digits > 2 and all(c.isalnum() or c in "-_.:" for c in t)
asktim/context.py ADDED
@@ -0,0 +1,156 @@
1
+ """What goes with a question: the context AskTim! gathers, and a list of it for the student.
2
+
3
+ Every piece passes through privacy.clean() (secrets, personal details, the user's name) and
4
+ anything that came out of a program passes through privacy.filter_output() (data lines).
5
+ The student is always told what was sent; `AskTim! show "question"` prints all of it
6
+ without sending anything.
7
+ """
8
+
9
+ import os
10
+
11
+ from . import fileinfo, history, paths, privacy
12
+
13
+ EXIT_MEANING = {
14
+ 1: "a general error",
15
+ 2: "wrong use of the command, or a file or folder that does not exist",
16
+ 126: "the file is not executable (check its permissions)",
17
+ 127: "command not found (not installed, not on PATH, or misspelt)",
18
+ 130: "stopped with Ctrl+C",
19
+ 134: "the program aborted (often a failed internal check)",
20
+ 137: "killed (often: it ran out of memory)",
21
+ 139: "the program crashed (segmentation fault)",
22
+ 141: "a pipe closed early (usually harmless, e.g. with head)",
23
+ 143: "terminated by a signal",
24
+ }
25
+
26
+
27
+ class Gathered(object):
28
+ def __init__(self):
29
+ self.parts = [] # text for the AI
30
+ self.sent = [] # what the student is told was sent
31
+ self.redactions = 0
32
+ self.withheld = 0
33
+
34
+ def add(self, text, what):
35
+ if text:
36
+ self.parts.append(text)
37
+ if what:
38
+ self.sent.append(what)
39
+
40
+ def text(self):
41
+ if not self.parts:
42
+ return ""
43
+ return "[Context that AskTim! gathered on the student's computer. It holds no file contents and no data.]\n" + "\n\n".join(self.parts) + "\n\n"
44
+
45
+ def summary(self):
46
+ s = ", ".join(self.sent) if self.sent else "only your question"
47
+ extra = []
48
+ if self.redactions:
49
+ extra.append("%d secret%s or personal detail%s removed" % (self.redactions, "" if self.redactions == 1 else "s", "" if self.redactions == 1 else "s"))
50
+ if self.withheld:
51
+ extra.append("%d line%s of data withheld" % (self.withheld, "" if self.withheld == 1 else "s"))
52
+ return "Sent with your question: %s%s. No file contents." % (s, (" (" + "; ".join(extra) + ")") if extra else "")
53
+
54
+
55
+ def _clean(g, text, strict):
56
+ text, n = privacy.clean(text, strict=strict)
57
+ g.redactions += n
58
+ return text
59
+
60
+
61
+ def terminal(cfg, files=(), stdin_text=None, send_history=None, history_n=None, send_files=None, cwd=None):
62
+ """Context for a question asked at the command line."""
63
+ strict = cfg.strict
64
+ g = Gathered()
65
+ cwd = cwd or os.getcwd()
66
+ g.add("The student's current folder: %s" % _clean(g, paths.pretty(cwd), strict), None)
67
+ if send_files if send_files is not None else cfg.get("send_file_names", True):
68
+ listing = fileinfo.listing(cwd, strict=strict)
69
+ g.add("Files in that folder (names and sizes only):\n" + _clean(g, listing, strict), "names of the files in this folder" if not strict else "the number of files here")
70
+ base = cfg.get("history_lines")
71
+ base = 20 if base is None else int(base)
72
+ n = min(int(history_n or base), 100)
73
+ if cfg.is_locked("history_lines"):
74
+ n = min(n, base)
75
+ if n > 0 and (send_history if send_history is not None else cfg.get("send_history", True)):
76
+ cmds, source = history.recent(n)
77
+ if cmds:
78
+ lines = []
79
+ for c in cmds:
80
+ line = _clean(g, c.line, strict)
81
+ st = "" if c.status is None else (" [exit %d]" % c.status if c.status else "")
82
+ lines.append(" $ %s%s" % (line.replace("\n", "\n "), st))
83
+ known = any(c.status is not None for c in cmds)
84
+ g.add("The student's last %d shell commands (oldest first%s):\n%s" % (len(cmds), "; [exit N] marks a command that failed" if known else "; exit statuses are not known", "\n".join(lines)),
85
+ "your last %d commands" % len(cmds))
86
+ last = history.last_failed(cmds[-3:])
87
+ if last is not None:
88
+ meaning = EXIT_MEANING.get(last.status, "")
89
+ g.add("The most recent failure: `%s` ended with exit status %d%s." % (_clean(g, last.line, strict), last.status, (" (" + meaning + ")") if meaning else ""), None)
90
+ elif source is None:
91
+ g.add("(AskTim! could not find the student's shell history.)", None)
92
+ for f in files or ():
93
+ desc = fileinfo.describe(f, strict=strict)
94
+ g.add("A file the student asked about: " + _clean(g, desc, strict), "a description of %s (its structure, not its contents)" % os.path.basename(f))
95
+ if stdin_text:
96
+ fr = privacy.filter_output(stdin_text, strict=strict)
97
+ g.withheld += fr.withheld
98
+ body = privacy.shorten(fr.text, 6000)
99
+ g.add("Output the student piped into AskTim! (lines that look like data are withheld):\n```text\n%s\n```" % body,
100
+ "the text you piped in (%s)" % fr.summary())
101
+ return g
102
+
103
+
104
+ def describe_value(name, v, strict=False):
105
+ """A variable of a notebook as a line: name, type, shape, columns - never its values."""
106
+ t = type(v)
107
+ mod = getattr(t, "__module__", "") or ""
108
+ tname = t.__name__
109
+ try:
110
+ if mod.startswith("pandas") and tname == "DataFrame":
111
+ cols = list(v.columns)
112
+ out = "%s: pandas DataFrame, %d rows × %d columns" % (name, v.shape[0], v.shape[1])
113
+ if not strict:
114
+ dt = [str(d) for d in v.dtypes]
115
+ shown = ", ".join("%s (%s)" % (str(c)[:40], d) for c, d in list(zip(cols, dt))[:40])
116
+ out += "; columns: " + shown + (", …" if len(cols) > 40 else "")
117
+ idx = v.index
118
+ if getattr(idx, "name", None):
119
+ out += "; index: %s" % idx.name
120
+ return out
121
+ if mod.startswith("pandas") and tname == "Series":
122
+ return "%s: pandas Series, length %d, dtype %s%s" % (name, len(v), v.dtype, ("" if strict or v.name is None else ", name %s" % str(v.name)[:40]))
123
+ if mod.startswith("numpy") and tname == "ndarray":
124
+ return "%s: numpy array, shape %s, dtype %s" % (name, tuple(v.shape), v.dtype)
125
+ if tname == "AnnData":
126
+ out = "%s: AnnData, %d observations × %d variables" % (name, v.n_obs, v.n_vars)
127
+ if not strict:
128
+ out += "; obs columns: %s; var columns: %s; layers: %s; obsm: %s" % (
129
+ ", ".join(map(str, list(v.obs.columns)[:20])) or "none", ", ".join(map(str, list(v.var.columns)[:20])) or "none",
130
+ ", ".join(map(str, list(v.layers.keys())[:10])) or "none", ", ".join(map(str, list(v.obsm.keys())[:10])) or "none")
131
+ return out
132
+ if mod.startswith("polars") and tname == "DataFrame":
133
+ return "%s: polars DataFrame, %d rows × %d columns%s" % (name, v.height, v.width, "" if strict else "; columns: " + ", ".join(str(c)[:40] for c in v.columns[:40]))
134
+ if mod.startswith("matplotlib"):
135
+ return "%s: %s (a plot)" % (name, tname)
136
+ if tname == "module":
137
+ return None
138
+ if callable(v) and not isinstance(v, type):
139
+ return "%s: function" % name if tname in ("function", "builtin_function_or_method") else "%s: %s" % (name, tname)
140
+ if isinstance(v, tuple) and 1 <= len(v) <= 4 and all(isinstance(x, int) and not isinstance(x, bool) for x in v):
141
+ return "%s: tuple %s (a shape or a count)" % (name, v)
142
+ if isinstance(v, (list, tuple, set, frozenset, dict)):
143
+ return "%s: %s of %d items" % (name, tname, len(v))
144
+ if isinstance(v, str):
145
+ return "%s: str (%d characters)" % (name, len(v))
146
+ if isinstance(v, (bytes, bytearray)):
147
+ return "%s: bytes (%d)" % (name, len(v))
148
+ if isinstance(v, (bool, int, float, complex)):
149
+ return "%s: %s" % (name, tname)
150
+ if hasattr(v, "shape"):
151
+ return "%s: %s, shape %s" % (name, tname, tuple(getattr(v, "shape")))
152
+ if hasattr(v, "__len__"):
153
+ return "%s: %s of length %d" % (name, tname, len(v))
154
+ except Exception:
155
+ pass
156
+ return "%s: %s" % (name, tname)