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/logbook.py ADDED
@@ -0,0 +1,159 @@
1
+ """A record, on the student's own computer, of how they used AI.
2
+
3
+ Each question and each agent run adds a line to ~/.local/state/asktim/log.jsonl: when, which
4
+ mode, which model, the question or task, what was sent with it (as a summary), and for agent
5
+ runs the folder with the full record. Nothing here is sent anywhere.
6
+
7
+ `AskTim! log` shows the recent entries. `AskTim! statement` drafts a statement on the use of
8
+ AI for coursework from them - the practicals ask students to write one.
9
+
10
+ The chat conversation of the command line is also kept here (cache/chat.json), so that a
11
+ follow-up question can refer to the answer before; it is forgotten after an hour without
12
+ questions, or with `AskTim! new`.
13
+ """
14
+
15
+ import json
16
+ import os
17
+ import time
18
+
19
+ from . import paths
20
+
21
+
22
+ def log_file():
23
+ return os.path.join(paths.state_dir(), "log.jsonl")
24
+
25
+
26
+ _log_file = log_file
27
+
28
+
29
+ def add(entry, cfg=None):
30
+ if cfg is not None and not cfg.get("log", True):
31
+ return
32
+ entry = dict(entry)
33
+ entry.setdefault("time", time.strftime("%Y-%m-%dT%H:%M:%S"))
34
+ try:
35
+ paths.ensure(paths.state_dir(), private=True)
36
+ with open(_log_file(), "a", encoding="utf-8") as f:
37
+ f.write(json.dumps(entry, ensure_ascii=False) + "\n")
38
+ except OSError:
39
+ pass
40
+
41
+
42
+ def entries(since=None, limit=None):
43
+ out = []
44
+ try:
45
+ with open(_log_file(), encoding="utf-8") as f:
46
+ for ln in f:
47
+ try:
48
+ e = json.loads(ln)
49
+ except ValueError:
50
+ continue
51
+ if since and e.get("time", "") < since:
52
+ continue
53
+ out.append(e)
54
+ except OSError:
55
+ return []
56
+ return out[-limit:] if limit else out
57
+
58
+
59
+ def statement(since=None, folder=None):
60
+ """A draft statement on the use of AI, in Markdown."""
61
+ es = entries(since=since)
62
+ if folder:
63
+ f = os.path.realpath(folder)
64
+ es = [e for e in es if (e.get("cwd") or "").startswith(paths.pretty(f)) or (e.get("cwd") or "") == paths.pretty(f)]
65
+ if not es:
66
+ return None
67
+ models = sorted(set(e.get("model", "") for e in es if e.get("model")))
68
+ chats = [e for e in es if e.get("mode") == "chat"]
69
+ runs = [e for e in es if e.get("mode", "").startswith("agent")]
70
+ first, last = es[0]["time"][:10], es[-1]["time"][:10]
71
+ lines = [
72
+ "## Statement on the use of AI",
73
+ "",
74
+ "Between %s and %s I used AskTim!, an AI assistant for bioinformatics (model%s: %s), in this work." % (first, last, "s" if len(models) != 1 else "", ", ".join(models) or "unknown"),
75
+ "",
76
+ "AskTim! did not send the contents of my data files to the AI: it sent my questions, the names of the programs installed "
77
+ "on the computer, my recent commands (with secrets removed), descriptions of files (format, size, columns) and, in "
78
+ "notebooks, the code of the cells I ran. In agent mode, the output of the commands it ran was sent with lines that "
79
+ "looked like data withheld.",
80
+ "",
81
+ ]
82
+ if chats:
83
+ lines += ["I asked %d question%s, among them:" % (len(chats), "" if len(chats) == 1 else "s"), ""]
84
+ for e in chats[-12:]:
85
+ lines.append("- %s – “%s”" % (e["time"][:10], (e.get("question") or "")[:160].replace("\n", " ")))
86
+ lines.append("")
87
+ if runs:
88
+ lines += ["AskTim! Agent carried out %d task%s; the record of each run (RUN.md) and a script to repeat it (rerun.sh) are in its folder:" % (len(runs), "" if len(runs) == 1 else "s"), ""]
89
+ for e in runs[-12:]:
90
+ lines.append("- %s – %s (%s): “%s” – %s" % (e["time"][:10], e.get("mode", "agent"), e.get("outcome", ""), (e.get("question") or "")[:140].replace("\n", " "), e.get("folder", "")))
91
+ lines.append("")
92
+ lines += [
93
+ "[Say here which suggestions you used, what you changed, and how you checked the results. The analysis and its conclusions are mine.]",
94
+ ]
95
+ return "\n".join(lines)
96
+
97
+
98
+ # -- the chat conversation of the command line ---------------------------------------------------
99
+
100
+
101
+ def _chat_file():
102
+ return os.path.join(paths.cache_dir(), "chat.json")
103
+
104
+
105
+ def load_chat(max_minutes=60):
106
+ try:
107
+ with open(_chat_file(), encoding="utf-8") as f:
108
+ data = json.load(f)
109
+ except (OSError, ValueError):
110
+ return []
111
+ if time.time() - data.get("time", 0) > max_minutes * 60:
112
+ return []
113
+ if data.get("cwd") and data["cwd"] != paths.pretty(os.getcwd()) and time.time() - data.get("time", 0) > 15 * 60:
114
+ return []
115
+ return data.get("items", [])
116
+
117
+
118
+ def save_chat(items):
119
+ try:
120
+ paths.ensure(paths.cache_dir(), private=True)
121
+ tmp = _chat_file() + ".tmp"
122
+ with open(tmp, "w", encoding="utf-8") as f:
123
+ json.dump({"time": time.time(), "cwd": paths.pretty(os.getcwd()), "items": items[-20:]}, f, ensure_ascii=False)
124
+ os.replace(tmp, _chat_file())
125
+ except OSError:
126
+ pass
127
+
128
+
129
+ def clear_chat():
130
+ try:
131
+ os.remove(_chat_file())
132
+ return True
133
+ except OSError:
134
+ return False
135
+
136
+
137
+ def save_suggested(blocks):
138
+ """The shell commands of the last answer, one per line, for Alt+A in the shell."""
139
+ cmds = []
140
+ for lang, code in blocks:
141
+ if lang in ("bash", "sh", "shell", "console", "zsh", ""):
142
+ for ln in code.splitlines():
143
+ ln = ln.rstrip()
144
+ if ln.startswith("$ "):
145
+ ln = ln[2:]
146
+ if ln and not ln.lstrip().startswith("#"):
147
+ cmds.append(ln)
148
+ try:
149
+ paths.ensure(paths.cache_dir(), private=True)
150
+ p = os.path.join(paths.cache_dir(), "suggested.txt")
151
+ with open(p, "w", encoding="utf-8") as f:
152
+ f.write("\n".join(cmds) + ("\n" if cmds else ""))
153
+ try:
154
+ os.remove(p + ".next")
155
+ except OSError:
156
+ pass
157
+ except OSError:
158
+ pass
159
+ return cmds
asktim/net.py ADDED
@@ -0,0 +1,151 @@
1
+ """A small HTTP client on the standard library: JSON requests and server-sent events (SSE).
2
+
3
+ Proxies are taken from the environment (HTTPS_PROXY ...), as urllib does. Certificates come
4
+ from the system; if Python has none (a common problem with python.org installers on macOS)
5
+ and the certifi package is installed, its certificates are used.
6
+ """
7
+
8
+ import json
9
+ import socket
10
+ import ssl
11
+ import time
12
+ import urllib.error
13
+ import urllib.request
14
+
15
+ from . import __version__
16
+
17
+ USER_AGENT = "AskTim/%s (+https://github.com/comparativechrono/AskTim)" % __version__
18
+
19
+ _ctx = None
20
+
21
+
22
+ def _ssl_context():
23
+ global _ctx
24
+ if _ctx is None:
25
+ ctx = ssl.create_default_context()
26
+ try:
27
+ if not ctx.get_ca_certs():
28
+ import certifi # type: ignore
29
+
30
+ ctx = ssl.create_default_context(cafile=certifi.where())
31
+ except Exception:
32
+ pass
33
+ _ctx = ctx
34
+ return _ctx
35
+
36
+
37
+ class HTTPError(Exception):
38
+ """An answer from the service that is not a success, or no answer at all."""
39
+
40
+ def __init__(self, message, status=None, body=None, retry_after=None, network=False):
41
+ Exception.__init__(self, message)
42
+ self.status = status
43
+ self.body = body
44
+ self.retry_after = retry_after
45
+ self.network = network
46
+
47
+ @property
48
+ def retryable(self):
49
+ return self.network or self.status in (408, 409, 425, 429, 500, 502, 503, 504, 529)
50
+
51
+
52
+ def _retry_after(headers):
53
+ try:
54
+ v = headers.get("retry-after")
55
+ if v is None:
56
+ return None
57
+ return max(0.0, float(v))
58
+ except Exception:
59
+ return None
60
+
61
+
62
+ def open_request(url, headers, body, timeout=90.0):
63
+ data = json.dumps(body).encode("utf-8") if body is not None else None
64
+ h = {"content-type": "application/json", "user-agent": USER_AGENT}
65
+ h.update(headers or {})
66
+ req = urllib.request.Request(url, data=data, headers=h, method="POST" if data is not None else "GET")
67
+ try:
68
+ return urllib.request.urlopen(req, timeout=timeout, context=_ssl_context())
69
+ except urllib.error.HTTPError as e:
70
+ raw = b""
71
+ try:
72
+ raw = e.read()
73
+ except Exception:
74
+ pass
75
+ text = raw.decode("utf-8", "replace")
76
+ raise HTTPError("HTTP %s" % e.code, status=e.code, body=text, retry_after=_retry_after(e.headers or {}))
77
+ except urllib.error.URLError as e:
78
+ reason = getattr(e, "reason", e)
79
+ if isinstance(reason, ssl.SSLError) or "CERTIFICATE" in str(reason).upper():
80
+ raise HTTPError(
81
+ "Could not check the service's certificate (%s). On a Mac with Python from python.org, run "
82
+ "'Install Certificates.command' in the Python folder, or `pip install certifi`." % reason,
83
+ network=False,
84
+ )
85
+ raise HTTPError("Could not reach %s (%s)." % (url.split("/")[2], reason), network=True)
86
+ except (socket.timeout, TimeoutError):
87
+ raise HTTPError("No answer from %s within %d seconds." % (url.split("/")[2], timeout), network=True)
88
+ except (ConnectionError, OSError) as e:
89
+ raise HTTPError("The connection to %s failed (%s)." % (url.split("/")[2], e), network=True)
90
+
91
+
92
+ def post_json(url, headers, body, timeout=90.0):
93
+ resp = open_request(url, headers, body, timeout)
94
+ try:
95
+ raw = resp.read()
96
+ finally:
97
+ resp.close()
98
+ try:
99
+ return json.loads(raw.decode("utf-8"))
100
+ except ValueError:
101
+ raise HTTPError("The service sent something that is not JSON.", status=getattr(resp, "status", None), body=raw[:2000])
102
+
103
+
104
+ def iter_sse(resp):
105
+ """(event, data) pairs from a server-sent event stream. data is the joined data: lines."""
106
+ event, data = None, []
107
+ try:
108
+ for raw in resp:
109
+ line = raw.decode("utf-8", "replace").rstrip("\r\n")
110
+ if not line:
111
+ if data:
112
+ yield event, "\n".join(data)
113
+ event, data = None, []
114
+ continue
115
+ if line.startswith(":"):
116
+ continue
117
+ field, _, value = line.partition(":")
118
+ if value.startswith(" "):
119
+ value = value[1:]
120
+ if field == "event":
121
+ event = value
122
+ elif field == "data":
123
+ data.append(value)
124
+ if data:
125
+ yield event, "\n".join(data)
126
+ except (socket.timeout, TimeoutError):
127
+ raise HTTPError("The answer stopped arriving (no data for a while).", network=True)
128
+ except (ConnectionError, OSError) as e:
129
+ raise HTTPError("The connection broke during the answer (%s)." % e, network=True)
130
+ finally:
131
+ try:
132
+ resp.close()
133
+ except Exception:
134
+ pass
135
+
136
+
137
+ def with_retries(fn, attempts=3, on_wait=None, max_wait=60.0):
138
+ """Call fn(); when the service is busy or unreachable, wait and try again (up to `attempts` times)."""
139
+ delay = 4.0
140
+ for i in range(attempts + 1):
141
+ try:
142
+ return fn()
143
+ except HTTPError as e:
144
+ if not e.retryable or i >= attempts:
145
+ raise
146
+ wait = e.retry_after if e.retry_after is not None else delay
147
+ wait = min(max_wait, max(1.0, wait))
148
+ if on_wait:
149
+ on_wait(e, wait)
150
+ time.sleep(wait)
151
+ delay *= 2