codehaven 0.14.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.
- codehaven-0.14.0.dist-info/METADATA +686 -0
- codehaven-0.14.0.dist-info/RECORD +57 -0
- codehaven-0.14.0.dist-info/WHEEL +5 -0
- codehaven-0.14.0.dist-info/entry_points.txt +3 -0
- codehaven-0.14.0.dist-info/licenses/LICENSE +21 -0
- codehaven-0.14.0.dist-info/top_level.txt +1 -0
- offline_agent/__init__.py +2 -0
- offline_agent/__main__.py +4 -0
- offline_agent/agent.py +815 -0
- offline_agent/answers.py +438 -0
- offline_agent/arabic.py +106 -0
- offline_agent/changes.py +228 -0
- offline_agent/chats.py +121 -0
- offline_agent/cli.py +379 -0
- offline_agent/coder.py +199 -0
- offline_agent/dependencies.py +132 -0
- offline_agent/doctor.py +190 -0
- offline_agent/documents.py +189 -0
- offline_agent/edits.py +204 -0
- offline_agent/errors.py +41 -0
- offline_agent/evaluation.py +284 -0
- offline_agent/evidence.py +187 -0
- offline_agent/exclusions.py +95 -0
- offline_agent/export.py +27 -0
- offline_agent/gui.css +237 -0
- offline_agent/gui.html +177 -0
- offline_agent/gui.js +1213 -0
- offline_agent/gui.py +967 -0
- offline_agent/gui_arabic.js +226 -0
- offline_agent/guides.py +203 -0
- offline_agent/history.py +126 -0
- offline_agent/index_cache.py +78 -0
- offline_agent/insights.py +333 -0
- offline_agent/javascript.py +200 -0
- offline_agent/knowledge.py +569 -0
- offline_agent/languages.py +396 -0
- offline_agent/memory.py +192 -0
- offline_agent/messages.py +51 -0
- offline_agent/model.py +498 -0
- offline_agent/more_languages.py +253 -0
- offline_agent/ocr.py +204 -0
- offline_agent/prompts.py +130 -0
- offline_agent/references/langgraph-approvals.md +38 -0
- offline_agent/references/langgraph-checkpoints.md +37 -0
- offline_agent/references/langgraph-graphs.md +42 -0
- offline_agent/references/langgraph.md +49 -0
- offline_agent/review.py +205 -0
- offline_agent/scans.py +325 -0
- offline_agent/semantic.py +264 -0
- offline_agent/slash.py +53 -0
- offline_agent/study.py +210 -0
- offline_agent/symbols.py +201 -0
- offline_agent/tasks.py +164 -0
- offline_agent/test_runner.py +264 -0
- offline_agent/trace.py +239 -0
- offline_agent/tracebacks.py +98 -0
- offline_agent/workspace.py +419 -0
offline_agent/model.py
ADDED
|
@@ -0,0 +1,498 @@
|
|
|
1
|
+
"""Ollama transport: numeric loopback only, no proxies or redirects."""
|
|
2
|
+
import contextlib
|
|
3
|
+
import http.client
|
|
4
|
+
import ipaddress
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
import socket
|
|
8
|
+
import sys
|
|
9
|
+
import threading
|
|
10
|
+
import urllib.error
|
|
11
|
+
import urllib.parse
|
|
12
|
+
import urllib.request
|
|
13
|
+
|
|
14
|
+
MODEL = "qwen2.5-coder:7b" # The default, and the model the evals were tuned and measured on.
|
|
15
|
+
# The characters an Ollama model name may use; anything else is refused before it reaches a request.
|
|
16
|
+
MODEL_NAME = re.compile(r"[\w.:/@-]{1,200}")
|
|
17
|
+
# The most bytes accepted in one model reply, so a misbehaving server cannot fill memory.
|
|
18
|
+
MAX_RESPONSE_BYTES = 2_000_000
|
|
19
|
+
# Messages this small are left as they are when compacting: a stub would save almost nothing.
|
|
20
|
+
STUB_MIN_BYTES = 400
|
|
21
|
+
PROMPT_BUDGET = 12_000 # Default conversation budget in UTF-8 bytes; --prompt-budget changes it.
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def cloud_name(name):
|
|
25
|
+
"""Ollama names cloud-backed models with a cloud tag; CodeHaven never sends code to them."""
|
|
26
|
+
return name.endswith(("-cloud", ":cloud"))
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def read_limit(model):
|
|
30
|
+
"""The most bytes of one file to put in a prompt: half the model's budget, so the rest of the conversation fits."""
|
|
31
|
+
return max(4000, getattr(model, "prompt_budget", PROMPT_BUDGET) // 2)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class InvalidReply(ValueError):
|
|
35
|
+
"""The model answered, but not with a usable action; the agent may ask it to correct itself."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Stopped(Exception):
|
|
39
|
+
"""The user stopped the answer. Not a ValueError, so no helper mistakes it for a bad reply and carries on."""
|
|
40
|
+
|
|
41
|
+
def __init__(self):
|
|
42
|
+
"""Carry the one message the page and the terminal show for a stopped answer."""
|
|
43
|
+
super().__init__("Stopped.")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class RepeatedAnswer(InvalidReply):
|
|
47
|
+
"""A finish answer began looping and generation was stopped. answer holds the text before the loop."""
|
|
48
|
+
|
|
49
|
+
def __init__(self, answer):
|
|
50
|
+
"""Keep the usable part of the answer, and word the error as a correction the model can act on."""
|
|
51
|
+
super().__init__("the final answer kept repeating the same text, so generation was stopped; "
|
|
52
|
+
"answer briefly and state each point only once")
|
|
53
|
+
self.answer = answer
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class RepetitionGuard:
|
|
57
|
+
"""Stop a final answer that keeps repeating the same phrase, as small models can at temperature 0.
|
|
58
|
+
|
|
59
|
+
Checked on every streamed piece, so the window slides across a loop's shared phrase even when
|
|
60
|
+
the surrounding words drift. A global repeat penalty is avoided because answers quote code, which must be copied exactly.
|
|
61
|
+
"""
|
|
62
|
+
# A loop is the latest WINDOW characters having appeared TIMES times; that tail must hold at least
|
|
63
|
+
# DISTINCT different characters to count.
|
|
64
|
+
WINDOW, TIMES, DISTINCT = 60, 3, 8
|
|
65
|
+
|
|
66
|
+
def __init__(self):
|
|
67
|
+
"""Start with no answer text seen."""
|
|
68
|
+
self.text = ""
|
|
69
|
+
|
|
70
|
+
def feed(self, piece):
|
|
71
|
+
"""Add one streamed piece of the answer; raise RepeatedAnswer once it is looping."""
|
|
72
|
+
self.text += piece
|
|
73
|
+
# Too short to hold TIMES copies of a window.
|
|
74
|
+
if len(self.text) < self.WINDOW * self.TIMES:
|
|
75
|
+
return
|
|
76
|
+
tail = self.text[-self.WINDOW:]
|
|
77
|
+
# Separator runs such as "-----" are ignored; real loops have varied characters.
|
|
78
|
+
if len(set(tail)) >= self.DISTINCT and self.text.count(tail) >= self.TIMES:
|
|
79
|
+
raise RepeatedAnswer(self.before_loop(tail))
|
|
80
|
+
|
|
81
|
+
def before_loop(self, tail):
|
|
82
|
+
"""Keep everything up to the loop's second pass, trimmed back to a sentence or line end."""
|
|
83
|
+
first = self.text.find(tail)
|
|
84
|
+
kept = self.text[:self.text.find(tail, first + len(tail))]
|
|
85
|
+
end = max(kept.rfind(". "), kept.rfind(".\n"), kept.rfind("\n"))
|
|
86
|
+
return (kept[:end + 1] if end > 0 else kept).strip()
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class FinishContent:
|
|
90
|
+
"""Incrementally decode the content string of a streamed finish action and pass new text to emit."""
|
|
91
|
+
ESCAPES = {"n": "\n", "t": "\t", "r": "\r", "b": "\b", "f": "\f"}
|
|
92
|
+
|
|
93
|
+
def __init__(self, emit):
|
|
94
|
+
"""position is the buffer index of the next undecoded character, or None until the content string opens."""
|
|
95
|
+
self.emit = emit
|
|
96
|
+
self.buffer = ""
|
|
97
|
+
self.position = None
|
|
98
|
+
self.done = False
|
|
99
|
+
|
|
100
|
+
def feed(self, text):
|
|
101
|
+
"""Add raw streamed JSON text and emit whatever more of the finish content can now be decoded."""
|
|
102
|
+
self.buffer += text
|
|
103
|
+
if self.done:
|
|
104
|
+
return
|
|
105
|
+
# Emit nothing until the reply is known to be a finish action and its content string has opened.
|
|
106
|
+
if self.position is None:
|
|
107
|
+
content = re.search(r'"content"\s*:\s*"', self.buffer)
|
|
108
|
+
if not content or not re.search(r'"action"\s*:\s*"finish"', self.buffer):
|
|
109
|
+
return
|
|
110
|
+
self.position = content.end()
|
|
111
|
+
decoded, index, buffer = [], self.position, self.buffer
|
|
112
|
+
while index < len(buffer):
|
|
113
|
+
char = buffer[index]
|
|
114
|
+
# An unescaped quote closes the content string.
|
|
115
|
+
if char == '"':
|
|
116
|
+
self.done = True
|
|
117
|
+
break
|
|
118
|
+
if char != "\\":
|
|
119
|
+
decoded.append(char)
|
|
120
|
+
index += 1
|
|
121
|
+
continue
|
|
122
|
+
if index + 1 >= len(buffer):
|
|
123
|
+
break # Wait for the rest of the escape sequence.
|
|
124
|
+
if buffer[index + 1] != "u":
|
|
125
|
+
decoded.append(self.ESCAPES.get(buffer[index + 1], buffer[index + 1]))
|
|
126
|
+
index += 2
|
|
127
|
+
continue
|
|
128
|
+
# A \uXXXX escape: wait until all four hex digits have arrived.
|
|
129
|
+
if index + 6 > len(buffer):
|
|
130
|
+
break
|
|
131
|
+
code = int(buffer[index + 2:index + 6], 16)
|
|
132
|
+
if 0xD800 <= code < 0xDC00: # A surrogate pair arrives as two escapes.
|
|
133
|
+
if index + 12 > len(buffer):
|
|
134
|
+
break
|
|
135
|
+
low = int(buffer[index + 8:index + 12], 16)
|
|
136
|
+
code = 0x10000 + ((code - 0xD800) << 10) + (low - 0xDC00)
|
|
137
|
+
# Step over the high half here; the shared code below steps over the low half.
|
|
138
|
+
index += 6
|
|
139
|
+
decoded.append(chr(code))
|
|
140
|
+
index += 6
|
|
141
|
+
self.position = index
|
|
142
|
+
if decoded:
|
|
143
|
+
self.emit("".join(decoded))
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def response_metrics(result):
|
|
147
|
+
"""Turn the counters in Ollama's final chunk into seconds, token counts, and tokens per second.
|
|
148
|
+
|
|
149
|
+
Missing or malformed counters are left out rather than guessed. bool is excluded explicitly because
|
|
150
|
+
it is a kind of int in Python.
|
|
151
|
+
"""
|
|
152
|
+
metrics = {}
|
|
153
|
+
for source, label in (("load_duration", "load_seconds"), ("prompt_eval_duration", "prompt_seconds"),
|
|
154
|
+
("eval_duration", "generation_seconds"), ("total_duration", "total_seconds")):
|
|
155
|
+
value = result.get(source)
|
|
156
|
+
if isinstance(value, (int, float)) and not isinstance(value, bool) and value >= 0:
|
|
157
|
+
# Ollama reports durations in nanoseconds.
|
|
158
|
+
metrics[label] = round(value / 1_000_000_000, 3)
|
|
159
|
+
for source, label in (("prompt_eval_count", "prompt_tokens"), ("eval_count", "generated_tokens"),
|
|
160
|
+
("prompt_eval_cached_count", "cached_tokens")):
|
|
161
|
+
value = result.get(source)
|
|
162
|
+
if isinstance(value, int) and not isinstance(value, bool) and value >= 0:
|
|
163
|
+
metrics[label] = value
|
|
164
|
+
duration = result.get("eval_duration")
|
|
165
|
+
if isinstance(duration, (int, float)) and not isinstance(duration, bool) and duration > 0 and "generated_tokens" in metrics:
|
|
166
|
+
metrics["tokens_per_second"] = round(metrics["generated_tokens"] / (duration / 1e9), 2)
|
|
167
|
+
# Not every Ollama version reports cached tokens; None says unknown, which is different from zero.
|
|
168
|
+
if metrics and "cached_tokens" not in metrics:
|
|
169
|
+
metrics["cached_tokens"] = None
|
|
170
|
+
return metrics
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def stub(message):
|
|
174
|
+
"""One-line stand-in for an old bulky message. Tool results keep their header line."""
|
|
175
|
+
content = message["content"]
|
|
176
|
+
size = len(content.encode("utf-8"))
|
|
177
|
+
if size <= STUB_MIN_BYTES:
|
|
178
|
+
return message
|
|
179
|
+
# An old assistant action keeps its JSON shape; only a long content field is replaced.
|
|
180
|
+
if message["role"] == "assistant":
|
|
181
|
+
try:
|
|
182
|
+
reply = json.loads(content)
|
|
183
|
+
except json.JSONDecodeError:
|
|
184
|
+
return message
|
|
185
|
+
body = reply.get("content") if isinstance(reply, dict) else None
|
|
186
|
+
if not isinstance(body, str) or len(body) <= 200:
|
|
187
|
+
return message
|
|
188
|
+
return {**message, "content": json.dumps({**reply, "content": f"[{len(body.encode()):,} bytes omitted]"})}
|
|
189
|
+
# Other messages are compacted only when they are tool results or reference excerpts, never user text.
|
|
190
|
+
header = content.split("\n", 1)[0][:200]
|
|
191
|
+
if not header.startswith(("Tool result for", "Local reference excerpts")):
|
|
192
|
+
return message
|
|
193
|
+
return {**message, "content": f"{header}\n[Older result compacted: {size:,} bytes omitted. "
|
|
194
|
+
"Read or search again if you need it.]"}
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def compact_messages(messages, budget=PROMPT_BUDGET):
|
|
198
|
+
"""Keep a stable prefix until bounded history requires compaction.
|
|
199
|
+
|
|
200
|
+
Preserve system instructions and the original task. First replace older tool results
|
|
201
|
+
and file contents with one-line stubs (oldest first), keeping the conversation's shape.
|
|
202
|
+
Only if that is not enough, drop the oldest messages and truncate the newest.
|
|
203
|
+
Never mutate the graph's complete in-memory conversation.
|
|
204
|
+
"""
|
|
205
|
+
def size(message):
|
|
206
|
+
"""Bytes a message costs in the prompt, allowing 64 for its role and framing."""
|
|
207
|
+
return len(message["content"].encode("utf-8")) + 64
|
|
208
|
+
|
|
209
|
+
if sum(map(size, messages)) <= budget:
|
|
210
|
+
return messages
|
|
211
|
+
if len(messages) < 2:
|
|
212
|
+
raise ValueError("Prompt exceeds budget; shorten the task or increase --prompt-budget")
|
|
213
|
+
# The system instructions and the original task are never compacted.
|
|
214
|
+
# 160 bytes are held back for the "Earlier context omitted" notice added at the end.
|
|
215
|
+
fixed = messages[:2]
|
|
216
|
+
remaining = budget - sum(map(size, fixed)) - 160
|
|
217
|
+
if remaining < 512:
|
|
218
|
+
raise ValueError("Task and instructions exceed prompt budget; shorten the task or increase --prompt-budget")
|
|
219
|
+
history = list(messages[2:])
|
|
220
|
+
for index in range(len(history) - 1): # The newest message stays intact.
|
|
221
|
+
if sum(map(size, fixed + history)) <= budget:
|
|
222
|
+
break
|
|
223
|
+
history[index] = stub(history[index])
|
|
224
|
+
if sum(map(size, fixed + history)) <= budget:
|
|
225
|
+
return fixed + history
|
|
226
|
+
# Stubs were not enough: keep the newest messages that fit, and cut the newest one if even it does not fit.
|
|
227
|
+
recent = []
|
|
228
|
+
for message in reversed(history):
|
|
229
|
+
if size(message) <= remaining:
|
|
230
|
+
recent.append(message)
|
|
231
|
+
remaining -= size(message)
|
|
232
|
+
elif not recent:
|
|
233
|
+
marker = "\n[CONTEXT TRUNCATED: incomplete evidence; do not reconstruct a file from this excerpt.]"
|
|
234
|
+
available = remaining - len(marker.encode()) - 64
|
|
235
|
+
excerpt = message["content"].encode()[:max(0, available)].decode("utf-8", errors="ignore")
|
|
236
|
+
recent.append({**message, "content": excerpt + marker})
|
|
237
|
+
break
|
|
238
|
+
else:
|
|
239
|
+
break
|
|
240
|
+
notice = {"role": "user", "content": "Earlier context omitted to fit budget; use tools to verify missing evidence."}
|
|
241
|
+
return fixed + [notice] + list(reversed(recent))
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
245
|
+
"""Refuse every HTTP redirect, so a reply can never send the prompt (and the code in it) to another host."""
|
|
246
|
+
|
|
247
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
248
|
+
"""Called by urllib for any 3xx reply; raising here stops the redirect from being followed."""
|
|
249
|
+
raise ValueError("Model server redirects are disabled")
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
class ChatHandler(urllib.request.HTTPHandler):
|
|
253
|
+
"""Opens connections like the standard handler, and lets the client keep hold of a chat's socket.
|
|
254
|
+
|
|
255
|
+
urllib hides the socket while it waits for the first byte of a reply, which with a local model can be
|
|
256
|
+
minutes of loading and prompt processing. Keeping the socket is what lets Ollama.stop() end that wait.
|
|
257
|
+
"""
|
|
258
|
+
|
|
259
|
+
def __init__(self, client):
|
|
260
|
+
"""Remember the Ollama client whose chat sockets are to be handed over."""
|
|
261
|
+
super().__init__()
|
|
262
|
+
self.client = client
|
|
263
|
+
|
|
264
|
+
def http_open(self, req):
|
|
265
|
+
"""Open req on a connection that reports its socket to the client as soon as it is connected."""
|
|
266
|
+
client = self.client
|
|
267
|
+
|
|
268
|
+
class Connection(http.client.HTTPConnection):
|
|
269
|
+
"""A plain HTTP connection that tells the client about its socket."""
|
|
270
|
+
|
|
271
|
+
def connect(self):
|
|
272
|
+
"""Connect, then hand the socket over; this raises Stopped if the answer was already stopped."""
|
|
273
|
+
super().connect()
|
|
274
|
+
client.connected(self.sock)
|
|
275
|
+
|
|
276
|
+
return self.do_open(Connection, req)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
class Ollama:
|
|
280
|
+
"""Client for one local Ollama server. Only plain HTTP on a numeric loopback address is accepted."""
|
|
281
|
+
|
|
282
|
+
# Waiting on a local model is normal: loading plus prompt processing alone can take minutes on a busy machine.
|
|
283
|
+
def __init__(self, model=MODEL, endpoint="http://127.0.0.1:11434", timeout=600,
|
|
284
|
+
max_output_tokens=1024, prompt_budget=PROMPT_BUDGET):
|
|
285
|
+
"""Validate the limits, the endpoint, and the model name. Nothing is sent until a request is made."""
|
|
286
|
+
if not 256 <= max_output_tokens <= 8192:
|
|
287
|
+
raise ValueError("--max-output-tokens must be between 256 and 8192")
|
|
288
|
+
if not 8000 <= prompt_budget <= 64_000:
|
|
289
|
+
raise ValueError("--prompt-budget must be between 8000 and 64000 bytes")
|
|
290
|
+
self.max_output_tokens = max_output_tokens
|
|
291
|
+
self.prompt_budget = prompt_budget
|
|
292
|
+
self.last_metrics = {}
|
|
293
|
+
self.last_raw = ""
|
|
294
|
+
self.companions = set() # Other models CodeHaven itself uses, such as the embedding model.
|
|
295
|
+
# The host must be a numeric loopback IP: a name such as localhost could be pointed somewhere else.
|
|
296
|
+
url = urllib.parse.urlsplit(endpoint)
|
|
297
|
+
try:
|
|
298
|
+
local = ipaddress.ip_address(url.hostname).is_loopback
|
|
299
|
+
url.port # Validate the optional port before making a request.
|
|
300
|
+
except (ValueError, TypeError):
|
|
301
|
+
local = False
|
|
302
|
+
# Credentials, a path, a query, or a fragment are refused too, so the endpoint is exactly an origin.
|
|
303
|
+
if (not local or url.scheme != "http" or url.username or url.password
|
|
304
|
+
or url.path not in ("", "/") or url.query or url.fragment):
|
|
305
|
+
raise ValueError("Endpoint must be an HTTP numeric loopback origin, e.g. http://127.0.0.1:11434")
|
|
306
|
+
if not isinstance(model, str) or not MODEL_NAME.fullmatch(model) or cloud_name(model):
|
|
307
|
+
raise ValueError(f"Not a local Ollama model name: {model!r}")
|
|
308
|
+
self.endpoint = endpoint.rstrip("/")
|
|
309
|
+
self.model = model
|
|
310
|
+
self.timeout = timeout
|
|
311
|
+
# An empty ProxyHandler ignores the proxy environment variables, and NoRedirect refuses redirects,
|
|
312
|
+
# so every request goes straight to the loopback address and nowhere else.
|
|
313
|
+
self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect(), ChatHandler(self))
|
|
314
|
+
# Stopping an answer: the flag stop() sets, the thread a chat is running on, and that chat's socket.
|
|
315
|
+
self.stopping = threading.Event()
|
|
316
|
+
self.chat_thread = self.chat_socket = None
|
|
317
|
+
|
|
318
|
+
def connected(self, sock):
|
|
319
|
+
"""Called for every new connection: keep a chat's socket, so stop() can end a wait on it."""
|
|
320
|
+
if threading.get_ident() != self.chat_thread:
|
|
321
|
+
return # Another request, such as an embedding, which stop() leaves alone.
|
|
322
|
+
self.chat_socket = sock
|
|
323
|
+
# stop() sets the flag before it looks for the socket, so one of the two always notices the other.
|
|
324
|
+
if self.stopping.is_set():
|
|
325
|
+
raise Stopped()
|
|
326
|
+
|
|
327
|
+
def stop(self):
|
|
328
|
+
"""Stop the chat in progress, and refuse later ones until allow() is called. Safe from any thread.
|
|
329
|
+
|
|
330
|
+
Closing the connection is what stops Ollama generating, and it ends a wait for a model that is still
|
|
331
|
+
loading or reading its prompt, which a flag checked between pieces of the reply would not.
|
|
332
|
+
"""
|
|
333
|
+
self.stopping.set()
|
|
334
|
+
sock = self.chat_socket
|
|
335
|
+
if sock is not None:
|
|
336
|
+
with contextlib.suppress(OSError):
|
|
337
|
+
sock.shutdown(socket.SHUT_RDWR)
|
|
338
|
+
# On Windows a shutdown does not wake a read that is already waiting; closing the socket does.
|
|
339
|
+
# _real_close marks the socket closed, so the reader's own close afterwards does nothing.
|
|
340
|
+
if sys.platform == "win32":
|
|
341
|
+
with contextlib.suppress(OSError, AttributeError):
|
|
342
|
+
sock._real_close()
|
|
343
|
+
|
|
344
|
+
def allow(self):
|
|
345
|
+
"""Let chats run again after a stop(); called when a new request begins."""
|
|
346
|
+
self.stopping.clear()
|
|
347
|
+
|
|
348
|
+
def request(self, path, payload=None):
|
|
349
|
+
"""Send one request (GET without a payload, POST with one) and return the JSON object in the reply."""
|
|
350
|
+
data = None if payload is None else json.dumps(payload).encode()
|
|
351
|
+
req = urllib.request.Request(self.endpoint + path, data=data,
|
|
352
|
+
headers={"Content-Type": "application/json"})
|
|
353
|
+
try:
|
|
354
|
+
with self.opener.open(req, timeout=self.timeout) as response:
|
|
355
|
+
# Reading one byte past the cap tells an oversized reply from one exactly at the cap.
|
|
356
|
+
raw = response.read(MAX_RESPONSE_BYTES + 1)
|
|
357
|
+
if len(raw) > MAX_RESPONSE_BYTES:
|
|
358
|
+
raise ValueError("Model response exceeds 2 MB")
|
|
359
|
+
result = json.loads(raw)
|
|
360
|
+
if not isinstance(result, dict):
|
|
361
|
+
raise ValueError("Model server returned a non-object response")
|
|
362
|
+
return result
|
|
363
|
+
except (urllib.error.URLError, TimeoutError) as exc:
|
|
364
|
+
raise ValueError(f"Local Ollama request failed: {exc}. Start Ollama and check the installed model.") from exc
|
|
365
|
+
|
|
366
|
+
def stream_chat(self, payload, on_text=None):
|
|
367
|
+
"""POST a streaming chat, guard the finish answer against loops, and pass its text to on_text.
|
|
368
|
+
|
|
369
|
+
Raising inside the read loop closes the connection, which stops Ollama generating. stop(), called from
|
|
370
|
+
another thread, ends this call with Stopped whether it is waiting for the reply or reading it.
|
|
371
|
+
"""
|
|
372
|
+
if self.stopping.is_set():
|
|
373
|
+
raise Stopped()
|
|
374
|
+
req = urllib.request.Request(self.endpoint + "/api/chat", data=json.dumps(payload).encode(),
|
|
375
|
+
headers={"Content-Type": "application/json"})
|
|
376
|
+
guard = RepetitionGuard()
|
|
377
|
+
|
|
378
|
+
def answer_text(text):
|
|
379
|
+
"""Check each decoded piece of the finish answer for looping, then show it."""
|
|
380
|
+
guard.feed(text)
|
|
381
|
+
if on_text is not None:
|
|
382
|
+
on_text(text)
|
|
383
|
+
|
|
384
|
+
decoder = FinishContent(answer_text)
|
|
385
|
+
pieces, received, final = [], 0, {}
|
|
386
|
+
self.chat_thread = threading.get_ident()
|
|
387
|
+
try:
|
|
388
|
+
with self.opener.open(req, timeout=self.timeout) as response:
|
|
389
|
+
# Ollama streams one JSON object per line.
|
|
390
|
+
for raw in response:
|
|
391
|
+
if self.stopping.is_set():
|
|
392
|
+
raise Stopped()
|
|
393
|
+
received += len(raw)
|
|
394
|
+
if received > MAX_RESPONSE_BYTES:
|
|
395
|
+
raise ValueError("Model response exceeds 2 MB")
|
|
396
|
+
if not raw.strip():
|
|
397
|
+
continue
|
|
398
|
+
chunk = json.loads(raw)
|
|
399
|
+
if not isinstance(chunk, dict):
|
|
400
|
+
raise ValueError("Model server returned a non-object response")
|
|
401
|
+
if chunk.get("error"):
|
|
402
|
+
# Ollama itself stopped a looping reply; that is a bad reply, not a broken server.
|
|
403
|
+
if "repeat" in str(chunk["error"]).lower():
|
|
404
|
+
self.last_raw = "".join(pieces)
|
|
405
|
+
raise InvalidReply("the reply kept repeating the same text, so generation was stopped; "
|
|
406
|
+
"reply briefly and state each point only once")
|
|
407
|
+
raise ValueError(f"Local Ollama error: {chunk['error']}")
|
|
408
|
+
piece = (chunk.get("message") or {}).get("content") or ""
|
|
409
|
+
if piece:
|
|
410
|
+
pieces.append(piece)
|
|
411
|
+
decoder.feed(piece)
|
|
412
|
+
if chunk.get("done"):
|
|
413
|
+
final = chunk
|
|
414
|
+
break
|
|
415
|
+
self.last_raw = "".join(pieces)
|
|
416
|
+
except Stopped:
|
|
417
|
+
raise
|
|
418
|
+
except Exception as exc:
|
|
419
|
+
# A connection closed by stop() fails in whatever way the read happened to be waiting.
|
|
420
|
+
if self.stopping.is_set():
|
|
421
|
+
raise Stopped() from None
|
|
422
|
+
if isinstance(exc, (urllib.error.URLError, TimeoutError)):
|
|
423
|
+
raise ValueError(f"Local Ollama request failed: {exc}. Start Ollama and check the installed model.") from exc
|
|
424
|
+
raise
|
|
425
|
+
finally:
|
|
426
|
+
self.chat_thread = self.chat_socket = None
|
|
427
|
+
if self.stopping.is_set():
|
|
428
|
+
raise Stopped() # The closed connection read as a reply that simply ended early.
|
|
429
|
+
return {**final, "message": {"content": "".join(pieces)}}
|
|
430
|
+
|
|
431
|
+
def check_model(self):
|
|
432
|
+
"""Raise ValueError unless the chosen model is installed, runs on this machine, and can chat."""
|
|
433
|
+
models = self.request("/api/tags").get("models", [])
|
|
434
|
+
names = {m.get("name") for m in models}
|
|
435
|
+
if self.model not in names:
|
|
436
|
+
raise ValueError(f"Model {self.model!r} is not installed. Run: ollama pull {self.model} while online.")
|
|
437
|
+
info = self.request("/api/show", {"model": self.model})
|
|
438
|
+
if info.get("remote_host") or info.get("remote_model"):
|
|
439
|
+
raise ValueError("Remote-backed models are disabled")
|
|
440
|
+
if "capabilities" in info and "completion" not in info["capabilities"]:
|
|
441
|
+
raise ValueError(f"Model {self.model!r} cannot chat (it is an embedding model); choose another.")
|
|
442
|
+
|
|
443
|
+
def local_models(self):
|
|
444
|
+
"""Installed models that run on this machine and can chat, the default first.
|
|
445
|
+
|
|
446
|
+
Cloud-backed models and embedding-only models are left out.
|
|
447
|
+
"""
|
|
448
|
+
found = []
|
|
449
|
+
for item in self.request("/api/tags").get("models", []):
|
|
450
|
+
name = item.get("name") if isinstance(item, dict) else None
|
|
451
|
+
if (not isinstance(name, str) or cloud_name(name) or item.get("remote_host") or item.get("remote_model")
|
|
452
|
+
or ("capabilities" in item and "completion" not in item["capabilities"])):
|
|
453
|
+
continue
|
|
454
|
+
details = item.get("details") or {}
|
|
455
|
+
found.append({"name": name, "parameters": details.get("parameter_size", ""), "family": details.get("family", ""),
|
|
456
|
+
"bytes": item.get("size", 0)})
|
|
457
|
+
return sorted(found, key=lambda m: (m["name"] != MODEL, m["name"]))
|
|
458
|
+
|
|
459
|
+
def use(self, name):
|
|
460
|
+
"""Switch to another installed local model; the current one stays if the new one fails its checks."""
|
|
461
|
+
if not isinstance(name, str) or not MODEL_NAME.fullmatch(name) or cloud_name(name):
|
|
462
|
+
raise ValueError(f"Not a local Ollama model name: {name!r}")
|
|
463
|
+
previous, self.model = self.model, name
|
|
464
|
+
try:
|
|
465
|
+
self.check_model()
|
|
466
|
+
except ValueError:
|
|
467
|
+
self.model = previous
|
|
468
|
+
raise
|
|
469
|
+
|
|
470
|
+
def other_loaded_models(self):
|
|
471
|
+
"""Other models Ollama holds in memory: competing for memory makes it reload ours on every step."""
|
|
472
|
+
try:
|
|
473
|
+
running = self.request("/api/ps").get("models", [])
|
|
474
|
+
except ValueError:
|
|
475
|
+
return []
|
|
476
|
+
return sorted({m.get("name") for m in running if isinstance(m, dict) and m.get("name") not in {None, self.model, *self.companions}})
|
|
477
|
+
|
|
478
|
+
def chat(self, messages, schema, on_text=None):
|
|
479
|
+
"""Return one JSON action. Always streams from Ollama so a looping answer can be stopped early;
|
|
480
|
+
with on_text, the finish answer is also shown as it is generated."""
|
|
481
|
+
self.last_metrics = {}
|
|
482
|
+
self.last_raw = ""
|
|
483
|
+
# Temperature 0 keeps actions repeatable, and keep_alive holds the model in memory between steps.
|
|
484
|
+
# num_ctx is in tokens while the budget is in bytes: half the budget plus the reply, and never below 8192.
|
|
485
|
+
payload = {"model": self.model, "messages": compact_messages(messages, self.prompt_budget),
|
|
486
|
+
"stream": True, "format": schema,
|
|
487
|
+
"keep_alive": "30m",
|
|
488
|
+
"options": {"temperature": 0, "num_predict": self.max_output_tokens,
|
|
489
|
+
"num_ctx": max(8192, self.prompt_budget // 2 + self.max_output_tokens)}}
|
|
490
|
+
result = self.stream_chat(payload, on_text)
|
|
491
|
+
self.last_metrics = response_metrics(result)
|
|
492
|
+
if result.get("done_reason") == "length":
|
|
493
|
+
raise InvalidReply("Model reached the response token limit; no partial action was executed. "
|
|
494
|
+
"Give a shorter answer, or increase --max-output-tokens.")
|
|
495
|
+
try:
|
|
496
|
+
return json.loads(result["message"]["content"])
|
|
497
|
+
except (KeyError, TypeError, json.JSONDecodeError) as exc:
|
|
498
|
+
raise InvalidReply("Model returned an invalid JSON response") from exc
|