imagent-cli 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.
Files changed (68) hide show
  1. imagent/__init__.py +0 -0
  2. imagent/__main__.py +5 -0
  3. imagent/cli.py +128 -0
  4. imagent/commands/__init__.py +0 -0
  5. imagent/commands/after_add.py +82 -0
  6. imagent/commands/delete.py +200 -0
  7. imagent/commands/failed.py +24 -0
  8. imagent/commands/forget.py +63 -0
  9. imagent/commands/help.py +82 -0
  10. imagent/commands/menu.py +155 -0
  11. imagent/commands/scan.py +1394 -0
  12. imagent/commands/search.py +432 -0
  13. imagent/commands/settings.py +139 -0
  14. imagent/commands/setup.py +1409 -0
  15. imagent/commands/uninstall.py +379 -0
  16. imagent/config.py +331 -0
  17. imagent/db/__init__.py +1 -0
  18. imagent/db/connection.py +237 -0
  19. imagent/db/operations.py +683 -0
  20. imagent/db/schema.sql +454 -0
  21. imagent/image_processing/__init__.py +14 -0
  22. imagent/image_processing/convert.py +48 -0
  23. imagent/image_processing/features.py +88 -0
  24. imagent/image_processing/hashing.py +49 -0
  25. imagent/image_processing/memory.py +101 -0
  26. imagent/image_processing/metadata.py +122 -0
  27. imagent/image_processing/ocr.py +129 -0
  28. imagent/image_processing/preprocess.py +33 -0
  29. imagent/image_processing/problems.py +53 -0
  30. imagent/image_processing/sample_pictures.py +214 -0
  31. imagent/os_specific/__init__.py +15 -0
  32. imagent/os_specific/convert.py +34 -0
  33. imagent/os_specific/files.py +64 -0
  34. imagent/os_specific/locking.py +31 -0
  35. imagent/os_specific/memory.py +153 -0
  36. imagent/os_specific/process.py +19 -0
  37. imagent/os_specific/storage.py +102 -0
  38. imagent/pipeline/__init__.py +1 -0
  39. imagent/pipeline/console.py +111 -0
  40. imagent/pipeline/discovery.py +107 -0
  41. imagent/pipeline/error_logger.py +69 -0
  42. imagent/pipeline/error_messages.py +56 -0
  43. imagent/pipeline/failure.py +51 -0
  44. imagent/pipeline/folder_picker.py +289 -0
  45. imagent/pipeline/locking.py +44 -0
  46. imagent/pipeline/progress.py +243 -0
  47. imagent/pipeline/serialisation.py +20 -0
  48. imagent/pipeline/storage.py +30 -0
  49. imagent/pipeline/validation.py +68 -0
  50. imagent/pipeline/versions.py +56 -0
  51. imagent/prompts/analysis_prompt.txt +8 -0
  52. imagent/prompts/analysis_schema.json +12 -0
  53. imagent/prompts/query_prompt.txt +14 -0
  54. imagent/text_processing/__init__.py +1 -0
  55. imagent/text_processing/cleaners.py +32 -0
  56. imagent/text_processing/formatters.py +79 -0
  57. imagent/vlm/__init__.py +1 -0
  58. imagent/vlm/analyzer.py +348 -0
  59. imagent/vlm/calibration.py +288 -0
  60. imagent/vlm/client.py +302 -0
  61. imagent/vlm/reply_validation.py +72 -0
  62. imagent/vlm/response_format.py +7 -0
  63. imagent_cli-0.1.0.dist-info/METADATA +171 -0
  64. imagent_cli-0.1.0.dist-info/RECORD +68 -0
  65. imagent_cli-0.1.0.dist-info/WHEEL +5 -0
  66. imagent_cli-0.1.0.dist-info/entry_points.txt +2 -0
  67. imagent_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
  68. imagent_cli-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,348 @@
1
+ from __future__ import annotations
2
+
3
+ import time
4
+ from typing import Callable, NamedTuple
5
+
6
+ import httpx
7
+ import ollama
8
+ from imagent import config
9
+ from imagent.vlm.client import make_client, other_models_running, restart_server, unload_model
10
+ from imagent.vlm.reply_validation import check_reply
11
+ from imagent.vlm.response_format import QueryUnderstanding
12
+ from imagent.image_processing.convert import ConversionFailed, converted_copy
13
+ from imagent.image_processing.features import extract_image_features
14
+ from imagent.image_processing.memory import check_image_size
15
+ from imagent.image_processing.ocr import extract_text_blocks
16
+ from imagent.image_processing.preprocess import preprocess_image
17
+ from imagent.image_processing.problems import TOO_LARGE, UNSUPPORTED, ImageProblem, explain
18
+ from imagent.pipeline.error_messages import describe
19
+ from imagent.pipeline.failure import IndexingFailure, attempt_record
20
+
21
+ # What went wrong; each has its own way of being put right.
22
+ CUT_OFF = "cut_off" # the reply ended at the output cap
23
+ INVALID_REPLY = "invalid_reply" # the reply is complete but does not fit the schema
24
+ TIMEOUT = "timeout" # no reply within the time limit
25
+ SERVER_CRASH = "server_crash" # the connection to Ollama broke, or its model runner stopped
26
+ OUT_OF_MEMORY = "out_of_memory" # Ollama has not enough memory for the model
27
+
28
+ # What the indexing loop does with a file for each kind (see pipeline/failure.py).
29
+ _HANDLING = {
30
+ CUT_OFF: {"retry_when": "model_changed", "model_trouble": True},
31
+ INVALID_REPLY: {"retry_when": "model_changed", "model_trouble": True},
32
+ # The machine's trouble, not the file's: the file stays queued and is tried again by the next run (the loop in
33
+ # imagent/commands/scan.py tries it config.SERVICE_TRIES times first, and tells the user when that was not enough).
34
+ TIMEOUT: {"park": False, "service": True},
35
+ SERVER_CRASH: {"park": False, "service": True},
36
+ OUT_OF_MEMORY: {"park": False, "service": True},
37
+ }
38
+
39
+
40
+ class AnalysisFailed(IndexingFailure):
41
+ """The model could not be made to give a usable reply by any of the steps for its kind of trouble.
42
+
43
+ ``kind`` is the last kind of trouble and ``attempts`` records every request made (see ``_request_analysis``).
44
+ """
45
+
46
+ def __init__(self, kind: str, error_id: str, attempts: list[dict], params: dict | None = None):
47
+ super().__init__(kind, error_id, attempts, params=params, **_HANDLING[kind])
48
+
49
+
50
+ class ServiceTrouble(Exception):
51
+ """Reaching the model failed in a way the steps in ``send_request`` could not put right."""
52
+
53
+ def __init__(self, kind: str, error_id: str, params: dict | None = None):
54
+ super().__init__(describe(error_id, params))
55
+ self.kind = kind
56
+ self.error_id = error_id
57
+ self.params = params or {}
58
+
59
+
60
+ class Analysis(NamedTuple):
61
+ """Everything learned about one image."""
62
+ reply: dict # the vision model's reply, exactly as it wrote it
63
+ ocr_text: list[str] # the pieces of text read in the image
64
+ features: dict # facts read from the pixels
65
+ attempts: list[dict] # one entry per request to the model; ``kind`` says what was wrong with the reply, if anything
66
+
67
+
68
+ def analyse_image(client: ollama.Client, model: str, image_path: str,
69
+ on_stage: Callable[[str], None] = lambda stage: None,
70
+ on_retry: Callable[[str], None] = lambda kind: None) -> Analysis:
71
+ """Analyse one image; ``on_stage`` is told what is being done, before each step.
72
+
73
+ ``on_retry`` is told the kind of trouble each time the model's reply has to be asked for again.
74
+ """
75
+ on_stage("checking image")
76
+ try:
77
+ return _analyse_file(client, model, image_path, on_stage, on_retry)
78
+ except ImageProblem as unsupported:
79
+ if unsupported.kind != UNSUPPORTED:
80
+ raise
81
+ on_stage("converting image")
82
+ try:
83
+ with converted_copy(image_path) as converted: # a PNG copy that is deleted when the analysis is done
84
+ return _analyse_file(client, model, converted, on_stage, on_retry)
85
+ except ConversionFailed as failed:
86
+ unsupported.attempts.append(attempt_record("converted the image", UNSUPPORTED, str(failed)))
87
+ raise unsupported from failed
88
+
89
+
90
+ def _check_image_size(client: ollama.Client, image_path: str, on_stage: Callable[[str], None]) -> None:
91
+ """``check_image_size``, but an image too large for the memory free is given more chances, one step after the other:
92
+ every model Ollama has loaded is unloaded (whatever setup found about the models sharing the memory) and the size is checked
93
+ again with the memory this frees; if it is still too large, it is checked once more with the larger share of the free memory,
94
+ ``config.IMAGE_MEMORY_SHARE_LAST_TRY``.
95
+
96
+ The models load again by themselves when the next request needs them. Raises ``ImageProblem`` as ``check_image_size`` does."""
97
+ try:
98
+ check_image_size(image_path)
99
+ return
100
+ except ImageProblem as large:
101
+ if large.kind != TOO_LARGE:
102
+ raise
103
+ loaded = other_models_running(client, [])
104
+ if loaded: # when no model is using memory there is nothing to free, and no reason to wait
105
+ on_stage("freeing memory for a large image")
106
+ for name in loaded:
107
+ unload_model(client, name)
108
+ time.sleep(config.OLLAMA_RECOVERY_WAIT) # the memory is not free the moment Ollama says the model is gone
109
+ try:
110
+ check_image_size(image_path)
111
+ return
112
+ except ImageProblem as still_large:
113
+ if still_large.kind != TOO_LARGE:
114
+ raise
115
+ check_image_size(image_path, config.IMAGE_MEMORY_SHARE_LAST_TRY)
116
+
117
+
118
+ def _analyse_file(client: ollama.Client, model: str, image_path: str,
119
+ on_stage: Callable[[str], None], on_retry: Callable[[str], None]) -> Analysis:
120
+ _check_image_size(client, image_path, on_stage) # raises ImageProblem if the image cannot be opened or is too large
121
+ # The steps that are quick and need no model come first: when one of them fails, no reply was asked for in vain.
122
+ try:
123
+ on_stage("preparing image")
124
+ image_bytes = preprocess_image(image_path)
125
+ features = extract_image_features(image_path)
126
+ on_stage("reading text in image")
127
+ ocr_text = extract_text_blocks(image_path)
128
+ except ImageProblem:
129
+ raise
130
+ except Exception as exc:
131
+ raise (explain(exc, image_path) or exc) from exc
132
+ on_stage("analysing image")
133
+ reply, attempts = _request_analysis(client, model, image_bytes, on_stage, on_retry)
134
+ return Analysis(reply, ocr_text, features, attempts)
135
+
136
+
137
+ def _ran_out_of_memory(exc: Exception) -> bool:
138
+ """True if a failed request was the computer running out of memory.
139
+
140
+ Ollama does not always say so: when the graphics memory runs out in the middle of a request, all it reports is
141
+ "Compute error" (status 500), so that counts too."""
142
+ if not isinstance(exc, ollama.ResponseError):
143
+ return False
144
+ message = str(exc).lower()
145
+ return "memory" in message or "compute error" in message
146
+
147
+
148
+ def send_request(client: ollama.Client, model: str, request: dict, note: Callable[[str, str], None],
149
+ on_stage: Callable[[str], None]) -> tuple:
150
+ """Send a chat request, putting right trouble in reaching the model, each kind in its own way.
151
+
152
+ No reply in time: ask again and wait longer. The connection broke or the model runner stopped: make sure Ollama is
153
+ running (starting it if it is on this computer) and ask again. Not enough memory: unload the other models, wait, ask again.
154
+ Each of these is done once for the connection troubles and up to ``config.OLLAMA_TIMEOUT_RAISES`` times for the wait.
155
+ Returns the reply and the client that got it (a new one if the wait was lengthened); raises ``ServiceTrouble`` when it runs out.
156
+ """
157
+ timeout, raises, recovered = config.OLLAMA_TIMEOUT, 0, False
158
+ while True:
159
+ try:
160
+ return client.chat(**request), client
161
+ except httpx.ReadTimeout as exc:
162
+ note(TIMEOUT, f"no reply within {timeout:g} seconds")
163
+ if raises >= config.OLLAMA_TIMEOUT_RAISES:
164
+ raise ServiceTrouble(TIMEOUT, "model_timeout") from exc
165
+ raises += 1
166
+ timeout *= config.OLLAMA_TIMEOUT_STEP
167
+ client = make_client(timeout=timeout)
168
+ on_stage(f"retrying: no reply in time; waiting up to {timeout:g} s")
169
+ except (httpx.RemoteProtocolError, httpx.ReadError, ConnectionError, ollama.ResponseError) as exc:
170
+ if isinstance(exc, ollama.ResponseError) and exc.status_code != 500:
171
+ raise # not a stopped runner (a missing model, a bad request): another kind of problem
172
+ out_of_memory = _ran_out_of_memory(exc)
173
+ kind = OUT_OF_MEMORY if out_of_memory else SERVER_CRASH
174
+ note(kind, f"{type(exc).__name__}: {exc}")
175
+ if recovered:
176
+ raise ServiceTrouble(kind, "model_out_of_memory" if out_of_memory else "model_stopped") from exc
177
+ recovered = True
178
+ if out_of_memory:
179
+ for name in other_models_running(client, [model]):
180
+ unload_model(client, name)
181
+ time.sleep(config.OLLAMA_RECOVERY_WAIT)
182
+ on_stage("retrying: memory was freed")
183
+ elif restart_server(client):
184
+ on_stage("retrying: Ollama was restarted")
185
+ else:
186
+ raise
187
+
188
+
189
+ def _was_cut_off(response, num_predict: int) -> bool:
190
+ """True if the model stopped because it reached the output cap, not because it was finished."""
191
+ if getattr(response, "done_reason", None) == "length":
192
+ return True
193
+ used = getattr(response, "eval_count", None)
194
+ return isinstance(used, int) and used >= num_predict
195
+
196
+
197
+ def _request_analysis(client: ollama.Client, model: str, image_bytes: bytes,
198
+ on_stage: Callable[[str], None] = lambda stage: None,
199
+ on_retry: Callable[[str], None] = lambda kind: None) -> tuple[dict, list[dict]]:
200
+ """Ask the model to describe the image and put right what is wrong with its reply, each kind of trouble in its own way.
201
+
202
+ A reply that ended at the output cap is either a loop or an answer that is simply long, and these are told apart by
203
+ what works. First one retry with different sampling at the same cap: it ends a loop, and costs a long answer only
204
+ one more try. If it is cut off again, the cap is raised step by step, up to what the context window has room for after
205
+ the prompt, with the normal sampling (a long answer is then the same answer, only finished). Nothing is asked to be shorter.
206
+
207
+ A complete reply that does not fit the schema is sent back with the problems found, and the model answers again.
208
+
209
+ Returns the reply and the record of every request; raises ``AnalysisFailed`` when the steps for its trouble run out.
210
+ """
211
+ first_messages = [
212
+ {"role": "system", "content": config.ANALYSIS_PROMPT},
213
+ {"role": "user", "content": "Analyze this image.", "images": [image_bytes]},
214
+ ]
215
+ messages = first_messages
216
+ cap = config.OLLAMA_MAX_OUTPUT_TOKENS
217
+ changed_sampling = False
218
+ step = "first try"
219
+ sampling_tried = False
220
+ raises = 0
221
+ feedback_tries = 0
222
+ retries = 0 # also the seed of a retry with changed sampling, so that no two retries repeat each other
223
+ attempts: list[dict] = []
224
+
225
+ def note(kind: str, detail: str) -> None:
226
+ """Record trouble that was put right on the way (a wait that ran out, a restart) as an attempt of its own."""
227
+ attempts.append(attempt_record(step, kind, detail, options=options))
228
+ on_retry(kind)
229
+
230
+ while True:
231
+ options = {**config.LLM_OPTIONS, "num_predict": cap}
232
+ if changed_sampling:
233
+ options.update(temperature=config.ANALYSIS_RETRY_TEMPERATURE, seed=retries,
234
+ repeat_penalty=config.ANALYSIS_RETRY_REPEAT_PENALTY)
235
+ try:
236
+ response, client = send_request(client, model, {"model": model, "messages": messages, "format": config.ANALYSIS_SCHEMA,
237
+ "options": options}, note, on_stage)
238
+ except ServiceTrouble as trouble:
239
+ raise AnalysisFailed(trouble.kind, trouble.error_id, attempts, trouble.params) from trouble
240
+ content = response.message.content or ""
241
+ reply, problems = check_reply(content, config.ANALYSIS_SCHEMA)
242
+ prompt_tokens = getattr(response, "prompt_eval_count", None)
243
+ attempt = {
244
+ "step": step, "kind": None, "options": options, "detail": "", "raw_reply": None,
245
+ "done_reason": getattr(response, "done_reason", None),
246
+ "eval_count": getattr(response, "eval_count", None), "prompt_eval_count": prompt_tokens,
247
+ }
248
+ attempts.append(attempt)
249
+ if reply is not None:
250
+ return reply, attempts
251
+
252
+ kind = CUT_OFF if _was_cut_off(response, cap) else INVALID_REPLY
253
+ attempt.update(kind=kind, detail="; ".join(problems)[:500], raw_reply=content)
254
+
255
+ if kind == CUT_OFF:
256
+ if not sampling_tried:
257
+ sampling_tried, changed_sampling, step = True, True, "changed sampling"
258
+ retries += 1
259
+ messages = first_messages
260
+ reason = "the reply was cut off; asking again with different sampling"
261
+ else:
262
+ room = config.OLLAMA_NUM_CTX - (prompt_tokens or 0) # the context window holds the prompt and the reply
263
+ larger = min(int(cap * config.ANALYSIS_CAP_STEP), room)
264
+ if raises >= config.ANALYSIS_CAP_RAISES or larger <= cap:
265
+ raise AnalysisFailed(kind, "reply_cut_off", attempts)
266
+ cap, changed_sampling, step = larger, False, "raised cap"
267
+ raises += 1
268
+ messages = first_messages
269
+ reason = f"the reply was cut off; asking again with room for {cap} tokens"
270
+ else:
271
+ if feedback_tries >= config.ANALYSIS_RETRIES:
272
+ raise AnalysisFailed(kind, "reply_invalid", attempts)
273
+ feedback_tries += 1
274
+ retries += 1
275
+ changed_sampling, step = True, "problems sent back"
276
+ messages = first_messages + [
277
+ {"role": "assistant", "content": content},
278
+ {"role": "user", "content": f"That reply was not valid ({'; '.join(problems[:3])[:300]}). "
279
+ "Reply again with one complete, valid JSON object that follows the schema."},
280
+ ]
281
+ reason = "the reply did not fit the schema; asking again"
282
+ on_retry(kind)
283
+ on_stage(f"retrying: {reason}")
284
+
285
+
286
+ def _too_long(exc: ollama.ResponseError) -> bool:
287
+ """True if Ollama refused an input because it does not fit the embedding model's context."""
288
+ message = str(exc).lower()
289
+ return exc.status_code == 400 and any(word in message for word in ("context", "too long", "exceed"))
290
+
291
+
292
+ def _split(text: str) -> tuple[str, str]:
293
+ """Cut a text in two, at a line break near the middle, or else at a space."""
294
+ lines = text.splitlines()
295
+ if len(lines) > 1:
296
+ running = 0
297
+ for index, line in enumerate(lines):
298
+ running += len(line) + 1
299
+ if running >= len(text) / 2:
300
+ break
301
+ cut = min(max(index + 1, 1), len(lines) - 1)
302
+ return "\n".join(lines[:cut]), "\n".join(lines[cut:])
303
+ middle = len(text) // 2
304
+ space = text.rfind(" ", 0, middle)
305
+ cut = space if space > 0 else middle
306
+ return text[:cut], text[cut:]
307
+
308
+
309
+ def _embed(client: ollama.Client, model: str, text: str) -> list[float]:
310
+ """One embedding request. If the embedding model's runner fails (status 500: usually the memory ran out because another
311
+ model is loaded beside it), every model is unloaded, which also resets the failed runner, and it is asked once more."""
312
+ request = {"model": model, "input": [text], "truncate": False, "options": config.EMBED_OPTIONS}
313
+ try:
314
+ return list(client.embed(**request).embeddings[0])
315
+ except ollama.ResponseError as exc:
316
+ if exc.status_code != 500:
317
+ raise
318
+ for name in other_models_running(client, []):
319
+ unload_model(client, name)
320
+ time.sleep(config.OLLAMA_RECOVERY_WAIT)
321
+ return list(client.embed(**request).embeddings[0])
322
+
323
+
324
+ def embed_search_text(client: ollama.Client, model: str, search_text: str) -> list[float]:
325
+ """The embedding of a text. Nothing is cut off: a text too long for the model's context is split in two, again and
326
+ again until the parts fit, and its vector is the average of the parts', each weighted by its length."""
327
+ try:
328
+ return _embed(client, model, search_text)
329
+ except ollama.ResponseError as exc:
330
+ if not _too_long(exc) or len(search_text) < 2:
331
+ raise
332
+ first, second = _split(search_text)
333
+ vectors = embed_search_text(client, model, first), embed_search_text(client, model, second)
334
+ weights = len(first), len(second)
335
+ return [(a * weights[0] + b * weights[1]) / sum(weights) for a, b in zip(*vectors)]
336
+
337
+
338
+ def understand_query(client: ollama.Client, model: str, query: str) -> QueryUnderstanding:
339
+ response = client.chat(
340
+ model=model,
341
+ messages=[
342
+ {"role": "system", "content": config.QUERY_PROMPT},
343
+ {"role": "user", "content": f"User query: {query}"},
344
+ ],
345
+ format=QueryUnderstanding.model_json_schema(),
346
+ options={**config.LLM_OPTIONS, "num_predict": config.QUERY_MAX_OUTPUT_TOKENS},
347
+ )
348
+ return QueryUnderstanding.model_validate_json(response.message.content)
@@ -0,0 +1,288 @@
1
+ """
2
+ imagent/vlm/calibration.py — Measure this computer with the vision model, so the settings that depend on it are measured, not guessed.
3
+
4
+ Run once by setup (and again when the vision model changed). It sends the model the real prompt and schema with a picture
5
+ made here (a scene drawn with Pillow, so nothing is downloaded or shipped), at smaller and smaller sizes, until one works:
6
+
7
+ * image_long_edge: the largest size, up to ``config.IMAGE_EDGE_CEILING``, that the computer handles (a trial that runs out
8
+ of memory, crashes or never answers goes on to the next smaller size);
9
+ * num_ctx: the smallest context window (a power of two) that holds the prompt, that image, and a reply with room to raise
10
+ the output cap once; a larger window only costs memory;
11
+ * use_mmap: whether the model is paged in from disk. Loading it fully is tried first when it fits in the free memory with
12
+ room to spare, paging otherwise; when a way fails (out of memory, or an Ollama that answers nothing in it) the other is tried;
13
+ * timeout_seconds: the time the largest first reply needs at the speed that was measured, times a margin;
14
+ * one_model_at_a_time: whether the embedding model runs while the vision model is still loaded (indexing does this for
15
+ every image). When it does not, indexing unloads the one before loading the other.
16
+
17
+ The trials are short (``config.CALIBRATION_TRIAL_TOKENS``), so one full description of the picture is asked for as well, with
18
+ the settings found and the steps indexing takes for a reply that is cut off or does not fit the schema: a model that cannot
19
+ write one is not fit for the job, whatever its speed.
20
+
21
+ When a size runs out of memory both ways (loaded fully and paged in), the person is asked first, through ``on_out_of_memory``, before
22
+ the picture is made smaller: other programs may be using the memory, and closing them can bring the larger sizes back.
23
+
24
+ ``calibrate`` raises ``NotPossible`` when not even the smallest size works, or the model cannot write a usable description:
25
+ the model does not run on this computer. ``NotPossible.model`` says which model it was.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import io
31
+ import math
32
+ import random
33
+ import time
34
+ from typing import Callable
35
+
36
+ import ollama
37
+ from PIL import Image, ImageDraw
38
+
39
+ from imagent import config
40
+ from imagent.image_processing.memory import available_memory
41
+ from imagent.vlm.analyzer import (
42
+ CUT_OFF, INVALID_REPLY, OUT_OF_MEMORY, AnalysisFailed, ServiceTrouble, _request_analysis, send_request,
43
+ )
44
+ from imagent.vlm.client import unload_model
45
+
46
+
47
+ class NotPossible(Exception):
48
+ """A model cannot run on this computer; the message says why, in plain words, and ``model`` is the one that cannot."""
49
+
50
+ def __init__(self, message: str, model: str | None = None):
51
+ super().__init__(message)
52
+ self.model = model
53
+
54
+
55
+ class NoAnswer(Exception):
56
+ """Ollama accepted the request and returned nothing: no text and no timings, and no error."""
57
+
58
+
59
+ def calibration_image(edge: int) -> bytes:
60
+ """A JPEG of a made-up scene whose longer side is ``edge``: a gradient, shapes of many sizes and some text.
61
+
62
+ What a picture shows does not change what it costs the model to read it; its size does."""
63
+ width, height = edge, max(edge * 3 // 4, 1)
64
+ rng = random.Random(edge) # the same picture for the same size
65
+ image = Image.new("RGB", (width, height))
66
+ draw = ImageDraw.Draw(image)
67
+ for y in range(height):
68
+ shade = 60 + 150 * y // height
69
+ draw.line([(0, y), (width, y)], fill=(shade, 120 + shade // 3, 255 - shade))
70
+ for _ in range(40):
71
+ x, y = rng.randrange(width), rng.randrange(height)
72
+ size = rng.randrange(max(edge // 40, 2), max(edge // 5, 4))
73
+ colour = tuple(rng.randrange(256) for _ in range(3))
74
+ box = [x, y, x + size, y + size]
75
+ draw.ellipse(box, fill=colour) if rng.random() < 0.5 else draw.rectangle(box, fill=colour)
76
+ for line in range(8):
77
+ draw.text((edge // 20, edge // 20 + line * max(edge // 16, 12)), f"Imagent test picture, line {line + 1}", fill=(255, 255, 255))
78
+ buffer = io.BytesIO()
79
+ image.save(buffer, format="JPEG", quality=config.IMAGE_JPEG_QUALITY)
80
+ return buffer.getvalue()
81
+
82
+
83
+ def _power_of_two_at_least(n: int) -> int:
84
+ return 1 << max(math.ceil(math.log2(max(n, 1))), 0)
85
+
86
+
87
+ def _model_context_limit(client: ollama.Client, model: str) -> int | None:
88
+ """The longest context the model was trained for, or None when Ollama does not say."""
89
+ try:
90
+ info = client.show(model).modelinfo or {}
91
+ except Exception:
92
+ return None
93
+ return next((int(value) for key, value in info.items() if key.endswith(".context_length") and isinstance(value, int)), None)
94
+
95
+
96
+ def _model_bytes(client: ollama.Client, model: str) -> int | None:
97
+ try:
98
+ return next((int(m.size) for m in client.list().models if m.model == model and m.size), None)
99
+ except Exception:
100
+ return None
101
+
102
+
103
+ def _embeds(client: ollama.Client, model: str, use_mmap: bool) -> bool:
104
+ """True if the embedding model answers a text about as long as a stored description, with the options indexing uses.
105
+
106
+ False when Ollama's reply is an error (the memory ran out while another model was loaded, or the model's runner failed);
107
+ any other trouble is raised."""
108
+ text = " ".join(["Imagent test description."] * (config.CALIBRATION_EMBED_TOKENS // 5)) # about five tokens a sentence
109
+ try:
110
+ client.embed(model=model, input=[text], truncate=False, options={**config.EMBED_OPTIONS, "use_mmap": use_mmap})
111
+ except ollama.ResponseError as exc:
112
+ if exc.status_code != 500:
113
+ raise
114
+ return False
115
+ return True
116
+
117
+
118
+ def _fits_with_vlm(client: ollama.Client, vlm_model: str, embedding_model: str, use_mmap: bool) -> bool:
119
+ """Whether the embedding model runs while the vision model is still loaded, as it does during indexing.
120
+
121
+ If it does not, both are unloaded (which also resets a runner that failed) and it is tried alone: False then means the two
122
+ do not fit together but each runs. Raises ``NotPossible`` when it does not run even alone."""
123
+ if _embeds(client, embedding_model, use_mmap):
124
+ return True
125
+ for name in (embedding_model, vlm_model):
126
+ unload_model(client, name)
127
+ time.sleep(config.OLLAMA_RECOVERY_WAIT)
128
+ if not _embeds(client, embedding_model, use_mmap):
129
+ raise NotPossible("did not work on this computer, even one after the other. A smaller model may.", embedding_model)
130
+ return False
131
+
132
+
133
+ def _seconds(nanoseconds) -> float:
134
+ return (nanoseconds or 0) / 1e9
135
+
136
+
137
+ def _trial(client: ollama.Client, model: str, edge: int, num_ctx: int, use_mmap: bool) -> tuple[dict, ollama.Client]:
138
+ """One real request at this size and context. Returns what Ollama measured, and the client to go on with.
139
+
140
+ Raises ``ServiceTrouble`` when the model could not be reached even after the steps for its kind of trouble, and
141
+ ``NoAnswer`` when it was reached and said nothing."""
142
+ request = {
143
+ "model": model,
144
+ "messages": [
145
+ {"role": "system", "content": config.ANALYSIS_PROMPT},
146
+ {"role": "user", "content": "Analyze this image.", "images": [calibration_image(edge)]},
147
+ ],
148
+ "format": config.ANALYSIS_SCHEMA,
149
+ "options": {**config.LLM_OPTIONS, "num_ctx": num_ctx, "use_mmap": use_mmap, "num_predict": config.CALIBRATION_TRIAL_TOKENS},
150
+ }
151
+ response, client = send_request(client, model, request, lambda kind, detail: None, lambda stage: None)
152
+ if not (response.message.content or "").strip() or not getattr(response, "eval_count", 0):
153
+ raise NoAnswer("Ollama answered with nothing.")
154
+ eval_seconds = _seconds(getattr(response, "eval_duration", 0))
155
+ return {
156
+ "prompt_tokens": int(getattr(response, "prompt_eval_count", 0) or 0),
157
+ "prefill_seconds": _seconds(getattr(response, "prompt_eval_duration", 0)),
158
+ "load_seconds": _seconds(getattr(response, "load_duration", 0)),
159
+ "tokens_per_second": (getattr(response, "eval_count", 0) or 0) / eval_seconds if eval_seconds else 0.0,
160
+ }, client
161
+
162
+
163
+ def _check_description(client: ollama.Client, model: str, edge: int) -> None:
164
+ """One full description of the test picture, asked for the way indexing asks, with the same steps for a reply that is cut off
165
+ or does not fit the schema. The settings to try are in place (``config.temporary_device_settings``).
166
+
167
+ Raises ``ServiceTrouble`` when the model could not be reached, and ``NotPossible`` when it did not give a usable reply."""
168
+ try:
169
+ _request_analysis(client, model, calibration_image(edge))
170
+ except AnalysisFailed as exc:
171
+ if exc.kind == CUT_OFF:
172
+ raise NotPossible("could not finish describing the test picture, even after trying again with different settings "
173
+ "and with more room. A smaller model may.", model) from exc
174
+ if exc.kind == INVALID_REPLY:
175
+ raise NotPossible("did not answer in the form Imagent needs (a JSON description that fits its schema), even after "
176
+ "it was told what was wrong. A different model may.", model) from exc
177
+ raise ServiceTrouble(exc.kind, exc.error_id, exc.params) from exc
178
+
179
+
180
+ def _fit_context(client: ollama.Client, model: str, edge: int, use_mmap: bool, limit: int | None,
181
+ start: int) -> tuple[int, dict, ollama.Client]: # raises ServiceTrouble, NoAnswer or NotPossible
182
+ """The smallest context that holds the prompt at this size, found by trying: Ollama cuts a prompt that does not fit.
183
+
184
+ Returns it with the trial's measurements. Raises ``ServiceTrouble`` if the trial fails, ``NotPossible`` if the
185
+ model's own limit is too small for this size."""
186
+ context = start
187
+ while True:
188
+ measured, client = _trial(client, model, edge, context, use_mmap)
189
+ needed = _power_of_two_at_least(measured["prompt_tokens"] + math.ceil(config.OLLAMA_MAX_OUTPUT_TOKENS * config.ANALYSIS_CAP_STEP))
190
+ if needed <= context:
191
+ return context, measured, client
192
+ if limit is not None and needed > limit:
193
+ raise NotPossible(f"At {edge} pixels the model needs a context of {needed}, more than it supports ({limit}).")
194
+ context = needed
195
+
196
+
197
+ def _prefers_mmap(size: int | None, available: int | None) -> bool:
198
+ """Paged in from disk only when the model would not fit in the free memory with headroom to spare; if that way fails, the other is tried."""
199
+ return bool(size and available and size > available * (1 - config.CALIBRATION_MEMORY_HEADROOM))
200
+
201
+
202
+ def calibrate(client: ollama.Client, model: str, embedding_model: str, say: Callable[[str], None] = print,
203
+ on_out_of_memory: Callable[[int, int | None, int | None], bool] | None = None) -> dict:
204
+ """Measure this computer with the vision model ``model``, and with the embedding model ``embedding_model`` beside it.
205
+
206
+ ``on_out_of_memory(edge, model_bytes, free_bytes)`` is called when that picture size ran out of memory both ways, before a smaller
207
+ one is tried (the memory free now is read again for it). It returns True to try again from the largest size, False to go on with
208
+ smaller ones, which is not asked again.
209
+
210
+ Returns the settings (see ``db.operations.set_device_settings``). Both models are unloaded afterwards. Raises
211
+ ``NotPossible`` (naming the model) when the vision model does not run here at any size worth sending or cannot write a usable
212
+ description, or the embedding model does not run at all."""
213
+ available = available_memory()
214
+ size = _model_bytes(client, model)
215
+ limit = _model_context_limit(client, model)
216
+ prefer_mmap = _prefers_mmap(size, available)
217
+ start = _power_of_two_at_least(config.OLLAMA_MAX_OUTPUT_TOKENS * 2)
218
+ trouble = ""
219
+ edge = config.IMAGE_EDGE_CEILING
220
+ smaller_chosen = False # the person chose to go on with smaller pictures, so they are not asked again
221
+ try:
222
+ while edge >= config.CALIBRATION_MIN_EDGE:
223
+ say(f"Trying pictures up to {edge} pixels…")
224
+ ran_out = False
225
+ for use_mmap in (prefer_mmap, not prefer_mmap):
226
+ try:
227
+ context, first, client = _fit_context(client, model, edge, use_mmap, limit, start)
228
+ except NotPossible as exc: # the model's own limit: another memory mode cannot help
229
+ trouble = str(exc)
230
+ break
231
+ except NoAnswer as exc:
232
+ trouble = str(exc)
233
+ continue
234
+ except ServiceTrouble as exc:
235
+ trouble = str(exc)
236
+ if exc.kind == OUT_OF_MEMORY:
237
+ ran_out = True
238
+ continue
239
+ break # no reply in time, or Ollama stopped: the other way would only wait as long again
240
+ # Measure again with the model loaded: how fast it writes once it is running. Ollama keeps what it worked
241
+ # out for an identical request, so a second reading of the prompt takes almost no time; the first one counts.
242
+ try:
243
+ warm, client = _trial(client, model, edge, context, use_mmap)
244
+ except (NoAnswer, ServiceTrouble) as exc:
245
+ trouble = str(exc)
246
+ break
247
+ speed = warm["tokens_per_second"] or first["tokens_per_second"]
248
+ if speed <= 0:
249
+ trouble = "The model did not report how fast it works."
250
+ break
251
+ prefill = max(first["prefill_seconds"], warm["prefill_seconds"])
252
+ first_reply = first["load_seconds"] + prefill + config.OLLAMA_MAX_OUTPUT_TOKENS / speed
253
+ timeout = math.ceil(first_reply * config.CALIBRATION_TIMEOUT_MARGIN)
254
+ say("Checking that the model writes a complete description…")
255
+ try:
256
+ with config.temporary_device_settings(num_ctx=context, use_mmap=use_mmap, image_long_edge=edge, timeout_seconds=timeout):
257
+ _check_description(client, model, edge)
258
+ except ServiceTrouble as exc: # the same steps as for a trial that does not get an answer
259
+ trouble = str(exc)
260
+ if exc.kind == OUT_OF_MEMORY:
261
+ ran_out = True
262
+ continue
263
+ break
264
+ say("Checking that the embedding model fits beside it…")
265
+ one_at_a_time = not _fits_with_vlm(client, model, embedding_model, use_mmap) # the vision model is still loaded from the checks above
266
+ return {
267
+ "num_ctx": context, "use_mmap": use_mmap, "image_long_edge": edge,
268
+ "timeout_seconds": timeout,
269
+ "one_model_at_a_time": one_at_a_time,
270
+ "measurements": {
271
+ "prompt_tokens": warm["prompt_tokens"], "prefill_seconds": round(prefill, 2),
272
+ "load_seconds": round(first["load_seconds"], 2), "tokens_per_second": round(speed, 2),
273
+ "model_bytes": size, "free_memory_bytes": available, "model_context_limit": limit,
274
+ },
275
+ }
276
+ if ran_out and on_out_of_memory and not smaller_chosen:
277
+ if on_out_of_memory(edge, size, available_memory()):
278
+ edge = config.IMAGE_EDGE_CEILING
279
+ available = available_memory() # programs may have been closed
280
+ prefer_mmap = _prefers_mmap(size, available)
281
+ continue
282
+ smaller_chosen = True
283
+ edge = int(edge * config.CALIBRATION_EDGE_STEP)
284
+ raise NotPossible(f"did not work on this computer at any picture size worth using"
285
+ f"{f' (last problem: {trouble})' if trouble else ''}. A smaller model may.", model)
286
+ finally:
287
+ unload_model(client, model)
288
+ unload_model(client, embedding_model)