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.
@@ -0,0 +1,215 @@
1
+ """Google Gemini, through the Gemini API's streamGenerateContent (server-sent events).
2
+
3
+ Gemini's free tier allows few requests per model per minute and per day, and its newest
4
+ models are sometimes busy. As in the practicals, when the chosen model is busy, over a limit
5
+ or not found, the next model of `gemini_fallback_models` is asked, and the answer says which
6
+ model replied. The parts of each reply are kept as they came, so that thought signatures go
7
+ back to the service unchanged in a function-calling loop.
8
+ """
9
+
10
+ import json
11
+ import time
12
+
13
+ from .. import net
14
+ from . import Provider, ProviderError, ToolCall, Turn, error_message_from_body
15
+
16
+ _REST = {} # model -> (until timestamp, why), for this process
17
+
18
+
19
+ def _gemini_schema(schema):
20
+ """Gemini's schemas are OpenAPI-style: upper-case type names, no additionalProperties."""
21
+ if isinstance(schema, dict):
22
+ out = {}
23
+ for k, v in schema.items():
24
+ if k in ("additionalProperties", "$schema", "default"):
25
+ continue
26
+ if k == "type" and isinstance(v, str):
27
+ out[k] = v.upper()
28
+ else:
29
+ out[k] = _gemini_schema(v)
30
+ return out
31
+ if isinstance(schema, list):
32
+ return [_gemini_schema(x) for x in schema]
33
+ return schema
34
+
35
+
36
+ class GeminiProvider(Provider):
37
+ name = "gemini"
38
+
39
+ def __init__(self, key, model, cfg):
40
+ Provider.__init__(self, key, model, cfg)
41
+ self.base = (cfg.get("gemini_base_url") or "https://generativelanguage.googleapis.com").rstrip("/")
42
+ self.fallbacks = [m for m in (cfg.get("gemini_fallback_models") or []) if m and m != model]
43
+
44
+ def _contents(self, conversation):
45
+ contents = []
46
+
47
+ def add(role, parts):
48
+ if contents and contents[-1]["role"] == role:
49
+ contents[-1]["parts"].extend(parts)
50
+ else:
51
+ contents.append({"role": role, "parts": list(parts)})
52
+
53
+ for it in conversation.items:
54
+ if it["kind"] == "user":
55
+ add("user", [{"text": it["text"] or "(empty)"}])
56
+ elif it["kind"] == "assistant":
57
+ t = it["turn"]
58
+ if t.provider == self.name and isinstance(t.raw, list) and t.raw:
59
+ add("model", t.raw)
60
+ else:
61
+ parts = [{"text": t.text}] if t.text else []
62
+ for c in t.tool_calls:
63
+ parts.append({"functionCall": {"name": c.name, "args": c.input}})
64
+ add("model", parts or [{"text": "(no reply)"}])
65
+ elif it["kind"] == "results":
66
+ parts = []
67
+ for r in it["results"]:
68
+ fr = {"name": r.name, "response": {"error" if r.is_error else "result": r.content or "(no output)"}}
69
+ if r.id and not str(r.id).startswith("gemini-"):
70
+ fr["id"] = r.id
71
+ parts.append({"functionResponse": fr})
72
+ if it.get("text"):
73
+ parts.append({"text": it["text"]})
74
+ add("user", parts)
75
+ return contents
76
+
77
+ def _body(self, system, conversation, tools, purpose):
78
+ body = {
79
+ "systemInstruction": {"parts": [{"text": system}]},
80
+ "contents": self._contents(conversation),
81
+ "generationConfig": {"maxOutputTokens": int((self.cfg.get("max_tokens") or {}).get(purpose) or 16000)},
82
+ }
83
+ if tools:
84
+ body["tools"] = [{"functionDeclarations": [{"name": t.name, "description": t.description, "parameters": _gemini_schema(t.parameters)} for t in tools]}]
85
+ return body
86
+
87
+ def complete(self, system, conversation, tools=None, purpose="chat", on_text=None, on_status=None):
88
+ body = self._body(system, conversation, tools, purpose)
89
+ models = [self.model] + self.fallbacks
90
+ now = time.time()
91
+ ready = [m for m in models if _REST.get(m, (0, ""))[0] <= now]
92
+ if not ready: # every model is resting: try the one that rests the shortest time
93
+ ready = sorted(models, key=lambda m: _REST.get(m, (0, ""))[0])[:1]
94
+ told = []
95
+ last = None
96
+ for i, model in enumerate(ready):
97
+ try:
98
+ turn = self._one(model, body, on_text)
99
+ if told:
100
+ turn.model = "%s (%s)" % (model, "; ".join(told))
101
+ return turn
102
+ except net.HTTPError as e:
103
+ last = e
104
+ why = self._rest(model, e)
105
+ if why is None: # an error that another model would not avoid
106
+ raise self._error(e, model)
107
+ told.append("%s %s" % (model, why))
108
+ if on_status and i + 1 < len(ready):
109
+ on_status("%s %s – asking %s…" % (model, why, ready[i + 1]))
110
+ # every model failed: wait once if a limit per minute or a busy server is the cause
111
+ if last is not None and last.retryable and (last.status in (429, 500, 502, 503, 504) or last.network):
112
+ wait = min(60.0, last.retry_after or 20.0)
113
+ if on_status:
114
+ on_status("No Gemini model could answer just now; waiting %d s and asking again…" % wait)
115
+ time.sleep(wait)
116
+ try:
117
+ return self._one(ready[0], body, on_text)
118
+ except net.HTTPError as e:
119
+ raise self._error(e, ready[0], told)
120
+ raise self._error(last, ready[-1], told)
121
+
122
+ def _rest(self, model, e):
123
+ """Note why a model could not answer, and for how long to leave it alone; None: do not try others."""
124
+ msg = error_message_from_body(e.body).lower() if e.body else ""
125
+ now = time.time()
126
+ if e.network:
127
+ _REST[model] = (now + 60, "gave no answer")
128
+ return "gave no answer"
129
+ if e.status == 404:
130
+ _REST[model] = (now + 10 ** 9, "was not found")
131
+ return "was not found"
132
+ if e.status == 429:
133
+ daily = "perday" in msg.replace(" ", "").replace("_", "") or "per day" in msg or "daily" in msg
134
+ if daily:
135
+ _REST[model] = (now + 6 * 3600, "is over its limit for today")
136
+ return "is over its limit for today"
137
+ _REST[model] = (now + (e.retry_after or 60), "is over its limit per minute")
138
+ return "is over its limit per minute"
139
+ if e.status in (500, 502, 503, 504):
140
+ _REST[model] = (now + 120, "is busy")
141
+ return "is busy"
142
+ return None
143
+
144
+ def _one(self, model, body, on_text):
145
+ url = "%s/v1beta/models/%s:streamGenerateContent?alt=sse" % (self.base, model)
146
+ resp = net.open_request(url, {"x-goog-api-key": self.key}, body, timeout=120)
147
+ parts, finish, usage, blocked = [], None, {}, None
148
+ for _event, data in net.iter_sse(resp):
149
+ try:
150
+ ev = json.loads(data)
151
+ except ValueError:
152
+ continue
153
+ if ev.get("error"):
154
+ err = ev["error"]
155
+ raise net.HTTPError(err.get("message", "error"), status=err.get("code") or 500, body=data)
156
+ if (ev.get("promptFeedback") or {}).get("blockReason"):
157
+ blocked = ev["promptFeedback"]["blockReason"]
158
+ usage = ev.get("usageMetadata") or usage
159
+ for cand in ev.get("candidates") or []:
160
+ for p in (cand.get("content") or {}).get("parts") or []:
161
+ parts.append(p)
162
+ if "text" in p and not p.get("thought") and on_text and p["text"]:
163
+ on_text(p["text"])
164
+ if cand.get("finishReason"):
165
+ finish = cand["finishReason"]
166
+ raw = _merge_parts(parts)
167
+ text = "".join(p.get("text", "") for p in raw if "text" in p and not p.get("thought"))
168
+ calls = []
169
+ n = 0
170
+ for p in raw:
171
+ fc = p.get("functionCall")
172
+ if fc:
173
+ n += 1
174
+ calls.append(ToolCall(fc.get("id") or "gemini-%d" % n, fc.get("name"), fc.get("args") or {}))
175
+ if blocked and not raw:
176
+ return Turn(text="(Gemini did not answer: %s)" % blocked, stop_reason="refusal", model=model, provider=self.name, raw=[{"text": ""}])
177
+ sr = "tool_use" if calls else {"STOP": "end", "MAX_TOKENS": "max_tokens", "SAFETY": "refusal", "RECITATION": "refusal", "MALFORMED_FUNCTION_CALL": "malformed"}.get(finish or "STOP", "end")
178
+ if not raw:
179
+ raw = [{"text": ""}]
180
+ return Turn(text=text, tool_calls=calls, stop_reason=sr, model=model, provider=self.name, raw=raw, usage=usage)
181
+
182
+ def _error(self, e, model, told=None):
183
+ msg = error_message_from_body(e.body) if e is not None and e.body else str(e)
184
+ also = (" (%s)" % "; ".join(told)) if told else ""
185
+ if e is None:
186
+ return ProviderError("No Gemini model could answer%s." % also, kind="busy")
187
+ if e.network:
188
+ return ProviderError("Could not reach the Gemini API: %s%s" % (e, also), kind="network")
189
+ if e.status in (400, 401, 403) and ("api key" in msg.lower() or "api_key" in msg.lower() or e.status in (401, 403)):
190
+ return ProviderError("Your Gemini key was not accepted (%s). Store a new one with: AskTim! Gemini" % msg, kind="auth", status=e.status)
191
+ if e.status == 404:
192
+ return ProviderError("The Gemini model %r was not found%s. Choose a current one with: AskTim! model NAME" % (model, also), kind="notfound", status=404)
193
+ if e.status == 429:
194
+ return ProviderError(
195
+ "Gemini says there are too many requests%s: %s The free tier allows only a few requests per minute and per day; wait, or use another key." % (also, msg),
196
+ kind="rate",
197
+ status=429,
198
+ )
199
+ if e.status and e.status >= 500:
200
+ return ProviderError("Gemini is busy (HTTP %s)%s. That is on Google's side: try again in a minute." % (e.status, also), kind="busy", status=e.status)
201
+ return ProviderError("Gemini refused the request (HTTP %s: %s)." % (e.status, msg), kind="bad_request", status=e.status)
202
+
203
+
204
+ def _merge_parts(parts):
205
+ """Join the text pieces of a streamed reply; keep function calls and signatures as they came."""
206
+ out = []
207
+ for p in parts:
208
+ if "text" in p and "functionCall" not in p and out and "text" in out[-1] and "functionCall" not in out[-1] and bool(p.get("thought")) == bool(out[-1].get("thought")):
209
+ prev = out[-1]
210
+ prev["text"] = prev.get("text", "") + p.get("text", "")
211
+ if p.get("thoughtSignature"):
212
+ prev["thoughtSignature"] = p["thoughtSignature"]
213
+ else:
214
+ out.append(dict(p))
215
+ return out
@@ -0,0 +1,135 @@
1
+ """Any service that speaks OpenAI's Chat Completions API (streamed), with function calling.
2
+
3
+ That covers OpenAI itself and many others - a university's AI gateway, vLLM, Ollama or
4
+ LM Studio on a lab server (set the address with `AskTim! OpenAI --url http://host:port/v1`).
5
+ A local server may not need a key.
6
+ """
7
+
8
+ import json
9
+
10
+ from .. import net
11
+ from . import Provider, ProviderError, ToolCall, Turn, error_message_from_body
12
+
13
+
14
+ class OpenAIProvider(Provider):
15
+ name = "openai"
16
+
17
+ def __init__(self, key, model, cfg):
18
+ Provider.__init__(self, key, model, cfg)
19
+ self.base = (cfg.get("openai_base_url") or "https://api.openai.com/v1").rstrip("/")
20
+ self._token_param = "max_completion_tokens" if "api.openai.com" in self.base else None
21
+ self._no_tools = False
22
+
23
+ def _messages(self, system, conversation):
24
+ msgs = [{"role": "system", "content": system}]
25
+ for it in conversation.items:
26
+ if it["kind"] == "user":
27
+ msgs.append({"role": "user", "content": it["text"] or "(empty)"})
28
+ elif it["kind"] == "assistant":
29
+ t = it["turn"]
30
+ if t.provider == self.name and isinstance(t.raw, dict):
31
+ msgs.append(t.raw)
32
+ else:
33
+ m = {"role": "assistant", "content": t.text or ""}
34
+ if t.tool_calls:
35
+ m["tool_calls"] = [
36
+ {"id": c.id, "type": "function", "function": {"name": c.name, "arguments": json.dumps(c.input)}} for c in t.tool_calls
37
+ ]
38
+ msgs.append(m)
39
+ elif it["kind"] == "results":
40
+ for r in it["results"]:
41
+ content = r.content or "(no output)"
42
+ if r.is_error:
43
+ content = "ERROR: " + content
44
+ msgs.append({"role": "tool", "tool_call_id": r.id, "content": content})
45
+ if it.get("text"):
46
+ msgs.append({"role": "user", "content": it["text"]})
47
+ return msgs
48
+
49
+ def complete(self, system, conversation, tools=None, purpose="chat", on_text=None, on_status=None):
50
+ def attempt():
51
+ body = {"model": self.model, "messages": self._messages(system, conversation), "stream": True}
52
+ if tools and not self._no_tools:
53
+ body["tools"] = [{"type": "function", "function": {"name": t.name, "description": t.description, "parameters": t.parameters}} for t in tools]
54
+ mt = self.cfg.get("openai_max_tokens")
55
+ if mt and self._token_param:
56
+ body[self._token_param] = int(mt)
57
+ headers = {"authorization": "Bearer " + self.key} if self.key else {}
58
+ resp = net.open_request(self.base + "/chat/completions", headers, body, timeout=120)
59
+ return self._read(resp, on_text)
60
+
61
+ for _round in range(3):
62
+ try:
63
+ return net.with_retries(attempt, attempts=3, on_wait=lambda e, w: on_status and on_status("The service is busy; waiting %d s…" % w))
64
+ except net.HTTPError as e:
65
+ msg = error_message_from_body(e.body).lower()
66
+ if e.status == 400 and self._token_param and ("max_completion_tokens" in msg or "max_tokens" in msg):
67
+ self._token_param = "max_tokens" if self._token_param == "max_completion_tokens" else None
68
+ continue
69
+ raise self._error(e)
70
+ raise ProviderError("The request could not be made to work with this service.", kind="bad_request")
71
+
72
+ def _read(self, resp, on_text):
73
+ text, calls, finish, model, usage = [], {}, None, self.model, {}
74
+ for _event, data in net.iter_sse(resp):
75
+ if data.strip() == "[DONE]":
76
+ break
77
+ try:
78
+ ev = json.loads(data)
79
+ except ValueError:
80
+ continue
81
+ if ev.get("error"):
82
+ raise net.HTTPError(str(ev["error"].get("message") if isinstance(ev["error"], dict) else ev["error"]), status=500, body=data)
83
+ model = ev.get("model") or model
84
+ if ev.get("usage"):
85
+ usage = ev["usage"]
86
+ for ch in ev.get("choices") or []:
87
+ d = ch.get("delta") or {}
88
+ if d.get("content"):
89
+ text.append(d["content"])
90
+ if on_text:
91
+ on_text(d["content"])
92
+ for tc in d.get("tool_calls") or []:
93
+ i = tc.get("index", 0)
94
+ c = calls.setdefault(i, {"id": None, "name": "", "arguments": ""})
95
+ if tc.get("id"):
96
+ c["id"] = tc["id"]
97
+ fn = tc.get("function") or {}
98
+ if fn.get("name"):
99
+ c["name"] += fn["name"]
100
+ if fn.get("arguments"):
101
+ c["arguments"] += fn["arguments"]
102
+ if ch.get("finish_reason"):
103
+ finish = ch["finish_reason"]
104
+ out_calls, raw_calls = [], []
105
+ for i in sorted(calls):
106
+ c = calls[i]
107
+ cid = c["id"] or "call_%d" % i
108
+ try:
109
+ args = json.loads(c["arguments"]) if c["arguments"].strip() else {}
110
+ except ValueError:
111
+ args = {"_incomplete": c["arguments"][:2000]}
112
+ out_calls.append(ToolCall(cid, c["name"], args))
113
+ raw_calls.append({"id": cid, "type": "function", "function": {"name": c["name"], "arguments": c["arguments"] or "{}"}})
114
+ raw = {"role": "assistant", "content": "".join(text)}
115
+ if raw_calls:
116
+ raw["tool_calls"] = raw_calls
117
+ sr = {"stop": "end", "tool_calls": "tool_use", "function_call": "tool_use", "length": "max_tokens", "content_filter": "refusal"}.get(finish or "stop", "end")
118
+ if out_calls and sr == "end":
119
+ sr = "tool_use"
120
+ return Turn(text="".join(text), tool_calls=out_calls, stop_reason=sr, model=model, provider=self.name, raw=raw, usage=usage)
121
+
122
+ def _error(self, e):
123
+ msg = error_message_from_body(e.body) if e.body else str(e)
124
+ host = self.base.split("/")[2] if "//" in self.base else self.base
125
+ if e.network:
126
+ return ProviderError("Could not reach %s: %s" % (host, e), kind="network")
127
+ if e.status in (401, 403):
128
+ return ProviderError("Your key was not accepted by %s (%s). Store a new one with: AskTim! OpenAI" % (host, msg), kind="auth", status=e.status)
129
+ if e.status == 404:
130
+ return ProviderError("%s did not find the model %r or the address (%s). Check with: AskTim! status" % (host, self.model, msg), kind="notfound", status=404)
131
+ if e.status == 429:
132
+ return ProviderError("Too many requests, or no credit left, at %s (%s)." % (host, msg), kind="rate", status=429)
133
+ if e.status and e.status >= 500:
134
+ return ProviderError("%s is busy or having trouble (HTTP %s: %s). Try again in a minute." % (host, e.status, msg), kind="busy", status=e.status)
135
+ return ProviderError("%s refused the request (HTTP %s: %s)." % (host, e.status, msg), kind="bad_request", status=e.status)