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/notebook.py ADDED
@@ -0,0 +1,1010 @@
1
+ """AskTim! in Jupyter and Google Colab notebooks.
2
+
3
+ After `import asktim` (or `%load_ext asktim`) a cell can start with AskTim!, exactly as at the
4
+ command line:
5
+
6
+ AskTim! Claude store a key (asked for; or use Colab's Secrets)
7
+ AskTim! "why does this cell fail?" a question about the notebook
8
+ AskTim! Agent "plot the library sizes in counts.csv"
9
+ AskTim! insert 2 put code block 2 of the last answer into a new cell
10
+ AskTim! cells the cells the agent made (next one, or all)
11
+
12
+ `%AskTim! ...`, `%%AskTim! ...` (with text or code below the first line) and asktim.ask() /
13
+ asktim.agent() work too.
14
+
15
+ What goes with a question: the code of the cells you have run, the names, types and shapes of
16
+ your variables (never their values), the last error, and what is installed - never the
17
+ contents of your data or of your variables.
18
+
19
+ Adding cells: Jupyter (JupyterLab, Notebook 7, classic) can take one new cell from the kernel
20
+ at a time, below the cell that is running. So the agent's cells arrive one by one: each one
21
+ that you run brings the next. Markdown cells come as `%%markdown` cells, which show their text
22
+ when run. Colab and VS Code cannot take cells from the kernel: there the cells are shown in
23
+ the output, with a Copy button, and the whole run is saved as a notebook file you can open.
24
+ """
25
+
26
+ import base64
27
+ import html
28
+ import io
29
+ import json
30
+ import os
31
+ import re
32
+ import shlex
33
+ import sys
34
+ import time
35
+ import traceback
36
+ import uuid
37
+
38
+ from . import config as _config
39
+ from . import context, fileinfo, inventory, logbook, paths, privacy, prompts, safety
40
+ from .providers import Conversation, ProviderError, ToolResult, make_provider
41
+ from .render import inline_code, inline_markdown, safe_markdown
42
+
43
+ _STATE = {
44
+ "ip": None,
45
+ "loaded": False,
46
+ "last_error": None,
47
+ "chat": Conversation(),
48
+ "answers": [], # code blocks of the last answer: (language, code)
49
+ "queue": [], # cells waiting to be added: {"kind": "markdown"|"code", "source": str}
50
+ "queue_total": 0,
51
+ "nested": 0,
52
+ "welcomed": False,
53
+ }
54
+
55
+ MARK = re.compile(r"AskTim! cell (\d+) of (\d+)")
56
+
57
+
58
+ # ------------------------------------------------------------------------------------------------
59
+ # loading
60
+ # ------------------------------------------------------------------------------------------------
61
+
62
+
63
+ def _transform(lines):
64
+ """Lets a cell start with `AskTim! ...` (a line further down may too)."""
65
+ if not lines:
66
+ return lines
67
+ pat = re.compile(r"^(\s*)(?:AskTim!|asktim!)(?=\s|$)(.*)$")
68
+ m = pat.match(lines[0].rstrip("\n"))
69
+ if m:
70
+ first = m.group(2).strip()
71
+ rest = "".join(lines[1:])
72
+ if rest.strip():
73
+ return ["get_ipython().run_cell_magic('AskTim', %r, %r)\n" % (first, rest)]
74
+ return ["get_ipython().run_line_magic('AskTim', %r)\n" % first]
75
+ out = []
76
+ for ln in lines:
77
+ m = pat.match(ln.rstrip("\n"))
78
+ out.append("%sget_ipython().run_line_magic('AskTim', %r)\n" % (m.group(1), m.group(2).strip()) if m else ln)
79
+ return out
80
+
81
+
82
+ def load(ip):
83
+ if _STATE["loaded"] and _STATE["ip"] is ip:
84
+ return
85
+ _STATE["ip"] = ip
86
+ for name in ("AskTim!", "AskTim", "asktim"):
87
+ ip.register_magic_function(_magic, magic_kind="line_cell", magic_name=name)
88
+ if _transform not in ip.input_transformers_cleanup:
89
+ ip.input_transformers_cleanup.append(_transform)
90
+ ip.events.register("post_run_cell", _post_run_cell)
91
+ _STATE["loaded"] = True
92
+ if not _STATE["welcomed"]:
93
+ _STATE["welcomed"] = True
94
+ cfg = _config.Config()
95
+ key, where = _config.find_key(cfg.provider)
96
+ tail = "" if key else " First set up a key: <code>AskTim! Claude</code>" + (" (or put it in Colab's Secrets as <code>ANTHROPIC_API_KEY</code>)" if frontend() == "colab" else "") + "."
97
+ _html("<div style='font-family:sans-serif;font-size:13px;color:#555'><b>AskTim!</b> is ready: start a cell with "
98
+ "<code>AskTim! \"your question\"</code> or <code>AskTim! Agent \"a task\"</code>. Your data stay here.%s</div>" % tail)
99
+
100
+
101
+ def unload(ip):
102
+ try:
103
+ ip.input_transformers_cleanup.remove(_transform)
104
+ except ValueError:
105
+ pass
106
+ try:
107
+ ip.events.unregister("post_run_cell", _post_run_cell)
108
+ except ValueError:
109
+ pass
110
+ _STATE["loaded"] = False
111
+
112
+
113
+ def frontend():
114
+ if "google.colab" in sys.modules:
115
+ return "colab"
116
+ ip = _STATE["ip"]
117
+ if os.environ.get("VSCODE_PID") or os.environ.get("VSCODE_CWD") or (ip is not None and "__vsc_ipynb_file__" in ip.user_ns):
118
+ return "vscode"
119
+ return "jupyter"
120
+
121
+
122
+ def _post_run_cell(result):
123
+ if _STATE["nested"]:
124
+ return
125
+ try:
126
+ info = getattr(result, "info", None)
127
+ raw = getattr(info, "raw_cell", "") or ""
128
+ err = getattr(result, "error_in_exec", None) or getattr(result, "error_before_exec", None)
129
+ if err is not None and not _is_asktim_cell(raw):
130
+ tb = "".join(traceback.format_exception(type(err), err, err.__traceback__))
131
+ _STATE["last_error"] = {"cell": raw, "error": "%s: %s" % (type(err).__name__, err), "traceback": tb, "time": time.time()}
132
+ elif err is None and not _is_asktim_cell(raw) and raw.strip():
133
+ pass
134
+ m = MARK.search(raw[:300])
135
+ if m and _STATE["queue"]:
136
+ _deliver_next()
137
+ except Exception:
138
+ pass
139
+
140
+
141
+ def _is_asktim_cell(raw):
142
+ s = (raw or "").lstrip()
143
+ return s.startswith(("AskTim!", "asktim!", "%AskTim", "%%AskTim", "%asktim", "%%asktim")) or "run_line_magic('AskTim'" in s or "run_cell_magic('AskTim'" in s
144
+
145
+
146
+ # ------------------------------------------------------------------------------------------------
147
+ # display helpers
148
+ # ------------------------------------------------------------------------------------------------
149
+
150
+
151
+ def _display(obj, **kw):
152
+ try:
153
+ from IPython.display import display
154
+
155
+ return display(obj, **kw)
156
+ except Exception:
157
+ print(obj)
158
+
159
+
160
+ def _html(s, **kw):
161
+ from IPython.display import HTML
162
+
163
+ return _display(HTML(s), **kw)
164
+
165
+
166
+ def _md(s, **kw):
167
+ from IPython.display import Markdown
168
+
169
+ return _display(Markdown(s), **kw)
170
+
171
+
172
+ def _fence(code, lang=""):
173
+ f = "```"
174
+ while f in code:
175
+ f += "`"
176
+ return "%s%s\n%s\n%s" % (f, lang, code.rstrip("\n"), f)
177
+
178
+
179
+ def _copy_box(code, lang="python", title=""):
180
+ cid = "asktim-%s" % uuid.uuid4().hex[:10]
181
+ esc = html.escape(code)
182
+ return (
183
+ "<div style='border:1px solid #ccc;border-radius:6px;margin:6px 0;font-family:sans-serif'>"
184
+ "<div style='display:flex;justify-content:space-between;align-items:center;background:#f3f3f3;padding:3px 8px;font-size:12px;color:#444'>"
185
+ "<span>%s</span><button style='font-size:12px' onclick=\"navigator.clipboard.writeText(document.getElementById('%s').innerText);this.innerText='Copied'\">Copy</button></div>"
186
+ "<pre id='%s' style='margin:0;padding:8px;white-space:pre-wrap;font-size:12.5px'>%s</pre></div>" % (html.escape(title or lang), cid, cid, esc)
187
+ )
188
+
189
+
190
+ def _ansi(text, code):
191
+ return "\x1b[%sm%s\x1b[0m" % (code, text)
192
+
193
+
194
+ # ------------------------------------------------------------------------------------------------
195
+ # cells
196
+ # ------------------------------------------------------------------------------------------------
197
+
198
+
199
+ def _insert_cell(source, replace=False):
200
+ """Put source into a new cell below (Jupyter); False where the frontend cannot."""
201
+ ip = _STATE["ip"]
202
+ if ip is None or frontend() != "jupyter":
203
+ return False
204
+ try:
205
+ ip.set_next_input(source, replace=replace)
206
+ return True
207
+ except Exception:
208
+ return False
209
+
210
+
211
+ def _cell_source(cell, i, n):
212
+ if cell["kind"] == "markdown":
213
+ # the text is the model's: made safe, since the notebook will render it as trusted Markdown
214
+ return "%%%%markdown\n<!-- AskTim! cell %d of %d: run this cell to show the text%s -->\n%s" % (i, n, " and to get the next cell" if i < n else "", safe_markdown(cell["source"].rstrip("\n")))
215
+ head = "# AskTim! cell %d of %d%s" % (i, n, (" – " + cell["why"]) if cell.get("why") else "")
216
+ if i < n:
217
+ head += "\n# (run it to get the next cell)"
218
+ return head + "\n" + cell["source"].rstrip("\n")
219
+
220
+
221
+ def _deliver_next():
222
+ q = _STATE["queue"]
223
+ if not q:
224
+ return False
225
+ n = _STATE["queue_total"]
226
+ i = n - len(q) + 1
227
+ cell = q[0]
228
+ if _insert_cell(_cell_source(cell, i, n)):
229
+ q.pop(0)
230
+ return True
231
+ return False
232
+
233
+
234
+ def _show_cells(cells, title):
235
+ parts = ["<div style='font-family:sans-serif;font-size:13px;margin:4px 0'><b>%s</b></div>" % html.escape(title)]
236
+ for i, c in enumerate(cells, 1):
237
+ if c["kind"] == "markdown":
238
+ parts.append("<div style='border-left:3px solid #bbb;padding:2px 10px;margin:6px 0;color:#333'><div style='font-size:11px;color:#888'>Markdown cell %d</div><pre style='white-space:pre-wrap;font-family:inherit'>%s</pre></div>" % (i, html.escape(c["source"])))
239
+ else:
240
+ parts.append(_copy_box(c["source"], "python", "Code cell %d%s" % (i, (" – " + c["why"]) if c.get("why") else "")))
241
+ _html("".join(parts))
242
+
243
+
244
+ def deliver_cells(cells, record_path=None):
245
+ """Hand the agent's cells to the notebook, as well as this frontend allows."""
246
+ if not cells:
247
+ return
248
+ fe = frontend()
249
+ _STATE["queue"] = list(cells)
250
+ _STATE["queue_total"] = len(cells)
251
+ if fe == "jupyter":
252
+ if _deliver_next():
253
+ print(_ansi("AskTim! put the first of %d cell%s below. Each one you run brings the next (or: AskTim! cells all, for all of them in one cell)." % (len(cells), "" if len(cells) == 1 else "s"), "36"))
254
+ return
255
+ where = "Colab" if fe == "colab" else "VS Code" if fe == "vscode" else "This notebook"
256
+ _show_cells(cells, "%s cannot take new cells from code, so here they are: copy each code cell into a new cell (Colab: Ctrl+M B adds one below)." % where)
257
+ if record_path:
258
+ print(_ansi("The whole run is also saved as a notebook: %s" % paths.pretty(record_path), "90"))
259
+ _STATE["queue"] = []
260
+
261
+
262
+ # ------------------------------------------------------------------------------------------------
263
+ # what goes with a question
264
+ # ------------------------------------------------------------------------------------------------
265
+
266
+
267
+ def _cells_run(max_cells=15, max_chars=6000):
268
+ ip = _STATE["ip"]
269
+ try:
270
+ hist = list(ip.history_manager.input_hist_raw)
271
+ except Exception:
272
+ hist = list(ip.user_ns.get("In", []) or [])
273
+ cells = [c for c in hist if c and c.strip() and not _is_asktim_cell(c)]
274
+ out, size = [], 0
275
+ for c in reversed(cells[-max_cells:]):
276
+ if size + len(c) > max_chars and out:
277
+ break
278
+ out.append(c)
279
+ size += len(c)
280
+ return list(reversed(out)), len(cells)
281
+
282
+
283
+ def variables_text(strict=False, limit=40):
284
+ ip = _STATE["ip"]
285
+ ns = ip.user_ns
286
+ hidden = set(getattr(ip, "user_ns_hidden", {}) or {})
287
+ lines = []
288
+ for name in sorted(ns):
289
+ if name.startswith("_") or name in hidden or name in ("In", "Out", "exit", "quit", "get_ipython", "asktim"):
290
+ continue
291
+ d = context.describe_value(name, ns[name], strict=strict)
292
+ if d:
293
+ lines.append(d)
294
+ if len(lines) >= limit:
295
+ lines.append("… and more")
296
+ break
297
+ return lines
298
+
299
+
300
+ def _packages():
301
+ try:
302
+ import importlib.metadata as md
303
+ except ImportError: # Python 3.7
304
+ return {}
305
+ have = {}
306
+ for d in md.distributions():
307
+ try:
308
+ have[d.metadata["Name"].lower()] = d.version
309
+ except Exception:
310
+ pass
311
+ pk = {n: have[n.lower()] for n in inventory.PY_PACKAGES if n.lower() in have}
312
+ return {"python": sys.version.split()[0], "packages": pk, "count": len(have)}
313
+
314
+
315
+ def notebook_context(cfg, attached=None):
316
+ strict = cfg.strict
317
+ g = context.Gathered()
318
+
319
+ def clean(t):
320
+ t, n = privacy.clean(t, strict=strict)
321
+ g.redactions += n
322
+ return t
323
+
324
+ fe = {"colab": "Google Colab", "vscode": "a VS Code notebook", "jupyter": "a Jupyter notebook"}[frontend()]
325
+ g.add("The student is working in %s; the notebook's code runs in %s." % (fe, clean(paths.pretty(os.getcwd()))), None)
326
+ if cfg.get("send_file_names", True):
327
+ g.add("Files in that folder (names and sizes only):\n" + clean(fileinfo.listing(os.getcwd(), strict=strict)), "names of the files in the notebook's folder")
328
+ cells, total = _cells_run()
329
+ if cells:
330
+ parts = []
331
+ for c in cells:
332
+ c, w = privacy.filter_code(c, strict=strict) # data typed into the code (a pasted table, a list of numbers)
333
+ g.withheld += w
334
+ parts.append("# --- cell ---\n" + clean(c))
335
+ body = "\n\n".join(parts)
336
+ g.add("The code of the last %d cells the student ran (of %d), oldest first:\n```python\n%s\n```" % (len(cells), total, body), "the code of your last %d cells" % len(cells))
337
+ vs = variables_text(strict=strict)
338
+ if vs:
339
+ g.add("The student's variables (names, types and shapes only - not their values):\n" + "\n".join(" " + clean(v) for v in vs), "the names, types and shapes of your variables")
340
+ err = _STATE["last_error"]
341
+ if err and time.time() - err["time"] < 3600:
342
+ fr = privacy.filter_output(err["traceback"], kind="default", strict=strict)
343
+ g.withheld += fr.withheld
344
+ g.add("The last error, in this cell:\n```python\n%s\n```\nIt raised:\n```text\n%s\n```" % (clean(privacy.filter_code(err["cell"], strict=strict)[0])[-3000:], privacy.shorten(fr.text, 3000)), "the last error")
345
+ if attached:
346
+ fr = privacy.filter_output(attached, kind="default", strict=strict)
347
+ g.withheld += fr.withheld
348
+ g.add("Text or code the student attached to the question (lines that look like data are withheld):\n```text\n%s\n```" % privacy.shorten(clean(fr.text), 6000), "the text under your question (%s)" % fr.summary())
349
+ return g
350
+
351
+
352
+ # ------------------------------------------------------------------------------------------------
353
+ # chat
354
+ # ------------------------------------------------------------------------------------------------
355
+
356
+
357
+ class _Streamer(object):
358
+ """Shows the answer as Markdown while it arrives (updated a few times a second)."""
359
+
360
+ def __init__(self):
361
+ from IPython.display import Markdown
362
+
363
+ self.text = ""
364
+ self.handle = _display(Markdown("*AskTim! is thinking…*"), display_id=True)
365
+ self.t = 0
366
+
367
+ def feed(self, delta):
368
+ self.text += delta or ""
369
+ if time.time() - self.t > 0.25:
370
+ self._update(" ▍")
371
+
372
+ def status(self, msg):
373
+ self._update(("\n\n" if self.text else "") + "*%s*" % html.escape(msg))
374
+
375
+ def _update(self, ours=""):
376
+ """The model's text (made safe: it is rendered as trusted Markdown) followed by AskTim!'s own."""
377
+ self.t = time.time()
378
+ try:
379
+ from IPython.display import Markdown
380
+
381
+ if self.handle is not None:
382
+ self.handle.update(Markdown(safe_markdown(self.text) + ours))
383
+ except Exception:
384
+ pass
385
+
386
+ def done(self, extra=""):
387
+ self._update(extra)
388
+
389
+
390
+ def _footer(blocks):
391
+ if not blocks:
392
+ return ""
393
+ names = ", ".join("%d (%s)" % (i, lang or "code") for i, (lang, _c) in enumerate(blocks, 1))
394
+ fe = frontend()
395
+ how = "`AskTim! insert N` puts block N into a new cell" if fe == "jupyter" else "`AskTim! insert N` shows block N with a Copy button"
396
+ return "\n\n---\n<small>Code blocks: %s. %s.</small>" % (names, how)
397
+
398
+
399
+ def nb_ask(question, attached=None, new=False, model=None, files=()):
400
+ from .render import code_blocks
401
+
402
+ cfg = _config.Config()
403
+ if new:
404
+ _STATE["chat"] = Conversation()
405
+ q_clean, n, pasted = privacy.clean_question(question, strict=cfg.strict)
406
+ if pasted:
407
+ print(_ansi("AskTim! withheld %d line%s of your question that look like data." % (pasted, "" if pasted == 1 else "s"), "33"))
408
+ if not q_clean.strip() and attached:
409
+ q_clean = "What does this mean, and what should I do?"
410
+ if not q_clean.strip():
411
+ err = _STATE["last_error"]
412
+ q_clean = "Why did my last cell fail, and how do I fix it?" if err else ""
413
+ if not q_clean.strip():
414
+ _md("Ask a question: `AskTim! \"how do I read a tab-separated file with pandas?\"`")
415
+ return None
416
+ inv = inventory.gather()
417
+ system = prompts.chat_system(inventory.describe(inv, notebook_packages=_packages()), cfg, notebook=True)
418
+ g = notebook_context(cfg, attached=attached)
419
+ g.redactions += n
420
+ g.withheld += pasted
421
+ for f in files or ():
422
+ g.add("A file the student asked about: " + privacy.clean(fileinfo.describe(f, strict=cfg.strict))[0], "a description of %s" % os.path.basename(f))
423
+ try:
424
+ prov = make_provider(cfg, model=model)
425
+ except ProviderError as e:
426
+ from . import offline
427
+
428
+ tips = offline.explain_text((_STATE["last_error"] or {}).get("error", "") + "\n" + (attached or ""))
429
+ _md("**AskTim!** has no AI set up yet.\n\n%s\n\n%s" % (safe_markdown("\n".join("- " + t for t in tips)) if tips else "", str(e).replace("\n\n", "\n\n").replace(" AskTim!", "`AskTim!").replace("Claude\n", "Claude`\n")))
430
+ return None
431
+ print(_ansi(g.summary(), "90"))
432
+ conv = _STATE["chat"]
433
+ conv.user(g.text() + "Question: " + q_clean)
434
+ st = _Streamer()
435
+ try:
436
+ turn = prov.complete(system, conv, purpose="chat", on_text=st.feed, on_status=st.status)
437
+ except ProviderError as e:
438
+ conv.items.pop()
439
+ st.done("\n\n**The AI service returned an error.** %s" % safe_markdown(str(e)))
440
+ return None
441
+ except KeyboardInterrupt:
442
+ conv.items.pop()
443
+ st.done("\n\n*(stopped)*")
444
+ return None
445
+ conv.items[-1] = {"kind": "user", "text": "Question: " + q_clean}
446
+ conv.assistant(turn)
447
+ conv.items[:] = conv.items[-20:]
448
+ blocks = code_blocks(turn.text)
449
+ _STATE["answers"] = blocks
450
+ st.done(_footer(blocks) + "\n\n<small>%s · %s</small>" % (html.escape(prov.describe()), "data stayed on this computer"))
451
+ logbook.add({"mode": "chat", "question": q_clean, "model": turn.model, "provider": prov.name, "sent": g.sent, "cwd": paths.pretty(os.getcwd()), "notebook": True}, cfg)
452
+ return None
453
+
454
+
455
+ def _insert_block(n):
456
+ blocks = _STATE["answers"]
457
+ if not blocks:
458
+ _md("There is no answer with code yet.")
459
+ return
460
+ if n < 1 or n > len(blocks):
461
+ _md("The last answer has %d code block%s." % (len(blocks), "" if len(blocks) == 1 else "s"))
462
+ return
463
+ lang, code = blocks[n - 1]
464
+ src = ("%%bash\n" + code) if lang in ("bash", "sh", "shell", "console") else code
465
+ if _insert_cell(src):
466
+ print(_ansi("Block %d is in a new cell below: read it, then run it." % n, "36"))
467
+ else:
468
+ _html(_copy_box(src, lang or "python", "Block %d – copy it into a new cell" % n))
469
+
470
+
471
+ # ------------------------------------------------------------------------------------------------
472
+ # the agent in a notebook
473
+ # ------------------------------------------------------------------------------------------------
474
+
475
+
476
+ class _Tee(io.TextIOBase):
477
+ def __init__(self, orig, buf):
478
+ self.orig = orig
479
+ self.buf = buf
480
+
481
+ def write(self, s):
482
+ self.buf.append(s)
483
+ return self.orig.write(s)
484
+
485
+ def flush(self):
486
+ try:
487
+ self.orig.flush()
488
+ except Exception:
489
+ pass
490
+
491
+ def isatty(self):
492
+ return False
493
+
494
+ @property
495
+ def encoding(self):
496
+ return getattr(self.orig, "encoding", "utf-8")
497
+
498
+
499
+ class NotebookTools(object):
500
+ """The tools only a notebook has: run_python, describe_variable, add_*_cell."""
501
+
502
+ def __init__(self, ip, cfg):
503
+ self.ip = ip
504
+ self.cfg = cfg
505
+ self.cells = []
506
+
507
+ def packages(self):
508
+ return _packages()
509
+
510
+ def state_text(self):
511
+ lines = []
512
+ vs = variables_text(strict=self.cfg.strict)
513
+ if vs:
514
+ lines.append("The student's notebook variables (names, types and shapes only):")
515
+ lines += [" " + privacy.clean(v, strict=self.cfg.strict)[0] for v in vs]
516
+ cells, total = _cells_run(max_cells=8, max_chars=3000)
517
+ if cells:
518
+ lines.append("The code of the student's last %d cells (of %d):" % (len(cells), total))
519
+ lines.append("```python\n%s\n```" % "\n\n".join(privacy.clean(privacy.filter_code(c, strict=self.cfg.strict)[0], strict=self.cfg.strict)[0] for c in cells))
520
+ err = _STATE["last_error"]
521
+ if err and time.time() - err["time"] < 3600:
522
+ fr = privacy.filter_output(err["traceback"], strict=self.cfg.strict)
523
+ lines.append("The student's last error:\n```text\n%s\n```" % privacy.shorten(fr.text, 2000))
524
+ lines.append("Notebook: %s; its folder is %s." % (frontend(), paths.pretty(os.getcwd())))
525
+ return "\n".join(lines)
526
+
527
+ def handle(self, agent, call, step):
528
+ name = call.name
529
+ if name == "run_python":
530
+ return self._run_python(agent, call, step)
531
+ if name == "describe_variable":
532
+ v = str(call.input.get("name") or "")
533
+ ns = self.ip.user_ns
534
+ step["decision"] = "auto"
535
+ if v not in ns:
536
+ return ToolResult(call.id, name, "There is no variable called %s." % v, True)
537
+ d = context.describe_value(v, ns[v], strict=self.cfg.strict) or v
538
+ extra = self._missing(ns[v]) if not self.cfg.strict else ""
539
+ msg = privacy.clean(d + extra, strict=self.cfg.strict)[0]
540
+ step["sent"] = msg
541
+ agent.ui.note("AskTim! described the variable %s to the AI: %s" % (v, msg))
542
+ return ToolResult(call.id, name, msg)
543
+ if name in ("add_markdown_cell", "add_code_cell"):
544
+ src = str(call.input.get("text") or call.input.get("code") or "")
545
+ kind = "markdown" if name == "add_markdown_cell" else "code"
546
+ step["text" if kind == "markdown" else "code"] = src
547
+ if kind == "code":
548
+ v = safety.Verdict()
549
+ safety._check_text_code(src, v, safety.Context(agent.work_dir, student_dir=agent.student_dir, allow_network=agent.allow_network), "Python")
550
+ if v.level == "block":
551
+ step["decision"] = "blocked"
552
+ step["blocked"] = v.reasons
553
+ agent.ui.blocked(step, v)
554
+ return ToolResult(call.id, name, "Not added: %s." % "; ".join(v.reasons), True)
555
+ step["decision"] = "auto"
556
+ self.cells.append({"kind": kind, "source": src, "why": str(call.input.get("why") or "")})
557
+ agent.ui.cell_added(step, kind, src)
558
+ return ToolResult(call.id, name, "Added a %s cell to the notebook (it is cell %d of this run's cells; they appear when the run ends)." % (kind, len(self.cells)))
559
+ return ToolResult(call.id, name, "Unknown tool.", True)
560
+
561
+ def _missing(self, v):
562
+ try:
563
+ if type(v).__name__ == "DataFrame":
564
+ na = v.isna().sum()
565
+ bad = [(str(c), int(n)) for c, n in na.items() if n]
566
+ return "; missing values: %s" % (", ".join("%s %d" % x for x in bad[:20]) if bad else "none")
567
+ except Exception:
568
+ pass
569
+ return ""
570
+
571
+ def _check(self, agent, code):
572
+ v = safety.Verdict()
573
+ ctx = safety.Context(agent.work_dir, student_dir=agent.student_dir, allow_network=agent.allow_network)
574
+ ctx.protect = agent.protect
575
+ safety._check_text_code(code, v, ctx, "Python")
576
+ safety.check_notebook_page(code, v)
577
+ # shell lines inside the code (!cmd, %%bash cells) get the shell's checks
578
+ shell = []
579
+ lines = code.splitlines()
580
+ if lines and lines[0].strip().startswith(("%%bash", "%%sh", "%%script")):
581
+ shell.append("\n".join(lines[1:]))
582
+ for ln in lines:
583
+ s = ln.strip()
584
+ if s.startswith("!"):
585
+ shell.append(s[1:])
586
+ elif s.startswith(("%system", "%sx")):
587
+ shell.append(s.split(None, 1)[1] if " " in s else "")
588
+ elif s.startswith(("%pip", "%conda", "%mamba")):
589
+ v.block("installing packages is not allowed")
590
+ for sh in shell:
591
+ sv = safety.check(sh, agent.work_dir, allow_network=agent.allow_network, student_dir=agent.student_dir, cwd=os.getcwd(), protect=agent.protect)
592
+ for r in sv.reasons:
593
+ (v.block if sv.level == "block" else v.confirm)(r)
594
+ return v
595
+
596
+ def _run_python(self, agent, call, step):
597
+ code = str(call.input.get("code") or "")
598
+ step["code"] = code
599
+ verdict = self._check(agent, code)
600
+ decision, new, comment = agent.decide(step, "python", verdict, code)
601
+ if decision == "blocked":
602
+ return ToolResult(call.id, call.name, "Not run: AskTim! does not allow this code – %s." % "; ".join(verdict.reasons), True)
603
+ if decision == "refuse":
604
+ return ToolResult(call.id, call.name, "Not run: the student refused this step." + (" Their reason: %s" % comment if comment else ""), True)
605
+ prefix = ("The student allowed this step, with a comment: %s\n" % comment) if comment else ""
606
+ ns = self.ip.user_ns
607
+ before = {k: id(v) for k, v in ns.items() if not k.startswith("_")}
608
+ buf = []
609
+ shown = []
610
+ pub = self.ip.display_pub
611
+ orig_publish = pub.publish
612
+
613
+ def publish(data, *a, **k):
614
+ try:
615
+ kinds = sorted(data.keys()) if isinstance(data, dict) else []
616
+ shown.append("figure" if any(x.startswith("image/") for x in kinds) else "table" if "text/html" in kinds else ", ".join(kinds))
617
+ except Exception:
618
+ pass
619
+ return orig_publish(data, *a, **k)
620
+
621
+ old_out, old_err = sys.stdout, sys.stderr
622
+ t0 = time.time()
623
+ _STATE["nested"] += 1
624
+ try:
625
+ pub.publish = publish
626
+ sys.stdout, sys.stderr = _Tee(old_out, buf), _Tee(old_err, buf)
627
+ res = self.ip.run_cell(code, store_history=False)
628
+ finally:
629
+ sys.stdout, sys.stderr = old_out, old_err
630
+ pub.publish = orig_publish
631
+ _STATE["nested"] -= 1
632
+ dt = time.time() - t0
633
+ err = getattr(res, "error_in_exec", None) or getattr(res, "error_before_exec", None)
634
+ step["ok"] = err is None
635
+ step["exit"] = 0 if err is None else 1
636
+ step["seconds"] = round(dt, 2)
637
+ printed = "".join(buf)
638
+ fr = privacy.filter_output(printed, strict=self.cfg.strict)
639
+ agent.withheld += fr.withheld
640
+ step["withheld"] = fr.withheld
641
+ step["lines"] = fr.total
642
+ step["output_tail"] = privacy.mask_identity("\n".join(printed.splitlines()[-30:]))
643
+ parts = [prefix + ("It ran without an error (%.1f s)." % dt if err is None else "It raised %s: %s" % (type(err).__name__, privacy.clean(str(err), strict=self.cfg.strict)[0][:500]))]
644
+ if err is not None:
645
+ tb = "".join(traceback.format_exception(type(err), err, err.__traceback__))
646
+ tf = privacy.filter_output(tb, strict=self.cfg.strict)
647
+ parts.append("Traceback (data lines withheld):\n" + privacy.shorten(tf.text, 2500))
648
+ if printed.strip():
649
+ parts.append("What it printed (%d line%s%s):\n%s" % (fr.total, "" if fr.total == 1 else "s", "; %d withheld as data" % fr.withheld if fr.withheld else "", privacy.shorten(fr.text, agent.out_chars)))
650
+ r = getattr(res, "result", None)
651
+ if r is not None:
652
+ parts.append("The result of the last line (shown to the student): " + (context.describe_value("result", r, strict=self.cfg.strict) or type(r).__name__).replace("result: ", "", 1))
653
+ if shown:
654
+ parts.append("Displayed to the student: %s (you are not sent what it shows)." % ", ".join(shown))
655
+ changed = [k for k, v in ns.items() if not k.startswith("_") and (k not in before or before[k] != id(v)) and k not in ("In", "Out")]
656
+ if changed:
657
+ ds = [context.describe_value(k, ns[k], strict=self.cfg.strict) for k in changed[:15]]
658
+ parts.append("New or changed variables: " + "; ".join(privacy.clean(d, strict=self.cfg.strict)[0] for d in ds if d))
659
+ msg = "\n".join(parts)
660
+ step["sent"] = msg
661
+ agent.ui.python_result(step, err, fr, shown)
662
+ return ToolResult(call.id, call.name, msg, err is not None)
663
+
664
+ def finish_run(self, rec):
665
+ rp = os.path.join(rec["work_dir"], "agent-record.ipynb") if not rec.get("here") else None
666
+ deliver_cells(self.cells, record_path=rp)
667
+
668
+
669
+ class NotebookUI(object):
670
+ """The agent's steps under a notebook cell; questions are asked with input()."""
671
+
672
+ def __init__(self, ip):
673
+ self.ip = ip
674
+ self.agent_mode = True
675
+ self._held = []
676
+ self._think = None
677
+
678
+ @property
679
+ def interactive(self):
680
+ k = getattr(self.ip, "kernel", None)
681
+ return bool(k is not None and getattr(k, "_allow_stdin", True))
682
+
683
+ def _input(self, prompt):
684
+ try:
685
+ return input(prompt)
686
+ except (EOFError, Exception) as e:
687
+ if type(e).__name__ == "StdinNotImplementedError":
688
+ return None
689
+ if isinstance(e, KeyboardInterrupt):
690
+ raise
691
+ return None
692
+
693
+ def note(self, text):
694
+ print(_ansi(text, "90"))
695
+
696
+ def warn(self, text):
697
+ print(_ansi(text, "33"))
698
+
699
+ def error(self, text):
700
+ print(_ansi(text, "31"))
701
+
702
+ def status(self, text):
703
+ self.note("… " + text)
704
+
705
+ def thinking(self):
706
+ self._held = []
707
+ from IPython.display import Markdown
708
+
709
+ self._think = _display(Markdown("*thinking…*"), display_id=True)
710
+
711
+ def stream_text(self, delta):
712
+ if delta:
713
+ self._held.append(delta)
714
+
715
+ def end_text(self):
716
+ if self._think is not None:
717
+ try:
718
+ from IPython.display import HTML
719
+
720
+ self._think.update(HTML(""))
721
+ except Exception:
722
+ pass
723
+ self._think = None
724
+
725
+ def agent_says(self, text):
726
+ if (text or "").strip():
727
+ _md(safe_markdown(text))
728
+
729
+ def start(self, info):
730
+ _html("<div style='font-family:sans-serif;border-left:4px solid #3a7bd5;padding:4px 10px;margin:6px 0'>"
731
+ "<b>AskTim! Agent</b> · run %d · %s<br><b>Task:</b> %s<br><span style='color:#666;font-size:12px'>Folder: %s · %s · %s; internet %s; at most %d steps. "
732
+ "The AI never sees your data: output reaches it with data lines withheld. "
733
+ "Python steps run in this notebook with your own permissions (no sandbox).</span></div>" % (
734
+ info["number"], html.escape({"approve": "approve each step", "plan": "plan first", "auto": "autonomous", "script": "write a script"}[info["mode"]]),
735
+ html.escape(info["task"]), html.escape(info["folder"]), html.escape(info["model"]), html.escape(info["sandbox"]),
736
+ "allowed for downloads" if info["network"] else "off", info["max_steps"]))
737
+
738
+ def show_step(self, step, kind, show, verdict, asking=False):
739
+ what = {"command": "run a command", "file": "write a file", "open": "open a file", "python": "run Python code"}.get(kind, kind)
740
+ lang = {"command": "bash", "python": "python"}.get(kind, "")
741
+ body = "**Step %d · %s**%s\n\n" % (step["n"], what, (" – " + inline_markdown(step["why"])) if step.get("why") else "")
742
+ if kind == "file":
743
+ body += "%s\n\n" % inline_code(step.get("path"))
744
+ body += _fence(show if show.count("\n") < 60 else "\n".join(show.splitlines()[:60]) + "\n… (%d more lines)" % (show.count("\n") - 59), "")
745
+ elif kind == "open":
746
+ body += "Open %s" % inline_code(show)
747
+ else:
748
+ body += _fence(show, lang)
749
+ if verdict is not None and verdict.level == "confirm":
750
+ body += "\n\n⚠️ AskTim! asks you to check this one: " + inline_markdown("; ".join(verdict.reasons))
751
+ _md(body)
752
+
753
+ def approve(self, step, kind, show, verdict):
754
+ from .ui import Decision
755
+
756
+ self.show_step(step, kind, show, verdict, asking=True)
757
+ if kind == "open":
758
+ a = (self._input("Open it? [y/N] ") or "n").strip().lower()
759
+ return Decision("run" if a.startswith("y") else "refuse")
760
+ while True:
761
+ a = self._input("Run it? [Enter/y] yes · [n] no · [a] all (stop asking) · [q] quit: " if kind != "file" else "Write it? [Enter/y] yes · [n] no · [a] all · [q] quit: ")
762
+ if a is None:
763
+ return Decision("stop")
764
+ a = a.strip().lower()
765
+ if a in ("", "y", "yes"):
766
+ return Decision("run")
767
+ if a in ("a", "all") and not (verdict is not None and verdict.level == "confirm"):
768
+ return Decision("all")
769
+ if a in ("q", "quit", "stop"):
770
+ return Decision("stop")
771
+ if a in ("n", "no"):
772
+ why = self._input("Why not, or what should it do instead? (the agent is told; Enter to skip): ") or ""
773
+ return Decision("refuse", comment=why.strip() or None)
774
+
775
+ def blocked(self, step, verdict):
776
+ _md("**Step %d** – ⛔ not allowed: %s\n\n%s" % (step["n"], inline_markdown("; ".join(verdict.reasons)), _fence(step.get("command") or step.get("code") or "", "bash" if step.get("command") else "python")))
777
+
778
+ def running(self, step):
779
+ pass
780
+
781
+ def output(self, stream, text):
782
+ (sys.stderr if stream == "stderr" else sys.stdout).write(text)
783
+
784
+ def result(self, step, res, fr):
785
+ ok = res.exit_code == 0
786
+ bits = ["%.1f s" % res.duration]
787
+ if fr.withheld:
788
+ bits.append("the AI was shown %d of %d lines; %d withheld as data" % (fr.kept, fr.total, fr.withheld))
789
+ print(_ansi(("✓ exit 0" if ok else "✗ exit %s" % res.exit_code), "32" if ok else "31") + _ansi(" · " + " · ".join(bits), "90"))
790
+
791
+ def python_result(self, step, err, fr, shown):
792
+ bits = ["%.1f s" % step.get("seconds", 0)]
793
+ if fr.withheld:
794
+ bits.append("%d printed line%s withheld from the AI as data" % (fr.withheld, "" if fr.withheld == 1 else "s"))
795
+ if shown:
796
+ bits.append("the AI was told only that %s was shown" % " and ".join(shown))
797
+ print(_ansi("✓ ran" if err is None else "✗ error", "32" if err is None else "31") + _ansi(" · " + " · ".join(bits), "90"))
798
+
799
+ def inspected(self, step, desc):
800
+ _md("**Step %d · look at a file** – AskTim! described %s to the AI (its structure, not its contents):\n\n%s" % (step["n"], inline_code(step.get("path")), _fence(desc, "text")))
801
+
802
+ def cell_added(self, step, kind, src):
803
+ _md("**Step %d · %s cell for your notebook**%s\n\n%s" % (step["n"], kind.capitalize(), (" – " + inline_markdown(step["why"])) if step.get("why") else "", _fence(src, "python" if kind == "code" else "markdown")))
804
+
805
+ def ask_stop(self):
806
+ a = self._input("Stop the agent? [y/N] ") or ""
807
+ return a.strip().lower().startswith("y")
808
+
809
+ def plan_review(self, plan):
810
+ _md("**The agent's plan**\n\n" + safe_markdown(plan or ""))
811
+ if not self.interactive:
812
+ return "cancel", None
813
+ while True:
814
+ a = self._input("Approve the plan? [Enter/y] yes · [s] yes, but ask before each step · [c] ask for changes · [q] cancel: ")
815
+ if a is None:
816
+ return "cancel", None
817
+ a = a.strip().lower()
818
+ if a in ("", "y", "yes"):
819
+ return "approve-auto", None
820
+ if a.startswith("s"):
821
+ return "approve-steps", None
822
+ if a.startswith("c"):
823
+ fb = (self._input("What should change? ") or "").strip()
824
+ if fb:
825
+ return "change", fb
826
+ if a.startswith("q"):
827
+ return "cancel", None
828
+
829
+ def reply_to_question(self, text):
830
+ _md(safe_markdown(text or ""))
831
+ return (self._input("The agent asked you something. Your answer (Enter to end the run): ") or "").strip()
832
+
833
+ def open_file(self, path, program=None):
834
+ if program:
835
+ from . import viewers
836
+
837
+ ok, how = viewers.launch(path, program)
838
+ if ok:
839
+ return ok, how
840
+ shown, how2 = self.open_file(path)
841
+ return shown, "%s; %s" % (how, how2) if shown else how
842
+ try:
843
+ low = path.lower()
844
+ size = os.path.getsize(path)
845
+ if low.endswith((".html", ".htm")):
846
+ if size > 25 << 20:
847
+ return False, "the report is too large to show here (%s)" % fileinfo.human(size)
848
+ with open(path, encoding="utf-8", errors="replace") as f:
849
+ doc = f.read()
850
+ _html('<iframe srcdoc="%s" style="width:100%%;height:600px;border:1px solid #ccc" sandbox="allow-scripts"></iframe>' % html.escape(doc, quote=True))
851
+ return True, "shown under the cell"
852
+ if low.endswith((".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp")):
853
+ from IPython.display import Image, SVG
854
+
855
+ _display(SVG(filename=path) if low.endswith(".svg") else Image(filename=path))
856
+ return True, "shown under the cell"
857
+ if low.endswith(".pdf"):
858
+ if size > 20 << 20:
859
+ return False, "the PDF is too large to show here"
860
+ with open(path, "rb") as f:
861
+ b64 = base64.b64encode(f.read()).decode()
862
+ _html('<embed src="data:application/pdf;base64,%s" type="application/pdf" style="width:100%%;height:600px">' % b64)
863
+ return True, "shown under the cell"
864
+ if fileinfo.is_code_file(path) or low.endswith((".txt", ".log", ".md")):
865
+ with open(path, encoding="utf-8", errors="replace") as f:
866
+ text = f.read(200000)
867
+ _md(_fence(text, ""))
868
+ return True, "shown under the cell"
869
+ return False, "AskTim! shows HTML reports, images, PDFs and text files; open %s yourself" % paths.pretty(path)
870
+ except OSError as e:
871
+ return False, str(e)
872
+
873
+ def report(self, text, outcome):
874
+ _md("**The agent's report**%s\n\n%s\n\n<small>The report is the model's own words: check it against the steps above.</small>" % ("" if outcome == "done" else " (%s)" % outcome, safe_markdown(text or "(no report)")))
875
+
876
+ def finish(self, written, rec):
877
+ self.note("AskTim! wrote the record of this run: %s" % ", ".join(written))
878
+
879
+
880
+ def nb_agent(task, mode="approve", here=False, web=None, steps=None, timeout=None, model=None):
881
+ from .agent import Agent
882
+
883
+ ip = _STATE["ip"]
884
+ if ip is None:
885
+ from IPython import get_ipython
886
+
887
+ ip = get_ipython()
888
+ load(ip)
889
+ cfg = _config.Config()
890
+ ui = NotebookUI(ip)
891
+ if mode in ("approve", "plan") and not ui.interactive:
892
+ _md("The agent needs you to approve its steps, and this notebook cannot ask (it is not being run by a person). Use `AskTim! Agent --auto ...` to let it work alone.")
893
+ return None
894
+ try:
895
+ prov = make_provider(cfg, model=model)
896
+ except ProviderError as e:
897
+ _md("**AskTim!** " + safe_markdown(str(e)))
898
+ return None
899
+ if web and cfg.is_locked("agent.allow_network") and not cfg.get("agent.allow_network"):
900
+ web = False
901
+ tools = NotebookTools(ip, cfg)
902
+ ag = Agent(cfg, prov, ui, task, mode=mode, here=here, allow_network=web, max_steps=steps, timeout=timeout, notebook=tools, student_dir=os.getcwd())
903
+ return ag.run()
904
+
905
+
906
+ # ------------------------------------------------------------------------------------------------
907
+ # the magic: everything after "AskTim!" in a cell
908
+ # ------------------------------------------------------------------------------------------------
909
+
910
+
911
+ def _scrub_key(raw_line, key):
912
+ """A key typed into a cell is in the notebook and in IPython's history: take it out where possible."""
913
+ ip = _STATE["ip"]
914
+ hm = getattr(ip, "history_manager", None)
915
+ fixed = False
916
+ try:
917
+ for lst in (hm.input_hist_raw, hm.input_hist_parsed):
918
+ for i in range(len(lst) - 1, max(-1, len(lst) - 4), -1):
919
+ if key in lst[i]:
920
+ lst[i] = lst[i].replace(key, "[key removed]")
921
+ fixed = True
922
+ for i, ent in enumerate(list(getattr(hm, "db_input_cache", []))):
923
+ if key in str(ent):
924
+ hm.db_input_cache[i] = tuple(x.replace(key, "[key removed]") if isinstance(x, str) else x for x in ent)
925
+ try:
926
+ with hm.db:
927
+ hm.db.execute("UPDATE history SET source=replace(source, ?, '[key removed]'), source_raw=replace(source_raw, ?, '[key removed]') WHERE session=?", (key, key, hm.session_number))
928
+ except Exception:
929
+ pass
930
+ except Exception:
931
+ pass
932
+ replaced = _insert_cell(raw_line.replace(key, "").rstrip(), replace=True)
933
+ return fixed, replaced
934
+
935
+
936
+ def _magic(line, cell=None):
937
+ from . import cli
938
+
939
+ try:
940
+ argv = shlex.split(line or "")
941
+ except ValueError:
942
+ argv = (line or "").split()
943
+ a = cli.parse(argv)
944
+ first = a.pos[0].lower() if a.pos else ""
945
+ cfg = _config.Config()
946
+ from .ui import TerminalUI
947
+
948
+ ui = TerminalUI(cfg)
949
+ ui.t.color = True
950
+ prov = _config.normalise_provider(first)
951
+ if prov and (len(a.pos) == 1 or (len(a.pos) == 2 and _config.looks_like_key(a.pos[1])) or a.opts.get("--url")):
952
+ key = a.pos[1] if len(a.pos) == 2 else None
953
+ if key:
954
+ fixed, replaced = _scrub_key("AskTim! " + line, key)
955
+ print(_ansi("Your key was typed into this cell, so it is in the notebook. %s Next time type just `AskTim! %s` and paste the key when asked%s." % (
956
+ "AskTim! has removed it from the cell." if replaced else "Delete it from the cell before you save or share the notebook!",
957
+ {"claude": "Claude", "gemini": "Gemini", "openai": "OpenAI"}[prov], " - or, in Colab, use Secrets (the key icon) with the name ANTHROPIC_API_KEY" if frontend() == "colab" else ""), "33"))
958
+ if frontend() == "colab" and not key:
959
+ print(_ansi("In Colab you can instead store the key in Secrets (the key icon on the left), named ANTHROPIC_API_KEY (Claude), GEMINI_API_KEY or OPENAI_API_KEY, and give this notebook access. Colab's runtime forgets a key stored here when it stops.", "90"))
960
+ return cli.setup(cfg, ui, prov, key, a, key_on_command_line=False)
961
+ if first == "agent":
962
+ task = " ".join(a.pos[1:]).strip()
963
+ if cell and cell.strip():
964
+ task = (task + "\n" + cell).strip()
965
+ if not task:
966
+ print("Give the agent a task: AskTim! Agent \"what it should do\"")
967
+ return None
968
+ mode = "plan" if a.opts.get("--plan") else "auto" if a.opts.get("--auto") else "script" if a.opts.get("--script") else "approve"
969
+ nb_agent(task, mode=mode, here=bool(a.opts.get("--here")), web=True if a.opts.get("--web") else None, steps=a.opts.get("--steps"), timeout=a.opts.get("--timeout"), model=a.opts.get("--model"))
970
+ return None
971
+ if first == "insert" and len(a.pos) == 2 and a.pos[1].isdigit():
972
+ _insert_block(int(a.pos[1]))
973
+ return None
974
+ if first == "cells":
975
+ sub = a.pos[1].lower() if len(a.pos) > 1 else "next"
976
+ q = _STATE["queue"]
977
+ if not q:
978
+ print("There are no cells waiting from the agent.")
979
+ elif sub == "all":
980
+ src = "\n\n".join(("# " + c["source"].replace("\n", "\n# ")) if c["kind"] == "markdown" else c["source"] for c in q)
981
+ if not _insert_cell(src):
982
+ _html(_copy_box(src, "python", "All the agent's cells, as one"))
983
+ _STATE["queue"] = []
984
+ elif sub == "clear":
985
+ _STATE["queue"] = []
986
+ print("The waiting cells are forgotten.")
987
+ else:
988
+ if not _deliver_next():
989
+ _show_cells(q, "The agent's cells")
990
+ return None
991
+ if first == "new" and len(a.pos) == 1:
992
+ _STATE["chat"] = Conversation()
993
+ print("The conversation is forgotten; the next question starts afresh.")
994
+ return None
995
+ if first in ("why", "explain") and len(a.pos) == 1:
996
+ return nb_ask("Why did my last cell fail, and how do I fix it?")
997
+ if first == "show" and len(a.pos) >= 2:
998
+ g = notebook_context(cfg, attached=cell)
999
+ inv = inventory.gather()
1000
+ _md("**What AskTim! would send (nothing has been sent):**\n\n" + _fence(prompts.chat_system(inventory.describe(inv, notebook_packages=_packages()), cfg, notebook=True), "text") + "\n\n" + _fence(g.text() + "Question: " + " ".join(a.pos[1:]), "text") + "\n\n" + safe_markdown(g.summary()))
1001
+ return None
1002
+ if (len(a.pos) == 1 and first in cli.SIMPLE_COMMANDS) or (len(a.pos) == 2 and first in ("model", "use", "forget", "log")) or a.opts.get("--help"):
1003
+ if a.opts.get("--help") or first == "help":
1004
+ print(cli.HELP)
1005
+ return None
1006
+ cli.command(cfg, ui, first, a)
1007
+ return None
1008
+ question = " ".join(a.pos).strip()
1009
+ nb_ask(question, attached=cell, new=bool(a.opts.get("--new")), model=a.opts.get("--model"), files=[f for f in a.files if f])
1010
+ return None