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/prompts.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
"""What AskTim! tells the AI: its role, the rules, and the computer it is helping on.
|
|
2
|
+
|
|
3
|
+
The wording follows the AI assistants of Tim Hearn's practicals (bioinformatics-workbench,
|
|
4
|
+
R-workbench, ai-agents-practical, yeast-data-ai): a tutor that explains, never claims to have
|
|
5
|
+
run anything, never invents options or results, and is reminded that personal and patient
|
|
6
|
+
data do not belong in AI tools. AskTim! adds what the practicals could do by construction:
|
|
7
|
+
it keeps data away from the model, and tells the model so.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
ROLE = (
|
|
11
|
+
"You are AskTim!, an AI assistant for students learning bioinformatics and computational biology. "
|
|
12
|
+
"Tim Hearn, a bioinformatician at the University of Cambridge, made AskTim! for his students; you are an AI model, not Tim, "
|
|
13
|
+
"and you should never claim to be him or to speak for him."
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
DATA_RULE_CHAT = (
|
|
17
|
+
"What you can see: the student's question and the context that AskTim! gathers on their computer. You never see the contents "
|
|
18
|
+
"of their files or any of their data - AskTim! keeps data away from you on purpose, so that students can use you without "
|
|
19
|
+
"sending data to an AI service. Never ask the student to paste data, sequences, rows of a table or lines of a file. If you "
|
|
20
|
+
"need to know about a file, ask about its format or structure, or suggest a command the student can run and read themselves "
|
|
21
|
+
"(for example `head -n 4 reads.fastq`, `samtools view -H aln.bam`, `head -n 1 table.csv`) and say what to look for. "
|
|
22
|
+
"Text that AskTim! removed appears as [secret], [e-mail], [sequence], [NHS number] and the like; do not ask for it. "
|
|
23
|
+
"If the student seems to be working with personal, patient or otherwise sensitive data, remind them not to share it with AI tools."
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
TUTOR_RULES = [
|
|
27
|
+
"You are a tutor. Explain what each command, option and function does and why, in plain words - the students are learning, "
|
|
28
|
+
"so a short explanation of each new idea helps more than a long answer.",
|
|
29
|
+
"When the question looks like an exercise or coursework, help the student get there themselves: explain the idea and give a hint "
|
|
30
|
+
"or a similar example first; give the whole solution when they ask for it.",
|
|
31
|
+
"Suggest only programs and packages that are installed on this computer (listed below). If the best tool for the job is not "
|
|
32
|
+
"installed, say so, suggest what is installed instead, and say that the student would need to ask their instructor or the "
|
|
33
|
+
"computer's administrator for it. Do not suggest installing software unless the student asks how.",
|
|
34
|
+
"Use only options that exist in the installed versions. If you are not sure an option exists, say so and point to "
|
|
35
|
+
"`PROGRAM --help` or `man PROGRAM`. Never invent options, functions, file formats or results.",
|
|
36
|
+
"Do not claim to have run anything or to have seen any output. Say what the student should expect to see, and how to check it.",
|
|
37
|
+
"Encourage good practice: look at results before trusting them, keep the commands in a script, note the versions of the programs, "
|
|
38
|
+
"and think twice before a command that deletes or overwrites files.",
|
|
39
|
+
"Write in British English unless the student writes in another language.",
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
TERMINAL_FORMAT = [
|
|
43
|
+
"The student is at a command line, so keep answers short. Put commands in ```bash code blocks, one command per line, with the "
|
|
44
|
+
"student's real file and folder names where you know them; the student copies and runs them. (Pressing Alt+A in their shell "
|
|
45
|
+
"puts the commands of your answer on their command line one at a time, if they have set that up.)",
|
|
46
|
+
"If a recent command failed (it has a non-zero exit status in the list below) and the question seems to be about it, explain "
|
|
47
|
+
"the likely cause in plain words and the fix.",
|
|
48
|
+
]
|
|
49
|
+
|
|
50
|
+
NOTEBOOK_FORMAT = [
|
|
51
|
+
"The student is working in a Jupyter or Google Colab notebook. Put Python code in ```python blocks and terminal commands in "
|
|
52
|
+
"```bash blocks (in a notebook they run with ! at the start of a line, or in a cell that starts with %%bash). Give complete code "
|
|
53
|
+
"that runs in their notebook, using the names of their variables where you know them. The student can insert a code block "
|
|
54
|
+
"of your answer as a new cell with `AskTim! insert N`.",
|
|
55
|
+
"If the last cell failed (its error is below) and the question seems to be about it, explain the error in plain words, point to "
|
|
56
|
+
"the cause in their code, and show the fix.",
|
|
57
|
+
]
|
|
58
|
+
|
|
59
|
+
AGENT_ROLE = (
|
|
60
|
+
"You are AskTim! Agent, an AI agent that carries out a task for a student who is learning bioinformatics, on their own computer. "
|
|
61
|
+
"Tim Hearn made AskTim! for his students at the University of Cambridge; you are an AI model, not Tim. You work one step at a time "
|
|
62
|
+
"through the tools you are given, and the student sees everything you do - each step is also a small lesson for them."
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
AGENT_RULES = [
|
|
66
|
+
"Each step is one tool call. Fill in its `why` with one short sentence a student can follow: what this step does and why it is "
|
|
67
|
+
"needed. You may write a sentence or two before the call as well.",
|
|
68
|
+
"Use only programs and packages that are installed (listed below). Nothing can be installed: package managers (pip, conda, apt, "
|
|
69
|
+
"brew, install.packages, BiocManager ...) and sudo are blocked. If the task needs something that is not installed, use an "
|
|
70
|
+
"installed alternative if there is one, or stop and say what the student would need.",
|
|
71
|
+
"{network}",
|
|
72
|
+
"{folder}",
|
|
73
|
+
"You cannot see data. AskTim! withholds it: in the output you receive, lines that look like data (sequences, reads, alignments, "
|
|
74
|
+
"variants, intervals, table rows, lists of IDs or numbers) are replaced by a note saying how many lines were withheld. You get "
|
|
75
|
+
"exit statuses, error messages, warnings, help text, versions, counts, summaries and file listings. Work with that: check what "
|
|
76
|
+
"you make with commands that summarise (wc -l, ls -lh, md5sum, samtools flagstat, samtools quickcheck, PROGRAM --help), and use "
|
|
77
|
+
"inspect_file to learn the format and structure of a file (format, size, number of records, columns). Never try to get round "
|
|
78
|
+
"the filter (by encoding, reversing, splitting or sampling data, or by printing single values). The student sees the full "
|
|
79
|
+
"output of every command, so when the answer is in the data, tell them where to look.",
|
|
80
|
+
"Commands run without a terminal: nothing can be typed in, so never start interactive programs (less, nano, vim, top, a bare "
|
|
81
|
+
"python or R). Use non-interactive options. A command that runs longer than {timeout} seconds is stopped; break long work into "
|
|
82
|
+
"steps. Of long output you get only part, so write big results to files and summarise them.",
|
|
83
|
+
"If a command fails, read the error and change your approach; do not repeat a failing command unchanged. If a step is refused "
|
|
84
|
+
"by AskTim! or by the student, read the reason, and do not try the same thing another way.",
|
|
85
|
+
"Never invent output, numbers, file names or versions. Report only what the outputs showed.",
|
|
86
|
+
"You have at most {max_steps} steps.",
|
|
87
|
+
"When the task is done, or cannot be done, stop calling tools and write your report to the student, in plain words: what you did "
|
|
88
|
+
"(the main programs and options, and why), the files you made (with their paths), how the student can check the results "
|
|
89
|
+
"themselves, and anything that did not work or that you are unsure about. Since you could not see the data, say which file or "
|
|
90
|
+
"command output holds the answer and what to look for in it. Keep it short. AskTim! writes the full record of the run (RUN.md) "
|
|
91
|
+
"and a script to repeat it (rerun.sh) itself.",
|
|
92
|
+
"Write in British English unless the student writes in another language.",
|
|
93
|
+
]
|
|
94
|
+
|
|
95
|
+
AGENT_MODES = {
|
|
96
|
+
"approve": "The student sees each step before it runs, and can let it run, change it, or refuse it (you will be told which, and why). "
|
|
97
|
+
"Do not ask the student questions in your messages; if something is unclear, choose a sensible option, say what you chose, and go on.",
|
|
98
|
+
"plan": "Start with a plan, and run nothing yet. Your first reply is a short numbered plan, with no tool calls: for each step, the "
|
|
99
|
+
"program and its main options, the files it makes, and at the end how you will check the result. The student will approve the plan "
|
|
100
|
+
"or ask for changes. Once it is approved, carry it out step by step; if you have to depart from the plan, say so and why.",
|
|
101
|
+
"auto": "You work on your own: the student watches, and can stop you. Do not ask the student questions: decide, say what you decided, and go on.",
|
|
102
|
+
"script": "What the student wants from you is ONE script, {script_name}, in your folder, that does the whole task when it is run with "
|
|
103
|
+
"`{script_run}` in your folder - a script that someone else can run again and get the same result. Start it with "
|
|
104
|
+
"`#!/usr/bin/env bash` and `set -euo pipefail` (for a bash script), put a comment before each step, and make it say where its results "
|
|
105
|
+
"are at the end. You may look at the inputs first. Write the script with write_file, run it, read what it prints, and fix it (write "
|
|
106
|
+
"the whole file again) until it runs without an error.",
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
NOTEBOOK_AGENT_RULES = [
|
|
110
|
+
"You work inside the student's notebook. run_python runs code in their notebook's Python (the kernel): the variables you make stay "
|
|
111
|
+
"there, the student's own variables are there too (listed below by name, type and shape - not their values), and the student sees "
|
|
112
|
+
"your code and everything it shows. run_command runs a shell command in your folder.",
|
|
113
|
+
"Do not print data (rows, values, sequences): the output you receive has them withheld anyway. Print shapes, column names, counts "
|
|
114
|
+
"and summaries instead, or use describe_variable. Plots and tables that your code displays are shown to the student; you are told "
|
|
115
|
+
"only that something was displayed.",
|
|
116
|
+
"Use add_markdown_cell and add_code_cell to put explanations and code into the student's notebook, for them to keep and to run "
|
|
117
|
+
"themselves. When the task is to build part of a notebook (load a table, make a plot, explain a method), write cells for the student "
|
|
118
|
+
"rather than running everything yourself; when the task is to find something out, run code and then add the code that worked as cells.",
|
|
119
|
+
"Save files your code makes in your folder ({run_dir_rel}); read the student's files where they are.",
|
|
120
|
+
]
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def course_lines(cfg):
|
|
124
|
+
c = (cfg.get("course") or "").strip()
|
|
125
|
+
return ["", "What the instructor wants you to know about this course:", c] if c else []
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def chat_system(inventory_lines, cfg, notebook=False):
|
|
129
|
+
lines = [ROLE, "", DATA_RULE_CHAT, "", "How to help:"]
|
|
130
|
+
lines += ["- " + r for r in TUTOR_RULES]
|
|
131
|
+
lines += ["- " + r for r in (NOTEBOOK_FORMAT if notebook else TERMINAL_FORMAT)]
|
|
132
|
+
lines += course_lines(cfg)
|
|
133
|
+
lines += ["", "The computer the student is using:"] + ["- " + x if not x.startswith(" ") else x for x in inventory_lines]
|
|
134
|
+
return "\n".join(lines)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def agent_system(inventory_lines, cfg, mode, run_dir_rel, student_dir_rel, notebook=False, sandbox_note="", script_name="analysis.sh"):
|
|
138
|
+
allow = bool(cfg.get("agent.allow_network"))
|
|
139
|
+
network = (
|
|
140
|
+
"The student has allowed you to use the internet to download public data and references (curl, wget, git clone, SRA tools). "
|
|
141
|
+
"Never upload or send anything: posting data, scp, git push and the like are blocked."
|
|
142
|
+
if allow
|
|
143
|
+
else "There is no internet access: curl, wget, git clone, SRA tools, NCBI E-utilities, remote BLAST and code that uses the web are "
|
|
144
|
+
"blocked. Work with the files that are on the computer. If the task needs a download, say so in your report (the student can "
|
|
145
|
+
"allow downloads with `AskTim! Agent --web ...`)."
|
|
146
|
+
)
|
|
147
|
+
folder = (
|
|
148
|
+
"Your folder is {run} (inside the student's folder {student}). Every command starts there; a `cd` lasts only until the end of "
|
|
149
|
+
"that command. Write files only inside your folder (and $TMPDIR for scratch): commands that would write anywhere else - including "
|
|
150
|
+
"index files that some programs write next to their input, such as bwa index or samtools faidx - are blocked. Read the student's "
|
|
151
|
+
"input files where they are (use paths such as ../../data/reads.fq or absolute paths); to index an input, link it into your "
|
|
152
|
+
"folder first (ln -s ../../data/ref.fa .) and index the link.{sandbox}"
|
|
153
|
+
).format(run=run_dir_rel, student=student_dir_rel, sandbox=(" " + sandbox_note) if sandbox_note else "")
|
|
154
|
+
max_steps = int(cfg.get("agent.max_steps") or 25)
|
|
155
|
+
timeout = int(cfg.get("agent.command_timeout") or 600)
|
|
156
|
+
rules = [r.format(network=network, folder=folder, timeout=timeout, max_steps=max_steps) for r in AGENT_RULES]
|
|
157
|
+
lines = [AGENT_ROLE, "", "How you work:"] + ["- " + r for r in rules]
|
|
158
|
+
if notebook:
|
|
159
|
+
lines += ["", "In the notebook:"] + ["- " + r.format(run_dir_rel=run_dir_rel) for r in NOTEBOOK_AGENT_RULES]
|
|
160
|
+
script_run = "bash " + script_name if script_name.endswith(".sh") else ("python " + script_name if script_name.endswith(".py") else "Rscript " + script_name)
|
|
161
|
+
lines += ["", "The way of working the student chose:", AGENT_MODES.get(mode, AGENT_MODES["approve"]).format(script_name=script_name, script_run=script_run)]
|
|
162
|
+
lines += course_lines(cfg)
|
|
163
|
+
lines += ["", "The computer:"] + ["- " + x if not x.startswith(" ") else x for x in inventory_lines]
|
|
164
|
+
return "\n".join(lines)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def tool_specs(notebook=False):
|
|
168
|
+
from .providers import ToolSpec
|
|
169
|
+
|
|
170
|
+
why = {"type": "string", "description": "One short sentence for the student: what this step does and why."}
|
|
171
|
+
tools = [
|
|
172
|
+
ToolSpec(
|
|
173
|
+
"run_command",
|
|
174
|
+
"Run a shell command (bash) in your folder. Returns the exit status and the output, with data lines withheld. "
|
|
175
|
+
"A few closely related commands may go in one call (joined with && or on separate lines).",
|
|
176
|
+
{"type": "object", "properties": {"command": {"type": "string", "description": "The command to run."}, "why": why}, "required": ["command", "why"]},
|
|
177
|
+
),
|
|
178
|
+
ToolSpec(
|
|
179
|
+
"write_file",
|
|
180
|
+
"Write a text file (a script, a configuration file, notes) inside your folder. Overwrites the file if it exists. "
|
|
181
|
+
"The student sees the content before it is written.",
|
|
182
|
+
{"type": "object", "properties": {"path": {"type": "string", "description": "A path inside your folder, e.g. analysis.sh"}, "content": {"type": "string", "description": "The whole content of the file."}, "why": why}, "required": ["path", "content", "why"]},
|
|
183
|
+
),
|
|
184
|
+
ToolSpec(
|
|
185
|
+
"inspect_file",
|
|
186
|
+
"Describe a file or folder without reading its data: its format, size, number of records, and for tables the number of "
|
|
187
|
+
"columns, the column names (if the first line is a header) and the kind of values in each. Use it to learn about input files.",
|
|
188
|
+
{"type": "object", "properties": {"path": {"type": "string", "description": "The file or folder (relative to your folder, or absolute)."}}, "required": ["path"]},
|
|
189
|
+
),
|
|
190
|
+
ToolSpec(
|
|
191
|
+
"open_file",
|
|
192
|
+
"Show the student a file - an HTML report (FastQC, MultiQC, fastp), an image or a PDF - " + ("under the notebook cell" if notebook else "in the computer's default program") +
|
|
193
|
+
", or open it in a program with a window that is installed here (for example IGV for a BAM or VCF file, Jalview or AliView for an "
|
|
194
|
+
"alignment, FigTree for a tree): name it in `program`; the first message says which are installed. Nothing of the file is sent to "
|
|
195
|
+
"you. The student is asked first, every time.",
|
|
196
|
+
{"type": "object", "properties": {"path": {"type": "string"},
|
|
197
|
+
"program": {"type": "string", "description": "Optional: an installed program to open the file in, e.g. igv."},
|
|
198
|
+
"why": why}, "required": ["path", "why"]},
|
|
199
|
+
),
|
|
200
|
+
]
|
|
201
|
+
if notebook:
|
|
202
|
+
tools += [
|
|
203
|
+
ToolSpec(
|
|
204
|
+
"run_python",
|
|
205
|
+
"Run Python code in the student's notebook kernel (their variables are there, and yours stay there). Returns what it printed "
|
|
206
|
+
"(data lines withheld), whether it raised an error (with the traceback), and a description - not the value - of the result "
|
|
207
|
+
"of its last line and of anything it displayed.",
|
|
208
|
+
{"type": "object", "properties": {"code": {"type": "string"}, "why": why}, "required": ["code", "why"]},
|
|
209
|
+
),
|
|
210
|
+
ToolSpec(
|
|
211
|
+
"describe_variable",
|
|
212
|
+
"Describe a variable of the student's notebook without its values: type, shape or length, column names and their types.",
|
|
213
|
+
{"type": "object", "properties": {"name": {"type": "string"}}, "required": ["name"]},
|
|
214
|
+
),
|
|
215
|
+
ToolSpec(
|
|
216
|
+
"add_markdown_cell",
|
|
217
|
+
"Add a Markdown cell (text, headings, an explanation) to the student's notebook, after the cells added so far.",
|
|
218
|
+
{"type": "object", "properties": {"text": {"type": "string"}}, "required": ["text"]},
|
|
219
|
+
),
|
|
220
|
+
ToolSpec(
|
|
221
|
+
"add_code_cell",
|
|
222
|
+
"Add a code cell to the student's notebook for them to run themselves (it is not run now).",
|
|
223
|
+
{"type": "object", "properties": {"code": {"type": "string"}, "why": why}, "required": ["code", "why"]},
|
|
224
|
+
),
|
|
225
|
+
]
|
|
226
|
+
return tools
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"""The AI services AskTim! can talk to, behind one small interface.
|
|
2
|
+
|
|
3
|
+
A conversation is kept in a neutral form (Conversation); each provider turns it into the
|
|
4
|
+
format of its service. An assistant turn keeps the provider's own content ("raw") so that it
|
|
5
|
+
can be sent back exactly as it came - Claude needs its thinking blocks back unchanged in a
|
|
6
|
+
tool-use loop, Gemini its thought signatures.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
|
|
11
|
+
from .. import config as _config
|
|
12
|
+
|
|
13
|
+
__all__ = ["Conversation", "Turn", "ToolCall", "ToolResult", "ToolSpec", "ProviderError", "make_provider"]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ProviderError(Exception):
|
|
17
|
+
"""A problem with the AI service, with a message a student can act on.
|
|
18
|
+
|
|
19
|
+
kind: auth | credit | rate | busy | notfound | bad_request | network | refusal | config | other
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
def __init__(self, message, kind="other", status=None, detail=None):
|
|
23
|
+
Exception.__init__(self, message)
|
|
24
|
+
self.kind = kind
|
|
25
|
+
self.status = status
|
|
26
|
+
self.detail = detail
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class ToolSpec(object):
|
|
30
|
+
def __init__(self, name, description, parameters):
|
|
31
|
+
self.name = name
|
|
32
|
+
self.description = description
|
|
33
|
+
self.parameters = parameters # a JSON schema: {"type": "object", "properties": {...}, "required": [...]}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class ToolCall(object):
|
|
37
|
+
def __init__(self, id, name, input):
|
|
38
|
+
self.id = id
|
|
39
|
+
self.name = name
|
|
40
|
+
self.input = input if isinstance(input, dict) else {}
|
|
41
|
+
|
|
42
|
+
def __repr__(self):
|
|
43
|
+
return "ToolCall(%r, %r, %s)" % (self.id, self.name, json.dumps(self.input)[:200])
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class ToolResult(object):
|
|
47
|
+
def __init__(self, id, name, content, is_error=False):
|
|
48
|
+
self.id = id
|
|
49
|
+
self.name = name
|
|
50
|
+
self.content = content
|
|
51
|
+
self.is_error = is_error
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class Turn(object):
|
|
55
|
+
"""One reply of the model."""
|
|
56
|
+
|
|
57
|
+
def __init__(self, text="", tool_calls=None, stop_reason="end", model="", provider="", raw=None, usage=None):
|
|
58
|
+
self.text = text
|
|
59
|
+
self.tool_calls = tool_calls or []
|
|
60
|
+
self.stop_reason = stop_reason # end | tool_use | max_tokens | refusal | other
|
|
61
|
+
self.model = model
|
|
62
|
+
self.provider = provider
|
|
63
|
+
self.raw = raw
|
|
64
|
+
self.usage = usage or {}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class Conversation(object):
|
|
68
|
+
"""The messages of a chat or of an agent's run, in a form that every provider can use."""
|
|
69
|
+
|
|
70
|
+
def __init__(self):
|
|
71
|
+
self.items = []
|
|
72
|
+
|
|
73
|
+
def user(self, text):
|
|
74
|
+
self.items.append({"kind": "user", "text": text})
|
|
75
|
+
|
|
76
|
+
def assistant(self, turn):
|
|
77
|
+
self.items.append({"kind": "assistant", "turn": turn})
|
|
78
|
+
|
|
79
|
+
def results(self, results, text=None):
|
|
80
|
+
self.items.append({"kind": "results", "results": list(results), "text": text})
|
|
81
|
+
|
|
82
|
+
def __len__(self):
|
|
83
|
+
return len(self.items)
|
|
84
|
+
|
|
85
|
+
def to_json(self):
|
|
86
|
+
"""Text-only form, for keeping a chat between commands (no thinking, no tool calls)."""
|
|
87
|
+
out = []
|
|
88
|
+
for it in self.items:
|
|
89
|
+
if it["kind"] == "user":
|
|
90
|
+
out.append({"role": "user", "text": it["text"]})
|
|
91
|
+
elif it["kind"] == "assistant" and it["turn"].text and not it["turn"].tool_calls:
|
|
92
|
+
out.append({"role": "assistant", "text": it["turn"].text})
|
|
93
|
+
return out
|
|
94
|
+
|
|
95
|
+
@classmethod
|
|
96
|
+
def from_json(cls, items):
|
|
97
|
+
conv = cls()
|
|
98
|
+
for it in items or []:
|
|
99
|
+
if it.get("role") == "user":
|
|
100
|
+
conv.user(it.get("text", ""))
|
|
101
|
+
elif it.get("role") == "assistant":
|
|
102
|
+
conv.assistant(Turn(text=it.get("text", "")))
|
|
103
|
+
return conv
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class Provider(object):
|
|
107
|
+
name = "base"
|
|
108
|
+
|
|
109
|
+
def __init__(self, key, model, cfg):
|
|
110
|
+
self.key = key
|
|
111
|
+
self.model = model
|
|
112
|
+
self.cfg = cfg
|
|
113
|
+
|
|
114
|
+
def complete(self, system, conversation, tools=None, purpose="chat", on_text=None, on_status=None):
|
|
115
|
+
raise NotImplementedError
|
|
116
|
+
|
|
117
|
+
def describe(self):
|
|
118
|
+
return "%s · %s" % (_config.PROVIDER_NAMES.get(self.name, self.name), self.model)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def error_message_from_body(body):
|
|
122
|
+
"""The service's own error message, from a JSON error body."""
|
|
123
|
+
try:
|
|
124
|
+
data = json.loads(body or "")
|
|
125
|
+
except ValueError:
|
|
126
|
+
return (body or "").strip()[:300]
|
|
127
|
+
if isinstance(data, list) and data:
|
|
128
|
+
data = data[0]
|
|
129
|
+
err = data.get("error", data) if isinstance(data, dict) else data
|
|
130
|
+
if isinstance(err, dict):
|
|
131
|
+
return str(err.get("message") or err.get("status") or err)[:500]
|
|
132
|
+
return str(err)[:500]
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def make_provider(cfg, provider=None, model=None, key=None):
|
|
136
|
+
"""The provider to use, with its key. Raises ProviderError(kind="config") if there is no key."""
|
|
137
|
+
name = _config.normalise_provider(provider) or cfg.provider
|
|
138
|
+
if key is None:
|
|
139
|
+
key, _where = _config.find_key(name)
|
|
140
|
+
model = model or cfg.model(name)
|
|
141
|
+
if name == "openai":
|
|
142
|
+
from .openai import OpenAIProvider
|
|
143
|
+
|
|
144
|
+
base = cfg.get("openai_base_url")
|
|
145
|
+
local = any(h in base for h in ("localhost", "127.0.0.1", "0.0.0.0", "[::1]"))
|
|
146
|
+
if not key and not local:
|
|
147
|
+
raise ProviderError(_no_key_message(name), kind="config")
|
|
148
|
+
if not model:
|
|
149
|
+
raise ProviderError("No model is set for the OpenAI-compatible service. Set one with: AskTim! model NAME", kind="config")
|
|
150
|
+
return OpenAIProvider(key, model, cfg)
|
|
151
|
+
if not key:
|
|
152
|
+
raise ProviderError(_no_key_message(name), kind="config")
|
|
153
|
+
if name == "gemini":
|
|
154
|
+
from .gemini import GeminiProvider
|
|
155
|
+
|
|
156
|
+
return GeminiProvider(key, model, cfg)
|
|
157
|
+
from .anthropic import AnthropicProvider
|
|
158
|
+
|
|
159
|
+
return AnthropicProvider(key, model, cfg)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _no_key_message(name):
|
|
163
|
+
label = {"claude": "Claude", "gemini": "Gemini", "openai": "OpenAI"}[name]
|
|
164
|
+
where = {
|
|
165
|
+
"claude": "console.anthropic.com (Settings → API keys)",
|
|
166
|
+
"gemini": "aistudio.google.com/apikey",
|
|
167
|
+
"openai": "your service's website",
|
|
168
|
+
}[name]
|
|
169
|
+
return (
|
|
170
|
+
"AskTim! has no API key for %s yet. Get one from %s, then run:\n\n AskTim! %s\n\n"
|
|
171
|
+
"and paste the key when you are asked (it is stored on this computer, readable by you only)."
|
|
172
|
+
% (label, where, label)
|
|
173
|
+
)
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
"""Claude, through Anthropic's Messages API (streamed).
|
|
2
|
+
|
|
3
|
+
Notes on the API that matter here:
|
|
4
|
+
- Current Claude models think before they answer (adaptive thinking, on by default; the
|
|
5
|
+
thinking text is omitted by default). In a tool-use loop the thinking blocks of an
|
|
6
|
+
assistant turn must be sent back unchanged, so a turn keeps its content blocks as received.
|
|
7
|
+
- The system prompt and the tools must stay the same during an agent's run (a change would
|
|
8
|
+
break the check the API makes on earlier thinking blocks).
|
|
9
|
+
- output_config.effort sets how much work the model does: "low" for chat, "medium" for the agent.
|
|
10
|
+
- A top-level cache_control turns on automatic prompt caching (cheaper repeated requests).
|
|
11
|
+
Optional parameters that a model or a proxy does not accept are dropped and the request is
|
|
12
|
+
sent again.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
import re
|
|
17
|
+
|
|
18
|
+
from .. import net
|
|
19
|
+
from . import Provider, ProviderError, ToolCall, Turn, error_message_from_body
|
|
20
|
+
|
|
21
|
+
# models that accept output_config.effort (Claude 4.5 Opus and later generations)
|
|
22
|
+
_EFFORT_MODELS = re.compile(r"claude-(fable|mythos|opus|sonnet|haiku)-(5|[6-9])|claude-opus-4-[5-9]|claude-sonnet-4-6|claude-mythos")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class AnthropicProvider(Provider):
|
|
26
|
+
name = "claude"
|
|
27
|
+
|
|
28
|
+
def __init__(self, key, model, cfg):
|
|
29
|
+
Provider.__init__(self, key, model, cfg)
|
|
30
|
+
self.base = (cfg.get("anthropic_base_url") or "https://api.anthropic.com").rstrip("/")
|
|
31
|
+
self.version = cfg.get("anthropic_version") or "2026-10-21"
|
|
32
|
+
self._drop = set() # optional parameters this service has refused
|
|
33
|
+
|
|
34
|
+
# -- the request ------------------------------------------------------------------------
|
|
35
|
+
|
|
36
|
+
def _messages(self, conversation):
|
|
37
|
+
msgs = []
|
|
38
|
+
|
|
39
|
+
def add(role, blocks):
|
|
40
|
+
if msgs and msgs[-1]["role"] == role:
|
|
41
|
+
msgs[-1]["content"].extend(blocks)
|
|
42
|
+
else:
|
|
43
|
+
msgs.append({"role": role, "content": list(blocks)})
|
|
44
|
+
|
|
45
|
+
for it in conversation.items:
|
|
46
|
+
if it["kind"] == "user":
|
|
47
|
+
add("user", [{"type": "text", "text": it["text"] or "(empty)"}])
|
|
48
|
+
elif it["kind"] == "assistant":
|
|
49
|
+
t = it["turn"]
|
|
50
|
+
if t.provider == self.name and isinstance(t.raw, list) and t.raw:
|
|
51
|
+
add("assistant", t.raw)
|
|
52
|
+
else:
|
|
53
|
+
blocks = []
|
|
54
|
+
if t.text:
|
|
55
|
+
blocks.append({"type": "text", "text": t.text})
|
|
56
|
+
for c in t.tool_calls:
|
|
57
|
+
blocks.append({"type": "tool_use", "id": c.id, "name": c.name, "input": c.input})
|
|
58
|
+
add("assistant", blocks or [{"type": "text", "text": "(no reply)"}])
|
|
59
|
+
elif it["kind"] == "results":
|
|
60
|
+
blocks = [
|
|
61
|
+
{"type": "tool_result", "tool_use_id": r.id, "content": r.content or "(no output)", "is_error": bool(r.is_error)}
|
|
62
|
+
for r in it["results"]
|
|
63
|
+
]
|
|
64
|
+
if it.get("text"):
|
|
65
|
+
blocks.append({"type": "text", "text": it["text"]})
|
|
66
|
+
add("user", blocks)
|
|
67
|
+
return msgs
|
|
68
|
+
|
|
69
|
+
def _body(self, system, conversation, tools, purpose):
|
|
70
|
+
max_tokens = int((self.cfg.get("max_tokens") or {}).get(purpose) or 16000)
|
|
71
|
+
body = {
|
|
72
|
+
"model": self.model,
|
|
73
|
+
"max_tokens": max_tokens,
|
|
74
|
+
"system": [{"type": "text", "text": system}],
|
|
75
|
+
"messages": self._messages(conversation),
|
|
76
|
+
"stream": True,
|
|
77
|
+
}
|
|
78
|
+
if tools:
|
|
79
|
+
body["tools"] = [{"name": t.name, "description": t.description, "input_schema": t.parameters} for t in tools]
|
|
80
|
+
effort = (self.cfg.get("effort") or {}).get(purpose)
|
|
81
|
+
if effort and "output_config" not in self._drop and _EFFORT_MODELS.search(self.model):
|
|
82
|
+
body["output_config"] = {"effort": effort}
|
|
83
|
+
if "cache_control" not in self._drop:
|
|
84
|
+
body["cache_control"] = {"type": "ephemeral"}
|
|
85
|
+
return body
|
|
86
|
+
|
|
87
|
+
def _headers(self):
|
|
88
|
+
return {"x-api-key": self.key, "anthropic-version": self.version}
|
|
89
|
+
|
|
90
|
+
# -- one call ---------------------------------------------------------------------------
|
|
91
|
+
|
|
92
|
+
def complete(self, system, conversation, tools=None, purpose="chat", on_text=None, on_status=None):
|
|
93
|
+
emitted = [False]
|
|
94
|
+
|
|
95
|
+
def emit(t):
|
|
96
|
+
emitted[0] = True
|
|
97
|
+
if on_text:
|
|
98
|
+
on_text(t)
|
|
99
|
+
|
|
100
|
+
def attempt():
|
|
101
|
+
body = self._body(system, conversation, tools, purpose)
|
|
102
|
+
resp = net.open_request(self.base + "/v1/messages", self._headers(), body, timeout=120)
|
|
103
|
+
return self._read_stream(resp, emit)
|
|
104
|
+
|
|
105
|
+
for _round in range(4):
|
|
106
|
+
try:
|
|
107
|
+
return net.with_retries(attempt, attempts=3, on_wait=lambda e, w: on_status and on_status(_wait_note(e, w, emitted[0])))
|
|
108
|
+
except net.HTTPError as e:
|
|
109
|
+
fixed = self._fix_request(e)
|
|
110
|
+
if fixed and not emitted[0]:
|
|
111
|
+
continue
|
|
112
|
+
raise self._error(e)
|
|
113
|
+
raise ProviderError("The request to Claude could not be made to work.", kind="bad_request")
|
|
114
|
+
|
|
115
|
+
def _fix_request(self, e):
|
|
116
|
+
"""For a 400 about an optional parameter: leave it out next time (True if changed)."""
|
|
117
|
+
if e.status != 400:
|
|
118
|
+
return False
|
|
119
|
+
msg = error_message_from_body(e.body).lower()
|
|
120
|
+
if "anthropic-version" in msg and self.version != "2023-06-01":
|
|
121
|
+
self.version = "2023-06-01"
|
|
122
|
+
return True
|
|
123
|
+
for param, words in (("output_config", ("output_config", "effort")), ("cache_control", ("cache_control",))):
|
|
124
|
+
if param not in self._drop and any(w in msg for w in words):
|
|
125
|
+
self._drop.add(param)
|
|
126
|
+
return True
|
|
127
|
+
return False
|
|
128
|
+
|
|
129
|
+
def _read_stream(self, resp, emit):
|
|
130
|
+
blocks = {}
|
|
131
|
+
partial = {}
|
|
132
|
+
stop_reason, usage, model = None, {}, self.model
|
|
133
|
+
for event, data in net.iter_sse(resp):
|
|
134
|
+
try:
|
|
135
|
+
ev = json.loads(data)
|
|
136
|
+
except ValueError:
|
|
137
|
+
continue
|
|
138
|
+
typ = ev.get("type") or event
|
|
139
|
+
if typ == "message_start":
|
|
140
|
+
m = ev.get("message") or {}
|
|
141
|
+
model = m.get("model") or model
|
|
142
|
+
usage.update(m.get("usage") or {})
|
|
143
|
+
elif typ == "content_block_start":
|
|
144
|
+
i = ev.get("index", len(blocks))
|
|
145
|
+
b = dict(ev.get("content_block") or {})
|
|
146
|
+
if b.get("type") == "tool_use":
|
|
147
|
+
b["input"] = {}
|
|
148
|
+
partial[i] = ""
|
|
149
|
+
blocks[i] = b
|
|
150
|
+
elif typ == "content_block_delta":
|
|
151
|
+
i = ev.get("index", 0)
|
|
152
|
+
d = ev.get("delta") or {}
|
|
153
|
+
b = blocks.setdefault(i, {"type": "text", "text": ""})
|
|
154
|
+
dt = d.get("type")
|
|
155
|
+
if dt == "text_delta":
|
|
156
|
+
b["text"] = b.get("text", "") + d.get("text", "")
|
|
157
|
+
emit(d.get("text", ""))
|
|
158
|
+
elif dt == "input_json_delta":
|
|
159
|
+
partial[i] = partial.get(i, "") + d.get("partial_json", "")
|
|
160
|
+
elif dt == "thinking_delta":
|
|
161
|
+
b["thinking"] = b.get("thinking", "") + d.get("thinking", "")
|
|
162
|
+
elif dt == "signature_delta":
|
|
163
|
+
b["signature"] = d.get("signature", "")
|
|
164
|
+
elif dt == "citations_delta":
|
|
165
|
+
b.setdefault("citations", []).append(d.get("citation"))
|
|
166
|
+
elif typ == "content_block_stop":
|
|
167
|
+
i = ev.get("index", 0)
|
|
168
|
+
if i in partial:
|
|
169
|
+
raw = partial.pop(i).strip()
|
|
170
|
+
try:
|
|
171
|
+
blocks[i]["input"] = json.loads(raw) if raw else {}
|
|
172
|
+
except ValueError:
|
|
173
|
+
blocks[i]["input"] = {"_incomplete": raw[:2000]}
|
|
174
|
+
elif typ == "message_delta":
|
|
175
|
+
d = ev.get("delta") or {}
|
|
176
|
+
stop_reason = d.get("stop_reason") or stop_reason
|
|
177
|
+
usage.update(ev.get("usage") or {})
|
|
178
|
+
elif typ == "error":
|
|
179
|
+
err = ev.get("error") or {}
|
|
180
|
+
etype = err.get("type", "")
|
|
181
|
+
status = 529 if etype == "overloaded_error" else 429 if etype == "rate_limit_error" else 500 if etype == "api_error" else 400
|
|
182
|
+
raise net.HTTPError(err.get("message") or etype or "error", status=status, body=json.dumps(ev))
|
|
183
|
+
# ping and new event types are ignored
|
|
184
|
+
# a tool call whose input never finished (the reply was cut off)
|
|
185
|
+
for i, raw in partial.items():
|
|
186
|
+
blocks[i]["input"] = {"_incomplete": raw[:2000]}
|
|
187
|
+
content = [blocks[i] for i in sorted(blocks)]
|
|
188
|
+
text = "".join(b.get("text", "") for b in content if b.get("type") == "text")
|
|
189
|
+
calls = [ToolCall(b.get("id"), b.get("name"), b.get("input")) for b in content if b.get("type") == "tool_use"]
|
|
190
|
+
sr = {"end_turn": "end", "tool_use": "tool_use", "max_tokens": "max_tokens", "stop_sequence": "end", "refusal": "refusal"}.get(stop_reason or "end_turn", stop_reason or "end")
|
|
191
|
+
if stop_reason == "model_context_window_exceeded":
|
|
192
|
+
sr = "max_tokens"
|
|
193
|
+
if stop_reason is None and not content:
|
|
194
|
+
raise net.HTTPError("The answer from Claude was empty or broke off.", network=True)
|
|
195
|
+
return Turn(text=text, tool_calls=calls, stop_reason=sr, model=model, provider=self.name, raw=content, usage=usage)
|
|
196
|
+
|
|
197
|
+
# -- errors -----------------------------------------------------------------------------
|
|
198
|
+
|
|
199
|
+
def _error(self, e):
|
|
200
|
+
msg = error_message_from_body(e.body) if e.body else str(e)
|
|
201
|
+
if e.network:
|
|
202
|
+
return ProviderError("Could not reach Claude: %s Check your internet connection and try again." % e, kind="network")
|
|
203
|
+
if e.status == 401:
|
|
204
|
+
return ProviderError("Your Claude API key was not accepted (%s). Check it, or store a new one with: AskTim! Claude" % msg, kind="auth", status=401)
|
|
205
|
+
if e.status == 403:
|
|
206
|
+
return ProviderError("Your key may not use this model or service (%s)." % msg, kind="auth", status=403)
|
|
207
|
+
if e.status == 404:
|
|
208
|
+
return ProviderError(
|
|
209
|
+
"The model %r was not found (%s). Choose a current one, for example: AskTim! model claude-sonnet-5-5" % (self.model, msg),
|
|
210
|
+
kind="notfound",
|
|
211
|
+
status=404,
|
|
212
|
+
)
|
|
213
|
+
if e.status == 400 and "credit" in msg.lower():
|
|
214
|
+
return ProviderError("Your Anthropic account has no credit left (%s). Add credit at console.anthropic.com, or use another key." % msg, kind="credit", status=400)
|
|
215
|
+
if e.status == 429:
|
|
216
|
+
return ProviderError("Too many requests for your key just now (%s). Wait a minute and try again." % msg, kind="rate", status=429)
|
|
217
|
+
if e.status in (500, 502, 503, 504, 529):
|
|
218
|
+
return ProviderError("Claude is busy or having trouble (HTTP %s: %s). This is not your fault: try again in a minute." % (e.status, msg), kind="busy", status=e.status)
|
|
219
|
+
if e.status == 413:
|
|
220
|
+
return ProviderError("The request was too large for the service (%s)." % msg, kind="bad_request", status=413)
|
|
221
|
+
return ProviderError("Claude refused the request (HTTP %s: %s)." % (e.status, msg), kind="bad_request", status=e.status, detail=e.body)
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _wait_note(e, wait, emitted):
|
|
225
|
+
what = "Too many requests" if e.status == 429 else "The service is busy" if e.status else "No answer from the service"
|
|
226
|
+
again = " – the answer broke off" if emitted else ""
|
|
227
|
+
return "%s%s; waiting %d s and asking again…" % (what, again, round(wait))
|