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/__init__.py +72 -0
- asktim/__main__.py +6 -0
- asktim/agent.py +490 -0
- asktim/api.py +41 -0
- asktim/chat.py +106 -0
- asktim/cli.py +577 -0
- asktim/config.py +316 -0
- asktim/context.py +156 -0
- asktim/fileinfo.py +593 -0
- asktim/history.py +214 -0
- asktim/inventory.py +379 -0
- asktim/logbook.py +159 -0
- asktim/net.py +151 -0
- asktim/notebook.py +1010 -0
- asktim/offline.py +110 -0
- asktim/paths.py +81 -0
- asktim/privacy.py +804 -0
- asktim/prompts.py +226 -0
- asktim/providers/__init__.py +173 -0
- asktim/providers/anthropic.py +227 -0
- asktim/providers/gemini.py +215 -0
- asktim/providers/openai.py +135 -0
- asktim/records.py +319 -0
- asktim/render.py +511 -0
- asktim/runner.py +308 -0
- asktim/safety.py +1495 -0
- asktim/shell_setup.py +183 -0
- asktim/ui.py +303 -0
- asktim/viewers.py +97 -0
- asktim-0.1.0.data/scripts/AskTim! +8 -0
- asktim-0.1.0.dist-info/METADATA +458 -0
- asktim-0.1.0.dist-info/RECORD +36 -0
- asktim-0.1.0.dist-info/WHEEL +5 -0
- asktim-0.1.0.dist-info/entry_points.txt +2 -0
- asktim-0.1.0.dist-info/licenses/LICENSE +21 -0
- asktim-0.1.0.dist-info/top_level.txt +1 -0
asktim/chat.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Chat mode: AskTim! explains and suggests; it runs nothing."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
|
|
5
|
+
from . import context, history, inventory, logbook, offline, privacy, prompts
|
|
6
|
+
from .providers import Conversation, ProviderError, make_provider
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def offline_answer(ui, question, stdin_text=None, reason=None):
|
|
10
|
+
"""Built-in help when no AI can be used."""
|
|
11
|
+
t = ui.t
|
|
12
|
+
lines = []
|
|
13
|
+
if stdin_text:
|
|
14
|
+
lines += offline.explain_text(stdin_text)
|
|
15
|
+
cmds, _src = history.recent(5)
|
|
16
|
+
last = history.last_failed(cmds[-2:]) if cmds else None
|
|
17
|
+
if last is not None:
|
|
18
|
+
lines.insert(0, "Your last command, `%s`, failed. %s" % (privacy.clean(last.line)[0], " ".join(offline.explain_command(last))))
|
|
19
|
+
lines += offline.explain_text(question or "")
|
|
20
|
+
if reason:
|
|
21
|
+
t.warn(reason)
|
|
22
|
+
if lines:
|
|
23
|
+
t.line(t.s("AskTim!'s built-in help (no AI):", "bold"))
|
|
24
|
+
for ln in lines:
|
|
25
|
+
t.line("%s %s" % (t.bullet(), ln))
|
|
26
|
+
else:
|
|
27
|
+
t.line("AskTim!'s built-in help knows common error messages: pipe one in, e.g. my_command 2>&1 | AskTim! \"what does this mean?\"")
|
|
28
|
+
return "\n".join(lines)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def ask(cfg, ui, question, files=(), stdin_text=None, new=False, dry_run=False, provider=None, model=None, send_history=None, history_n=None, send_files=None):
|
|
32
|
+
"""Answer one question at the command line. Returns the answer text (or None)."""
|
|
33
|
+
question = (question or "").strip()
|
|
34
|
+
if not question and stdin_text:
|
|
35
|
+
question = "What does this mean, and what should I do?"
|
|
36
|
+
# text pasted into a question: data lines are withheld as from any output
|
|
37
|
+
q_clean, n_q, pasted = privacy.clean_question(question, strict=cfg.strict)
|
|
38
|
+
inv = inventory.gather()
|
|
39
|
+
system = prompts.chat_system(inventory.describe(inv), cfg, notebook=False)
|
|
40
|
+
g = context.terminal(cfg, files=files, stdin_text=stdin_text, send_history=send_history, history_n=history_n, send_files=send_files)
|
|
41
|
+
g.redactions += n_q
|
|
42
|
+
g.withheld += pasted
|
|
43
|
+
if pasted:
|
|
44
|
+
ui.t.warn("AskTim! withheld %d line%s of your question that look like data." % (pasted, "" if pasted == 1 else "s"))
|
|
45
|
+
items = [] if new else logbook.load_chat(int(cfg.get("chat_memory_minutes") or 60))
|
|
46
|
+
conv = Conversation.from_json(items)
|
|
47
|
+
message = g.text() + "Question: " + q_clean
|
|
48
|
+
if dry_run:
|
|
49
|
+
t = ui.t
|
|
50
|
+
t.rule("What AskTim! would send (nothing has been sent)", "cyan")
|
|
51
|
+
t.line(t.s("System prompt (the same for every question):", "bold"))
|
|
52
|
+
t.line(system)
|
|
53
|
+
t.line()
|
|
54
|
+
if items:
|
|
55
|
+
t.line(t.s("The conversation so far: %d earlier messages" % len(items), "bold"))
|
|
56
|
+
t.line(t.s("Your message, with its context:", "bold"))
|
|
57
|
+
t.line(message)
|
|
58
|
+
t.rule("", "cyan")
|
|
59
|
+
t.note(g.summary())
|
|
60
|
+
return None
|
|
61
|
+
conv.user(message)
|
|
62
|
+
try:
|
|
63
|
+
prov = provider or make_provider(cfg, model=model)
|
|
64
|
+
except ProviderError as e:
|
|
65
|
+
if e.kind == "config":
|
|
66
|
+
offline_answer(ui, question, stdin_text)
|
|
67
|
+
ui.t.line()
|
|
68
|
+
ui.t.note(str(e))
|
|
69
|
+
return None
|
|
70
|
+
raise
|
|
71
|
+
ui.chat_header(g.summary(), prov.describe())
|
|
72
|
+
ui.thinking()
|
|
73
|
+
try:
|
|
74
|
+
turn = prov.complete(system, conv, purpose="chat", on_text=ui.stream_text, on_status=ui.status)
|
|
75
|
+
except KeyboardInterrupt:
|
|
76
|
+
ui.end_text()
|
|
77
|
+
ui.t.note("(stopped)")
|
|
78
|
+
return None
|
|
79
|
+
except ProviderError as e:
|
|
80
|
+
ui.end_text()
|
|
81
|
+
ui.t.error(str(e))
|
|
82
|
+
if e.kind in ("network", "busy", "rate"):
|
|
83
|
+
offline_answer(ui, question, stdin_text)
|
|
84
|
+
return None
|
|
85
|
+
blocks = ui.md.blocks if ui.md is not None else []
|
|
86
|
+
ui.end_text()
|
|
87
|
+
if not turn.text.strip():
|
|
88
|
+
ui.t.warn("The model sent an empty answer. Ask again – a second try usually works.")
|
|
89
|
+
return None
|
|
90
|
+
if turn.stop_reason == "refusal":
|
|
91
|
+
ui.t.note("(The model declined to answer this.)")
|
|
92
|
+
# keep the conversation (text only, without the context) for follow-up questions
|
|
93
|
+
conv.items[-1] = {"kind": "user", "text": "Question: " + q_clean}
|
|
94
|
+
conv.assistant(turn)
|
|
95
|
+
logbook.save_chat(conv.to_json())
|
|
96
|
+
from .render import code_blocks
|
|
97
|
+
|
|
98
|
+
cmds = logbook.save_suggested(code_blocks(turn.text) or blocks)
|
|
99
|
+
if cmds and ui.t.interactive():
|
|
100
|
+
from . import shell_setup
|
|
101
|
+
|
|
102
|
+
sh = history.detect_shell()
|
|
103
|
+
if sh in ("bash", "zsh") and shell_setup.installed(sh):
|
|
104
|
+
ui.t.note("Alt+A puts these commands on your command line, one at a time.")
|
|
105
|
+
logbook.add({"mode": "chat", "question": q_clean, "model": turn.model, "provider": prov.name, "sent": g.sent, "cwd": context.paths.pretty(os.getcwd())}, cfg)
|
|
106
|
+
return turn.text
|
asktim/cli.py
ADDED
|
@@ -0,0 +1,577 @@
|
|
|
1
|
+
"""The AskTim! command.
|
|
2
|
+
|
|
3
|
+
AskTim! Claude store a Claude API key (you are asked for it; it is not shown)
|
|
4
|
+
AskTim! Claude KEY the same, with the key on the command line
|
|
5
|
+
AskTim! "my question" ask (chat mode: explains and suggests, runs nothing)
|
|
6
|
+
AskTim! Agent "my task" the agent does the task, asking before each step
|
|
7
|
+
AskTim! status | tools | privacy | help
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import getpass
|
|
11
|
+
import os
|
|
12
|
+
import sys
|
|
13
|
+
|
|
14
|
+
from . import __version__
|
|
15
|
+
from . import config as _config
|
|
16
|
+
|
|
17
|
+
HELP = """\
|
|
18
|
+
AskTim! – an AI helper for bioinformatics that keeps your data out of the AI.
|
|
19
|
+
|
|
20
|
+
Set up (once):
|
|
21
|
+
AskTim! Claude store your Claude API key (paste it when asked; it is not shown)
|
|
22
|
+
AskTim! Gemini …or a Google Gemini key AskTim! OpenAI --url URL …or another service
|
|
23
|
+
AskTim! setup-shell let AskTim! see your latest commands and which ones failed
|
|
24
|
+
|
|
25
|
+
Ask:
|
|
26
|
+
AskTim! "how do I sort a BAM file?"
|
|
27
|
+
AskTim! why explain why your last command failed
|
|
28
|
+
some_command 2>&1 | AskTim! "what does this error mean?"
|
|
29
|
+
AskTim! --file data/counts.csv "how do I plot column 2 against 3?"
|
|
30
|
+
AskTim! a conversation (type your questions; Ctrl+D to stop)
|
|
31
|
+
|
|
32
|
+
Let the agent do it (it asks before each step; nothing is installed; data stay out of the AI):
|
|
33
|
+
AskTim! Agent "map the reads in data/ to ref.fa and count how many map"
|
|
34
|
+
--plan show a plan first --auto run without asking (Ctrl+C stops)
|
|
35
|
+
--script write one script, analysis.sh, and get it working
|
|
36
|
+
--web allow downloads (curl, wget) --here work in this folder, not in asktim-runs/
|
|
37
|
+
--steps N at most N steps --timeout S seconds per command
|
|
38
|
+
|
|
39
|
+
More:
|
|
40
|
+
AskTim! show "question" print exactly what would be sent, and send nothing
|
|
41
|
+
AskTim! status settings, key, model, safeguards
|
|
42
|
+
AskTim! tools the programs and packages AskTim! found
|
|
43
|
+
AskTim! privacy what is sent to the AI, and what never is
|
|
44
|
+
AskTim! model NAME change the model AskTim! use claude|gemini|openai
|
|
45
|
+
AskTim! log your recent questions AskTim! statement a draft statement on your use of AI
|
|
46
|
+
AskTim! new forget the conversation AskTim! forget delete your stored key(s)
|
|
47
|
+
|
|
48
|
+
Options for questions: --no-history, --history N, --no-files, --new, --offline, --model NAME
|
|
49
|
+
Put your question in quotes. (In zsh, an unquoted ? or * is read by the shell first.)
|
|
50
|
+
In a notebook: `import asktim`, then type AskTim! … in a cell. `asktim` is the same command without the "!".
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
SIMPLE_COMMANDS = {"status", "tools", "help", "version", "privacy", "new", "reset", "forget", "logout", "log", "statement",
|
|
54
|
+
"setup-shell", "model", "use", "why", "explain", "doctor", "insert", "cells"}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class Args(object):
|
|
58
|
+
def __init__(self):
|
|
59
|
+
self.pos = []
|
|
60
|
+
self.files = []
|
|
61
|
+
self.opts = {}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
FLAGS = {"--plan", "--auto", "--script", "--here", "--web", "--no-web", "--approve", "--no-history", "--no-files", "--new", "--offline",
|
|
65
|
+
"--strict", "--no-check", "--remove", "--refresh", "--all", "--color", "--no-color", "--help", "--version", "--show", "--dry-run", "--yes"}
|
|
66
|
+
VALUE_OPTS = {"--model", "--provider", "--history", "--file", "-f", "--steps", "--timeout", "--url", "--key", "--since", "--shell", "--script-name", "--effort", "--folder"}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def parse(argv):
|
|
70
|
+
a = Args()
|
|
71
|
+
i = 0
|
|
72
|
+
rest_is_text = False
|
|
73
|
+
while i < len(argv):
|
|
74
|
+
t = argv[i]
|
|
75
|
+
if rest_is_text:
|
|
76
|
+
a.pos.append(t)
|
|
77
|
+
elif t == "--":
|
|
78
|
+
rest_is_text = True
|
|
79
|
+
elif t in ("-h",):
|
|
80
|
+
a.opts["--help"] = True
|
|
81
|
+
elif t in ("-V",):
|
|
82
|
+
a.opts["--version"] = True
|
|
83
|
+
elif t in FLAGS:
|
|
84
|
+
a.opts[t] = True
|
|
85
|
+
elif t.split("=", 1)[0] in VALUE_OPTS:
|
|
86
|
+
if "=" in t:
|
|
87
|
+
k, v = t.split("=", 1)
|
|
88
|
+
else:
|
|
89
|
+
k, v = t, (argv[i + 1] if i + 1 < len(argv) else None)
|
|
90
|
+
i += 1
|
|
91
|
+
if k in ("--file", "-f"):
|
|
92
|
+
a.files.append(v)
|
|
93
|
+
else:
|
|
94
|
+
a.opts[k] = v
|
|
95
|
+
else:
|
|
96
|
+
a.pos.append(t)
|
|
97
|
+
i += 1
|
|
98
|
+
return a
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _read_stdin(wait=0.5):
|
|
102
|
+
"""Text piped into AskTim! (cmd 2>&1 | AskTim! ...), or None.
|
|
103
|
+
|
|
104
|
+
Standard input is read only if something arrives on it soon: under Jupyter's `!`, in some
|
|
105
|
+
editors and in cron, it is a pipe that never sends anything, and reading it would hang.
|
|
106
|
+
"""
|
|
107
|
+
try:
|
|
108
|
+
if sys.stdin is None or sys.stdin.isatty():
|
|
109
|
+
return None
|
|
110
|
+
fd = sys.stdin.fileno()
|
|
111
|
+
except (OSError, ValueError, AttributeError):
|
|
112
|
+
return None
|
|
113
|
+
chunks = []
|
|
114
|
+
total = 0
|
|
115
|
+
limit = 2000000
|
|
116
|
+
if os.name == "posix":
|
|
117
|
+
import select
|
|
118
|
+
|
|
119
|
+
try:
|
|
120
|
+
ready, _, _ = select.select([fd], [], [], wait)
|
|
121
|
+
except (OSError, ValueError):
|
|
122
|
+
return None
|
|
123
|
+
if not ready:
|
|
124
|
+
return None
|
|
125
|
+
while total < limit:
|
|
126
|
+
try:
|
|
127
|
+
ready, _, _ = select.select([fd], [], [], 30)
|
|
128
|
+
except (OSError, ValueError):
|
|
129
|
+
break
|
|
130
|
+
if not ready:
|
|
131
|
+
break
|
|
132
|
+
b = os.read(fd, 65536)
|
|
133
|
+
if not b:
|
|
134
|
+
break
|
|
135
|
+
chunks.append(b)
|
|
136
|
+
total += len(b)
|
|
137
|
+
else:
|
|
138
|
+
import threading
|
|
139
|
+
|
|
140
|
+
box = []
|
|
141
|
+
|
|
142
|
+
def reader():
|
|
143
|
+
try:
|
|
144
|
+
box.append(sys.stdin.buffer.read(limit))
|
|
145
|
+
except Exception:
|
|
146
|
+
pass
|
|
147
|
+
|
|
148
|
+
th = threading.Thread(target=reader)
|
|
149
|
+
th.daemon = True
|
|
150
|
+
th.start()
|
|
151
|
+
th.join(wait + 30)
|
|
152
|
+
chunks = box
|
|
153
|
+
data = b"".join(chunks).decode("utf-8", "replace")
|
|
154
|
+
return data if data.strip() else None
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def main(argv=None):
|
|
158
|
+
argv = sys.argv[1:] if argv is None else list(argv)
|
|
159
|
+
try:
|
|
160
|
+
return _main(argv)
|
|
161
|
+
except KeyboardInterrupt:
|
|
162
|
+
sys.stderr.write("\n(stopped)\n")
|
|
163
|
+
return 130
|
|
164
|
+
except BrokenPipeError:
|
|
165
|
+
return 0
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _cfg(a):
|
|
169
|
+
over = {}
|
|
170
|
+
if a.opts.get("--strict"):
|
|
171
|
+
over["privacy"] = "strict"
|
|
172
|
+
if a.opts.get("--provider"):
|
|
173
|
+
over["provider"] = a.opts["--provider"]
|
|
174
|
+
if a.opts.get("--no-color"):
|
|
175
|
+
over["color"] = "never"
|
|
176
|
+
if a.opts.get("--color"):
|
|
177
|
+
over["color"] = "always"
|
|
178
|
+
if a.opts.get("--effort"):
|
|
179
|
+
over["effort.chat"] = a.opts["--effort"]
|
|
180
|
+
over["effort.agent"] = a.opts["--effort"]
|
|
181
|
+
return _config.Config(over)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _main(argv):
|
|
185
|
+
a = parse(argv)
|
|
186
|
+
if a.opts.get("--version") or (len(a.pos) == 1 and a.pos[0].lower() == "version"):
|
|
187
|
+
print("AskTim! %s" % __version__)
|
|
188
|
+
return 0
|
|
189
|
+
cfg = _cfg(a)
|
|
190
|
+
from .ui import TerminalUI
|
|
191
|
+
|
|
192
|
+
ui = TerminalUI(cfg)
|
|
193
|
+
if a.opts.get("--help") or (len(a.pos) == 1 and a.pos[0].lower() in ("help", "-help")):
|
|
194
|
+
print(HELP)
|
|
195
|
+
return 0
|
|
196
|
+
first = a.pos[0].lower() if a.pos else ""
|
|
197
|
+
|
|
198
|
+
# set-up: AskTim! Claude [KEY]
|
|
199
|
+
prov = _config.normalise_provider(first)
|
|
200
|
+
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") or a.opts.get("--key")):
|
|
201
|
+
key = a.opts.get("--key") or (a.pos[1] if len(a.pos) == 2 else None)
|
|
202
|
+
return setup(cfg, ui, prov, key, a, key_on_command_line=bool(key))
|
|
203
|
+
|
|
204
|
+
if first == "agent":
|
|
205
|
+
task = " ".join(a.pos[1:]).strip()
|
|
206
|
+
stdin = _read_stdin()
|
|
207
|
+
if stdin and not task:
|
|
208
|
+
task = stdin.strip()
|
|
209
|
+
if not task:
|
|
210
|
+
if not ui.interactive:
|
|
211
|
+
ui.error("Give the agent a task: AskTim! Agent \"what it should do\"")
|
|
212
|
+
return 2
|
|
213
|
+
task = ui.t.ask("What should the agent do? ")
|
|
214
|
+
if not task:
|
|
215
|
+
return 2
|
|
216
|
+
return run_agent(cfg, ui, task, a)
|
|
217
|
+
|
|
218
|
+
if first == "show" and len(a.pos) >= 2:
|
|
219
|
+
from . import chat
|
|
220
|
+
|
|
221
|
+
chat.ask(cfg, ui, " ".join(a.pos[1:]), files=a.files, dry_run=True, send_history=False if a.opts.get("--no-history") else None,
|
|
222
|
+
history_n=a.opts.get("--history"), send_files=False if a.opts.get("--no-files") else None)
|
|
223
|
+
return 0
|
|
224
|
+
|
|
225
|
+
if (len(a.pos) == 1 and first in SIMPLE_COMMANDS) or (len(a.pos) == 2 and first in ("model", "use", "forget", "log", "insert")):
|
|
226
|
+
return command(cfg, ui, first, a)
|
|
227
|
+
|
|
228
|
+
question = " ".join(a.pos).strip()
|
|
229
|
+
stdin = _read_stdin()
|
|
230
|
+
if not question and not stdin:
|
|
231
|
+
return conversation(cfg, ui, a)
|
|
232
|
+
if a.opts.get("--offline"):
|
|
233
|
+
from .chat import offline_answer
|
|
234
|
+
|
|
235
|
+
offline_answer(ui, question, stdin)
|
|
236
|
+
return 0
|
|
237
|
+
from . import chat
|
|
238
|
+
|
|
239
|
+
files = [f for f in a.files if f]
|
|
240
|
+
missing = [f for f in files if not os.path.exists(f)]
|
|
241
|
+
if missing:
|
|
242
|
+
ui.error("There is no file %s." % ", ".join(missing))
|
|
243
|
+
return 2
|
|
244
|
+
try:
|
|
245
|
+
ans = chat.ask(cfg, ui, question, files=files, stdin_text=stdin, new=bool(a.opts.get("--new")), model=a.opts.get("--model"),
|
|
246
|
+
send_history=False if a.opts.get("--no-history") else None, history_n=a.opts.get("--history"),
|
|
247
|
+
send_files=False if a.opts.get("--no-files") else None)
|
|
248
|
+
except Exception as e: # a last resort: never show a student a raw traceback for a network problem
|
|
249
|
+
if os.environ.get("ASKTIM_DEBUG"):
|
|
250
|
+
raise
|
|
251
|
+
ui.error("AskTim! had a problem: %s" % e)
|
|
252
|
+
return 1
|
|
253
|
+
return 0 if ans is not None else 1
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def conversation(cfg, ui, a):
|
|
257
|
+
"""`AskTim!` on its own: a conversation in the terminal."""
|
|
258
|
+
from . import chat
|
|
259
|
+
from .providers import make_provider, ProviderError
|
|
260
|
+
|
|
261
|
+
t = ui.t
|
|
262
|
+
try:
|
|
263
|
+
make_provider(cfg)
|
|
264
|
+
except ProviderError as e:
|
|
265
|
+
print(HELP)
|
|
266
|
+
t.note(str(e).split("\n")[0])
|
|
267
|
+
return 0
|
|
268
|
+
if not ui.interactive:
|
|
269
|
+
print(HELP)
|
|
270
|
+
return 0
|
|
271
|
+
t.line(t.s("AskTim!", "bold") + t.s(" – ask about the tools on this computer. Your data stay here. Empty line or Ctrl+D to stop; /agent TASK for the agent; /new to start afresh.", "gray"))
|
|
272
|
+
new = bool(a.opts.get("--new"))
|
|
273
|
+
while True:
|
|
274
|
+
try:
|
|
275
|
+
q = input(t.s("\nAskTim!> ", "cyan", "bold"))
|
|
276
|
+
except EOFError:
|
|
277
|
+
t.line()
|
|
278
|
+
return 0
|
|
279
|
+
q = q.strip()
|
|
280
|
+
if not q or q in ("exit", "quit", "/exit", "/quit", "bye"):
|
|
281
|
+
return 0
|
|
282
|
+
if q == "/new":
|
|
283
|
+
from . import logbook
|
|
284
|
+
|
|
285
|
+
logbook.clear_chat()
|
|
286
|
+
t.note("A new conversation.")
|
|
287
|
+
continue
|
|
288
|
+
if q.startswith("/agent "):
|
|
289
|
+
run_agent(cfg, ui, q[7:], a)
|
|
290
|
+
continue
|
|
291
|
+
chat.ask(cfg, ui, q, new=new)
|
|
292
|
+
new = False
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def setup(cfg, ui, prov, key, a, key_on_command_line=False):
|
|
296
|
+
t = ui.t
|
|
297
|
+
name = {"claude": "Claude", "gemini": "Gemini", "openai": "OpenAI-compatible"}[prov]
|
|
298
|
+
if prov == "openai" and a.opts.get("--url"):
|
|
299
|
+
_config.save_user_setting("openai_base_url", a.opts["--url"].rstrip("/"))
|
|
300
|
+
cfg = _config.Config()
|
|
301
|
+
if a.opts.get("--model"):
|
|
302
|
+
_config.save_user_setting("models." + prov, a.opts["--model"])
|
|
303
|
+
cfg = _config.Config()
|
|
304
|
+
if not key:
|
|
305
|
+
if prov == "openai" and any(h in cfg.get("openai_base_url") for h in ("localhost", "127.0.0.1")):
|
|
306
|
+
key = ""
|
|
307
|
+
elif not ui.interactive:
|
|
308
|
+
ui.error("Give the key: AskTim! %s KEY (or run this in a terminal to be asked for it)" % name)
|
|
309
|
+
return 2
|
|
310
|
+
else:
|
|
311
|
+
where = {"claude": "console.anthropic.com → Settings → API keys", "gemini": "aistudio.google.com/apikey", "openai": "your service's website"}[prov]
|
|
312
|
+
t.line("Paste your %s API key (from %s). It is not shown as you paste it." % (name, where))
|
|
313
|
+
try:
|
|
314
|
+
key = getpass.getpass("Key: ").strip()
|
|
315
|
+
except (EOFError, KeyboardInterrupt):
|
|
316
|
+
return 1
|
|
317
|
+
if not key and prov != "openai":
|
|
318
|
+
ui.error("No key was given.")
|
|
319
|
+
return 2
|
|
320
|
+
if prov == "claude" and key and not key.startswith("sk-ant-"):
|
|
321
|
+
t.warn("That does not look like a Claude key (they start with sk-ant-). Storing it anyway.")
|
|
322
|
+
if key or prov == "openai":
|
|
323
|
+
if not a.opts.get("--no-check"):
|
|
324
|
+
ok = _check_key(cfg, ui, prov, key)
|
|
325
|
+
if ok is False:
|
|
326
|
+
return 1
|
|
327
|
+
if key:
|
|
328
|
+
where = _config.save_key(prov, key)
|
|
329
|
+
t.good("Your %s key is stored in %s (readable by you only)." % (name, _short(where)))
|
|
330
|
+
if cfg.provider != prov and cfg.is_locked("provider"):
|
|
331
|
+
t.note("Your course's settings use %s, so AskTim! keeps using it; this key is stored for later." % _config.PROVIDER_NAMES[cfg.provider])
|
|
332
|
+
else:
|
|
333
|
+
if cfg.provider != prov:
|
|
334
|
+
_config.save_user_setting("provider", prov)
|
|
335
|
+
t.line("AskTim! will use %s (model %s). Try: AskTim! \"what does samtools flagstat tell me?\"" % (name, _config.Config().model(prov)))
|
|
336
|
+
if key_on_command_line:
|
|
337
|
+
t.warn("Your key is now in your shell's history. Next time type just `AskTim! %s` and paste the key when asked. "
|
|
338
|
+
"To remove it from bash's history now: history -d $((HISTCMD-1)). (Starting a command with a space keeps it out of history on most systems.)" % name)
|
|
339
|
+
from . import history, shell_setup
|
|
340
|
+
|
|
341
|
+
sh = history.detect_shell()
|
|
342
|
+
if sh in ("bash", "zsh", "fish") and not shell_setup.installed(sh):
|
|
343
|
+
t.note("Tip: AskTim! setup-shell lets AskTim! see your latest commands and which of them failed.")
|
|
344
|
+
t.note("Remove the key at any time with: AskTim! forget")
|
|
345
|
+
return 0
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def _short(p):
|
|
349
|
+
from . import paths
|
|
350
|
+
|
|
351
|
+
return paths.pretty(p)
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def _check_key(cfg, ui, prov, key):
|
|
355
|
+
"""True: works; False: refused; None: could not check."""
|
|
356
|
+
from .providers import Conversation, ProviderError, make_provider
|
|
357
|
+
|
|
358
|
+
t = ui.t
|
|
359
|
+
t.note("Checking the key with a tiny request…")
|
|
360
|
+
try:
|
|
361
|
+
p = make_provider(cfg, provider=prov, key=key)
|
|
362
|
+
conv = Conversation()
|
|
363
|
+
conv.user("Reply with the single word: ready")
|
|
364
|
+
turn = p.complete("You are being tested for a connection. Reply with one word.", conv, purpose="chat")
|
|
365
|
+
t.good("It works (%s answered)." % (turn.model or p.model))
|
|
366
|
+
return True
|
|
367
|
+
except ProviderError as e:
|
|
368
|
+
if e.kind in ("auth", "credit", "notfound"):
|
|
369
|
+
ui.error(str(e))
|
|
370
|
+
if e.kind == "notfound":
|
|
371
|
+
t.note("The key may be fine; the model was not found. Store it with --no-check and choose a model with: AskTim! model NAME")
|
|
372
|
+
return False
|
|
373
|
+
t.warn("Could not check the key (%s). It is stored anyway; AskTim! status shows it." % e)
|
|
374
|
+
return None
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def run_agent(cfg, ui, task, a):
|
|
378
|
+
from .agent import Agent
|
|
379
|
+
from .providers import ProviderError, make_provider
|
|
380
|
+
|
|
381
|
+
mode = "plan" if a.opts.get("--plan") else "auto" if a.opts.get("--auto") else "script" if a.opts.get("--script") else "approve"
|
|
382
|
+
if mode in ("approve", "plan") and not ui.interactive:
|
|
383
|
+
ui.error("The agent needs you at the keyboard to approve its steps. Run it in a terminal, or let it work alone with --auto.")
|
|
384
|
+
return 2
|
|
385
|
+
if os.name == "nt" and not __import__("shutil").which("bash"):
|
|
386
|
+
ui.error("The agent runs commands in bash, which this computer does not have. Use WSL or Git Bash, or ask questions without Agent.")
|
|
387
|
+
return 2
|
|
388
|
+
try:
|
|
389
|
+
prov = make_provider(cfg, model=a.opts.get("--model"))
|
|
390
|
+
except ProviderError as e:
|
|
391
|
+
ui.error(str(e))
|
|
392
|
+
return 3
|
|
393
|
+
web = True if a.opts.get("--web") else (False if a.opts.get("--no-web") else None)
|
|
394
|
+
if web and cfg.is_locked("agent.allow_network") and not cfg.get("agent.allow_network"):
|
|
395
|
+
ui.warn("Your course's settings do not allow the agent to use the internet; --web is ignored.")
|
|
396
|
+
web = False
|
|
397
|
+
script_name = a.opts.get("--script-name") or "analysis.sh"
|
|
398
|
+
ag = Agent(cfg, prov, ui, task, mode=mode, here=bool(a.opts.get("--here")), allow_network=web,
|
|
399
|
+
max_steps=a.opts.get("--steps"), timeout=a.opts.get("--timeout"), script_name=script_name)
|
|
400
|
+
rec = ag.run()
|
|
401
|
+
return 0 if rec.get("outcome") == "done" else 1
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def command(cfg, ui, name, a):
|
|
405
|
+
t = ui.t
|
|
406
|
+
arg = a.pos[1] if len(a.pos) > 1 else None
|
|
407
|
+
if name == "status" or name == "doctor":
|
|
408
|
+
return status(cfg, ui)
|
|
409
|
+
if name == "tools":
|
|
410
|
+
from . import inventory
|
|
411
|
+
|
|
412
|
+
t.note("Looking for programs and packages…")
|
|
413
|
+
inv = inventory.gather(refresh=True)
|
|
414
|
+
for ln in inventory.describe(inv):
|
|
415
|
+
t.line(ln)
|
|
416
|
+
t.note("This is what AskTim! tells the AI is installed. The agent can use any program on your PATH, but nothing else.")
|
|
417
|
+
return 0
|
|
418
|
+
if name == "privacy":
|
|
419
|
+
from . import logbook, paths
|
|
420
|
+
|
|
421
|
+
print(PRIVACY.format(level=cfg.get("privacy"), log=paths.pretty(logbook.log_file())))
|
|
422
|
+
return 0
|
|
423
|
+
if name in ("new", "reset"):
|
|
424
|
+
from . import logbook
|
|
425
|
+
|
|
426
|
+
logbook.clear_chat()
|
|
427
|
+
t.note("The conversation is forgotten; the next question starts afresh.")
|
|
428
|
+
return 0
|
|
429
|
+
if name in ("forget", "logout"):
|
|
430
|
+
p = _config.normalise_provider(arg) if arg and arg.lower() != "all" else None
|
|
431
|
+
gone = _config.forget_key(p)
|
|
432
|
+
t.good("Deleted the stored key%s for: %s." % ("s" if len(gone) != 1 else "", ", ".join(gone))) if gone else t.note("There was no stored key to delete.")
|
|
433
|
+
env = [e for p_ in _config.PROVIDERS for e in _config.KEY_ENV[p_] if os.environ.get(e)]
|
|
434
|
+
if env:
|
|
435
|
+
t.warn("A key is still set in the environment variable %s (remove it from your shell's settings)." % ", ".join(env))
|
|
436
|
+
return 0
|
|
437
|
+
if name == "log":
|
|
438
|
+
from . import logbook
|
|
439
|
+
|
|
440
|
+
n = int(arg) if arg and arg.isdigit() else 15
|
|
441
|
+
es = logbook.entries(limit=n)
|
|
442
|
+
if not es:
|
|
443
|
+
t.note("Nothing in the log yet.")
|
|
444
|
+
for e in es:
|
|
445
|
+
t.line("%s %-14s %s %s" % (e.get("time", "")[:16].replace("T", " "), e.get("mode", ""), t.s(e.get("model", ""), "gray"), (e.get("question") or "")[:90].replace("\n", " ")))
|
|
446
|
+
return 0
|
|
447
|
+
if name == "statement":
|
|
448
|
+
from . import logbook
|
|
449
|
+
|
|
450
|
+
s = logbook.statement(since=a.opts.get("--since"), folder=None if a.opts.get("--all") else os.getcwd())
|
|
451
|
+
if not s:
|
|
452
|
+
s = logbook.statement(since=a.opts.get("--since"))
|
|
453
|
+
print(s or "AskTim!'s log is empty, so there is nothing to put in a statement yet.")
|
|
454
|
+
return 0
|
|
455
|
+
if name == "setup-shell":
|
|
456
|
+
from . import history, shell_setup
|
|
457
|
+
|
|
458
|
+
sh = a.opts.get("--shell") or history.detect_shell()
|
|
459
|
+
if sh not in ("bash", "zsh", "fish"):
|
|
460
|
+
t.error("AskTim! can set up bash, zsh and fish; your shell is %s." % sh)
|
|
461
|
+
return 2
|
|
462
|
+
if a.opts.get("--remove"):
|
|
463
|
+
f, done = shell_setup.remove(sh)
|
|
464
|
+
t.good("Removed AskTim!'s lines from %s." % _short(f)) if done else t.note("AskTim!'s lines were not in %s." % _short(f))
|
|
465
|
+
return 0
|
|
466
|
+
f, had = shell_setup.install(sh)
|
|
467
|
+
t.good("%s AskTim!'s lines in %s." % ("Updated" if had else "Added", _short(f)))
|
|
468
|
+
t.line("They record each command you type and whether it worked (never its output), so AskTim! can help with the latest one.")
|
|
469
|
+
if sh != "fish":
|
|
470
|
+
t.line("Alt+A then puts the commands from AskTim!'s last answer on your command line, one at a time, for you to read and run.")
|
|
471
|
+
t.line("Start a new terminal, or run: source %s" % _short(f))
|
|
472
|
+
t.note("To undo: AskTim! setup-shell --remove")
|
|
473
|
+
return 0
|
|
474
|
+
if name == "model":
|
|
475
|
+
if not arg:
|
|
476
|
+
t.line("%s: %s" % (_config.PROVIDER_NAMES[cfg.provider], cfg.model()))
|
|
477
|
+
return 0
|
|
478
|
+
if cfg.is_locked("models." + cfg.provider):
|
|
479
|
+
t.error("Your course's settings fix the model.")
|
|
480
|
+
return 1
|
|
481
|
+
_config.save_user_setting("models." + cfg.provider, arg)
|
|
482
|
+
t.good("AskTim! will use %s for %s." % (arg, _config.PROVIDER_NAMES[cfg.provider]))
|
|
483
|
+
return 0
|
|
484
|
+
if name == "use":
|
|
485
|
+
p = _config.normalise_provider(arg)
|
|
486
|
+
if not p:
|
|
487
|
+
t.error("Choose claude, gemini or openai.")
|
|
488
|
+
return 2
|
|
489
|
+
if cfg.is_locked("provider") and p != cfg.provider:
|
|
490
|
+
t.error("Your course's settings fix the AI service (%s)." % _config.PROVIDER_NAMES[cfg.provider])
|
|
491
|
+
return 1
|
|
492
|
+
_config.save_user_setting("provider", p)
|
|
493
|
+
key, _w = _config.find_key(p)
|
|
494
|
+
t.good("AskTim! will use %s." % _config.PROVIDER_NAMES[p])
|
|
495
|
+
if not key and p != "openai":
|
|
496
|
+
t.note("There is no key for it yet: AskTim! %s" % {"claude": "Claude", "gemini": "Gemini"}[p])
|
|
497
|
+
return 0
|
|
498
|
+
if name in ("why", "explain"):
|
|
499
|
+
from . import chat
|
|
500
|
+
|
|
501
|
+
stdin = _read_stdin()
|
|
502
|
+
return 0 if chat.ask(cfg, ui, "Why did my last command fail, and how do I fix it?", stdin_text=stdin) is not None else 1
|
|
503
|
+
if name in ("insert", "cells"):
|
|
504
|
+
t.note("`AskTim! %s` works in a notebook (it adds cells there)." % name)
|
|
505
|
+
return 0
|
|
506
|
+
print(HELP)
|
|
507
|
+
return 0
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def status(cfg, ui):
|
|
511
|
+
from . import history, paths, runner, shell_setup
|
|
512
|
+
|
|
513
|
+
t = ui.t
|
|
514
|
+
t.line(t.s("AskTim! %s" % __version__, "bold"))
|
|
515
|
+
for p in _config.PROVIDERS:
|
|
516
|
+
key, where = _config.find_key(p)
|
|
517
|
+
mark = "→ " if p == cfg.provider else " "
|
|
518
|
+
t.line("%s%-26s model %-22s key %s" % (mark, _config.PROVIDER_NAMES[p], cfg.model(p) or "(none)", ("%s (%s)" % (_config.mask(key), where)) if key else "not set"))
|
|
519
|
+
if cfg.provider == "openai":
|
|
520
|
+
t.line(" address: %s" % cfg.get("openai_base_url"))
|
|
521
|
+
t.line("Privacy: %s (AskTim! privacy explains it)" % cfg.get("privacy"))
|
|
522
|
+
sh = history.detect_shell()
|
|
523
|
+
hooked = shell_setup.installed(sh) if sh in ("bash", "zsh", "fish") else False
|
|
524
|
+
t.line("Shell: %s; AskTim!'s shell integration %s%s" % (sh, "is installed" if hooked else "is not installed (AskTim! setup-shell)",
|
|
525
|
+
"; it is recording" if history.hook_active() else ""))
|
|
526
|
+
sb, why = runner.make_sandbox(cfg.get("agent.sandbox") or "auto", os.getcwd(), os.getcwd(), False) if os.access(os.getcwd(), os.W_OK) else (None, "this folder cannot be written")
|
|
527
|
+
t.line("Agent: at most %s steps, %s s per command, internet %s; %s" % (cfg.get("agent.max_steps"), cfg.get("agent.command_timeout"),
|
|
528
|
+
"allowed" if cfg.get("agent.allow_network") else "off (unless --web)", sb.describe() if sb else "no sandbox (%s)" % why))
|
|
529
|
+
if sb:
|
|
530
|
+
sb.cleanup()
|
|
531
|
+
t.note("Settings: %s%s" % (paths.pretty(_config.config_file()), ("; course settings: %s" % paths.site_config_file()) if os.path.exists(paths.site_config_file()) else ""))
|
|
532
|
+
if cfg.data.get("locked"):
|
|
533
|
+
t.note("Fixed by your course: %s" % ", ".join(cfg.data["locked"]))
|
|
534
|
+
if cfg.get("course"):
|
|
535
|
+
t.note("Course notes for the AI: %s" % cfg.get("course")[:200])
|
|
536
|
+
return 0
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
PRIVACY = """\
|
|
540
|
+
What AskTim! sends to the AI service you chose (with your own key), and what it never sends.
|
|
541
|
+
|
|
542
|
+
Sent with a question:
|
|
543
|
+
• your question;
|
|
544
|
+
• what is installed on this computer: programs (and their versions), Python and R packages;
|
|
545
|
+
• your recent shell commands - with secrets (API keys, tokens, passwords), e-mail addresses,
|
|
546
|
+
NHS numbers, phone numbers and long sequences taken out, and your user name replaced by "user";
|
|
547
|
+
• the names and sizes of the files in the current folder;
|
|
548
|
+
• if you ask about a file (--file), a description of its structure: format, size, number of
|
|
549
|
+
records, and for a table the column names and the kind of values in each - not the values;
|
|
550
|
+
• if you pipe text in (cmd 2>&1 | AskTim!), that text with lines that look like data withheld.
|
|
551
|
+
In a notebook: the code of the cells you have run (with tables pasted into the code and long
|
|
552
|
+
lists of numbers withheld), the names, types and shapes of your variables (not their values),
|
|
553
|
+
and the last error message.
|
|
554
|
+
|
|
555
|
+
Sent by the agent: its commands and files (which you see first), and what each command printed
|
|
556
|
+
with every line that looks like data withheld - sequences, reads, alignments, variants,
|
|
557
|
+
intervals, table rows, lists of IDs or numbers, encoded data. Error messages, warnings, help
|
|
558
|
+
text, versions, counts, summaries and file listings get through, and so does text: if the
|
|
559
|
+
agent reads a README or your notes, the AI sees them.
|
|
560
|
+
|
|
561
|
+
Never sent: the contents of your data files, your keys, your shell history beyond the last
|
|
562
|
+
commands, anything from ~/.ssh and other credentials.
|
|
563
|
+
|
|
564
|
+
Settings: privacy is "{level}". "strict" (AskTim! --strict ..., or "privacy": "strict" in the
|
|
565
|
+
settings) also withholds column names, file listings and summaries, and quoted values in errors.
|
|
566
|
+
|
|
567
|
+
Limits: the filter recognises data by their shape. It is made for bioinformatics data and
|
|
568
|
+
works well on them, but it cannot promise to catch every piece of free text - a name quoted in
|
|
569
|
+
an error message, for example (strict mode replaces quoted values). Do not use AskTim!, or any
|
|
570
|
+
AI tool, on personal or patient data unless your institution has approved it. `AskTim! show
|
|
571
|
+
"question"` prints everything that would be sent, without sending it.
|
|
572
|
+
|
|
573
|
+
What the AI service does with what it receives is set by its terms (for Claude: Anthropic's
|
|
574
|
+
API terms; for Gemini's free tier, Google may use what is sent to improve its products outside
|
|
575
|
+
the UK, Switzerland and the EEA). A local log of your questions is kept in
|
|
576
|
+
{log} (AskTim! log); it never leaves your computer.
|
|
577
|
+
"""
|