Coverage for collectra/tasks/llms.py: 100.00%
298 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
1"""Large Language Model (LLM) tasks for Collectra workflows, built on pydantic-ai.
3A task fills its prompt template with the texts and images it is given and
4asks a model for the answer: free text for one output node, or one field per
5node when there are several. It can call lookups (pipeline resources such as
6``EntityLookup``) before it answers.
8The model is named as ``provider:model`` (``anthropic:claude-sonnet-5-5``,
9``openai:gpt-5``, ``ollama:qwen2.5vl:7b``...). A bare name such as
10``claude-sonnet-5-5`` still works for the main hosted providers.
12Classes:
13 LLM: Task for Large Language Model inference operations
14"""
16__all__ = ["LLM", "model_id"]
18import asyncio
19import hashlib
20import json
21import os
22import re
23import threading
24from dataclasses import dataclass
25from functools import cached_property
26from typing import Any
28import yaml
29from dotenv import load_dotenv
30from pydantic import BaseModel, Field, create_model, field_validator
32from collectra.tasks.text_output import TextOutputTask
33from collectra.types.images import Image
34from collectra.types.texts import Text
36from ..logger import get_logger
38# pydantic-ai prints a banner the first time an agent runs; keep output clean.
39os.environ.setdefault("PYDANTIC_AI_NO_BANNER", "1")
41load_dotenv()
43logger = get_logger(__name__)
45DEFAULT_SYSTEM = "You are a helpful assistant."
46# How often the model may be asked to correct an answer that does not fit.
47RETRIES = 3
49# Bare model names that still work, by the provider that serves them.
50PROVIDERS = (
51 (("claude",), "anthropic"),
52 (("gpt", "o1", "o3", "o4", "chatgpt"), "openai"),
53 (("gemini", "gemma"), "google"),
54 (
55 (
56 "mistral",
57 "pixtral",
58 "codestral",
59 "ministral",
60 "magistral",
61 "devstral",
62 "open-mistral",
63 ),
64 "mistral",
65 ),
66 (("grok",), "xai"),
67)
70class LLMSetupError(RuntimeError):
71 """The task cannot run as configured; raised, not logged page by page."""
74class StructuredOutputUnsupported(LLMSetupError):
75 """The model cannot produce structured output (it has no tool calling)."""
78class ToolCallingUnsupported(LLMSetupError):
79 """The model cannot call tools, which a task with ``tools`` needs."""
82def model_id(model: str) -> str:
83 """``model`` as ``provider:model``, adding the provider to a bare name."""
84 if ":" in model:
85 return model
86 for prefixes, provider in PROVIDERS:
87 if model.startswith(prefixes):
88 return f"{provider}:{model}"
89 raise LLMSetupError(
90 f"Cannot tell which provider serves model {model!r}. Give it as "
91 "provider:model, for example anthropic:claude-sonnet-5-5, openai:gpt-5, "
92 "or ollama:qwen2.5vl:7b for a local model."
93 )
96def _as_text(cls, value):
97 """A field the model left out or filled with a non-string is still a string."""
98 if value is None:
99 return ""
100 return value if isinstance(value, str) else str(value)
103# Every model call runs on one background event loop, whichever thread asks:
104# pydantic-ai's HTTP clients are shared, and must stay on the loop they began on.
105_loop: asyncio.AbstractEventLoop | None = None
106_loop_lock = threading.Lock()
109def _run(coroutine):
110 """Run ``coroutine`` on the shared event loop and wait for its result."""
111 global _loop
112 with _loop_lock:
113 if _loop is None:
114 _loop = asyncio.new_event_loop()
115 threading.Thread(
116 target=_loop.run_forever, name="collectra-llm", daemon=True
117 ).start()
118 return asyncio.run_coroutine_threadsafe(coroutine, _loop).result()
121@dataclass
122class _Lookups:
123 """The lookups made in one conversation, to hold them to ``max_tool_calls``."""
125 made: int = 0
128def _limited_lookups(task: "LLM", tools: list):
129 """The task's lookups as tools, refused past the limit and never raising."""
130 from pydantic_ai import ModelRetry
131 from pydantic_ai.toolsets import FunctionToolset, WrapperToolset
133 class LimitedLookups(WrapperToolset):
134 async def call_tool(self, name, tool_args, ctx, tool):
135 lookups: _Lookups = ctx.deps
136 if lookups.made >= task.max_tool_calls:
137 return (
138 f"Lookup limit reached ({task.max_tool_calls}). "
139 "Give your final answer now, without further lookups."
140 )
141 lookups.made += 1
142 logger.info("Task '%s' called %s(%s)", task.name, name, tool_args)
143 try:
144 return str(await super().call_tool(name, tool_args, ctx, tool))
145 except ModelRetry:
146 raise
147 except Exception as error:
148 return f"Lookup failed: {error}"
150 return LimitedLookups(FunctionToolset(tools))
153class LLM(TextOutputTask):
154 """Task for Large Language Model inference operations.
156 Attributes:
157 name (str): Name identifier for the LLM task.
158 model (str): The model, as ``provider:model`` or a bare hosted name.
159 template (str | Path): Prompt template string or path to template file.
160 ``prompt`` is accepted as an alias, matching other tasks' option name.
161 preamble (str): Text put before the template.
162 system (str): The system prompt.
163 temperature (float | None): Sampling temperature for generation. Leave
164 unset (None) to use the model's own default.
165 max_tokens (int): Maximum number of tokens to generate.
166 cache (bool): Use prompt caching (default True). The fixed text before
167 the first image is cached too, so it is reused across pages.
168 batch_size (int): Number of prompts sent to the model concurrently when
169 the pipeline prefetches many files at once. 1 disables batching.
170 output: One node name, or several. With several, the model answers in
171 structured form: one string field per node, named after the node,
172 and every node gets a Text (empty when the model found nothing).
173 The prompt template is where each field is described.
174 tools: Names of pipeline resources (such as ``EntityLookup``) the model
175 may call before answering. A task with tools needs a model that
176 supports tool calling. With several outputs the answer is given by
177 calling one more tool, whose fields are the outputs.
178 max_tool_calls (int): The most lookups the model may make per prompt.
179 """
181 def __init__(self, name: str, model: str, **kwargs):
182 super().__init__(name, **kwargs)
183 if kwargs.get("template") and kwargs.get("prompt"):
184 raise ValueError(
185 f"LLM task {name!r} sets both template and prompt; use only one"
186 )
187 self.template: str = kwargs.get("template") or kwargs.get("prompt", "")
188 self.preamble: str = kwargs.get("preamble", "")
189 # None leaves the model at its own default: some models reject the setting.
190 self.temperature = kwargs.get("temperature")
191 self.max_tokens = kwargs.get("max_tokens", None)
192 self.cache = bool(kwargs.get("cache", True))
193 self.model = model
194 self.batch_size = int(self.batch_size) # the Task base requires >= 1
195 self._prefetched: dict[str, list] = {}
196 if len(self.output_names) != len(set(self.output_names)):
197 raise ValueError(f"LLM task {name!r} lists the same output more than once")
198 tools = kwargs.get("tools")
199 self.tools = (
200 [tools] if isinstance(tools, str) else [str(t) for t in tools or []]
201 )
202 self.max_tool_calls = int(kwargs.get("max_tool_calls", 5))
203 if self.max_tool_calls < 1:
204 raise ValueError(f"LLM task {name!r} needs max_tool_calls >= 1")
206 self.system: str = kwargs.get("system", "") or DEFAULT_SYSTEM
207 # The system prompt, then (once a prompt is built) the user's content.
208 self.messages: list = [self.system]
210 @cached_property
211 def llm(self):
212 """The pydantic-ai model, loaded when it is first needed."""
213 try:
214 from pydantic_ai.models import infer_model
215 except ModuleNotFoundError as error:
216 if error.name != "pydantic_ai":
217 raise
218 raise ImportError(
219 'LLM execution requires optional dependencies. Install with: pip install "collectra[ml]"'
220 ) from error
221 return infer_model(model_id(self.model))
223 @property
224 def output_names(self) -> list[str]:
225 """The output node names, whether given as one name or a list."""
226 output = getattr(self, "output", None)
227 if output is None:
228 return []
229 return [output] if isinstance(output, str) else list(output)
231 @property
232 def is_structured(self) -> bool:
233 """Several output nodes mean the model must answer field by field."""
234 return len(self.output_names) > 1
236 @cached_property
237 def output_model(self) -> type[BaseModel]:
238 """One optional string field per output node, named after the node.
240 Fields are positional (``field_0``...) with the node name as alias, so
241 any node name works, even ones pydantic would reject as an attribute.
242 """
243 fields = {
244 f"field_{index}": (str, Field(default="", alias=name))
245 for index, name in enumerate(self.output_names)
246 }
247 return create_model(
248 "LLMOutputs",
249 __doc__=(
250 "Fill in every field from the input. Leave a field as an empty "
251 "string when the input does not contain it."
252 ),
253 __validators__={"as_text": field_validator("*", mode="before")(_as_text)},
254 **fields,
255 )
257 def model_settings(self) -> dict[str, Any]:
258 """The settings sent with every request: only those that were set."""
259 settings: dict[str, Any] = {}
260 if self.temperature is not None:
261 settings["temperature"] = self.temperature
262 if self.max_tokens is not None:
263 settings["max_tokens"] = self.max_tokens
264 settings["cache"] = self.cache
265 return settings
267 @cached_property
268 def agent(self):
269 """The pydantic-ai agent that asks the model, with the task's tools."""
270 from pydantic_ai import Agent, ToolOutput
272 model = self.llm
273 supports_tools = model.profile.get("supports_tools", True)
274 if self.tools and not supports_tools:
275 raise ToolCallingUnsupported(
276 f"LLM task {self.name!r} uses tools, but model {self.model!r} "
277 "does not support tool calling. Use a model that does, or remove "
278 "the tools."
279 )
280 if self.is_structured and not supports_tools:
281 raise StructuredOutputUnsupported(
282 f"LLM task {self.name!r} has {len(self.output_names)} outputs, which "
283 f"needs structured output, but model {self.model!r} does not support "
284 "tool calling. Use a model that does, or give the task one output."
285 )
286 toolsets = []
287 if self.tools:
288 toolsets.append(_limited_lookups(self, list(self._tool_objects().values())))
289 # With several outputs the answer itself is a tool call: the model is
290 # free to look things up first and submits when it is done.
291 output_type = (
292 ToolOutput(self.output_model, name=self.output_model.__name__)
293 if self.is_structured
294 else str
295 )
296 return Agent(
297 model,
298 output_type=output_type,
299 instructions=self.system,
300 toolsets=toolsets,
301 deps_type=_Lookups,
302 model_settings=self.model_settings(),
303 retries=RETRIES,
304 # An answer ends the conversation, even with lookups in the same reply.
305 end_strategy="early",
306 )
308 def validate_resources(self, resources: dict[str, Any]) -> None:
309 """Fail early, when the pipeline connects, if a named tool does not exist."""
310 for tool in self.tools:
311 if tool not in resources:
312 raise ValueError(
313 f"Task {self.name!r} uses unknown tool {tool!r}. "
314 f"Available tools: {', '.join(sorted(resources)) or 'none'}"
315 )
317 def _tool_objects(self) -> dict[str, Any]:
318 """The task's tools by name, taken from the pipeline's resources."""
319 if self.pipeline is None:
320 raise LLMSetupError(
321 f"LLM task {self.name!r} uses tools but is not part of a pipeline"
322 )
323 tools = [self.pipeline.resource(name).as_tool() for name in self.tools]
324 return {tool.name: tool for tool in tools}
326 # --- the prompt ---------------------------------------------------------------
328 def get_pattern_matches(self) -> tuple:
329 prompt = f"{self.preamble}\n\n{self.template}".strip()
330 if not prompt:
331 raise ValueError(
332 f"LLM task {self.name!r} has no prompt; set template: (or prompt:) "
333 "in its pipeline.yaml entry"
334 )
335 pattern = r"\{(.*?)\}"
336 return prompt, pattern
338 def image_content(self, image: Image) -> dict:
339 """The image as a content block, in a format models accept."""
340 return {"type": "image", "data": image.load(), "mime_type": image.mime()}
342 def _add_content(self, value: Image | Text) -> dict:
343 if isinstance(value, Image):
344 return self.image_content(value)
345 return self._add_text(value())
347 def _add_text(self, text: str) -> dict:
348 text = (
349 "''" if len(text.strip()) == 0 else text.strip()
350 ) # Avoid empty string issues in some LLMs
351 return {"type": "text", "text": text}
353 def pre_run(self) -> tuple:
354 self.messages = self.messages[:1] # Reset to the system prompt
355 prompt, pattern = self.get_pattern_matches()
356 return prompt, pattern
358 def check_inputs(self, *args: Text | Image) -> None:
359 """Validate that the messages are not longer than the expected number of inputs."""
360 residual_inputs = len(args)
361 if len(self.messages) != 2:
362 raise ValueError("Expected one system message and one human message.")
363 for content in self.messages[1]:
364 if isinstance(content, dict) and (
365 content.get("type") == "image" or content.get("type") == "text"
366 ):
367 residual_inputs -= 1
368 if residual_inputs > 0:
369 raise ValueError("Number of inputs does not match the expected count")
371 def replace_inputs(
372 self, pattern: str, prompt: str, *args: Text | Image, **kwargs
373 ) -> list[str | dict]:
374 messages: list[str | dict] = list()
375 while re.search(pattern, prompt):
376 match = next(re.finditer(pattern, prompt))
377 start, end = match.span()
378 item = match[1].strip()
379 replaced = False
380 if prompt[:start]:
381 messages.append(self._add_text(prompt[:start]))
382 for arg in args:
383 key = arg.name
384 if key == item:
385 messages.append(self._add_content(arg))
386 replaced = True
387 break
388 if item == "entities" and kwargs.get("entities", None):
389 replaced = True
390 messages.append(self._add_text(kwargs["entities"]))
391 if not replaced:
392 messages.append(
393 self._add_text(f"No content provided for {item}. Ignore this part.")
394 )
395 prompt = prompt[end:].strip()
397 if prompt:
398 messages.append(self._add_text(prompt))
400 return messages
402 def _build_messages(self, args: tuple) -> list[str | dict]:
403 """Fill the prompt template for ``args``, leaving ``self.messages`` ready to send."""
404 prompt, pattern = self.pre_run()
405 content = self.replace_inputs(pattern, prompt, *args)
406 self.messages.append(content)
407 self.check_inputs(*args)
408 return content
410 def _user_content(self, content: list[dict]) -> list:
411 """The prompt's blocks as pydantic-ai content, in the same order.
413 With caching on, a cache point goes just before the first image, so the
414 fixed text of the template ahead of it is reused from page to page.
415 """
416 from pydantic_ai.messages import BinaryContent, CachePoint
418 parts: list = []
419 for block in content:
420 if block.get("type") == "image":
421 if self.cache and parts and all(isinstance(p, str) for p in parts):
422 parts.append(CachePoint())
423 parts.append(
424 BinaryContent(data=block["data"], media_type=block["mime_type"])
425 )
426 else:
427 parts.append(block["text"])
428 return parts
430 @staticmethod
431 def _cache_key(content: list[str | dict]) -> str:
432 """Identify a prompt by its content (images are hashed, not stored)."""
434 def digest(value: bytes) -> str: # only an image's bytes need this
435 return hashlib.sha256(value).hexdigest()
437 return hashlib.sha256(
438 json.dumps(content, sort_keys=True, default=digest).encode()
439 ).hexdigest()
441 # --- asking the model -------------------------------------------------------------
443 async def _ask(self, content: list[dict]):
444 """One conversation with the model for ``content``; its run result."""
445 from pydantic_ai import UsageLimits
446 from pydantic_ai.exceptions import UnexpectedModelBehavior, UsageLimitExceeded
448 lookups = _Lookups()
449 # Room for every allowed lookup, then a few turns to give the answer.
450 limits = UsageLimits(request_limit=self.max_tool_calls + 3)
451 try:
452 return await self.agent.run(
453 self._user_content(content), deps=lookups, usage_limits=limits
454 )
455 except UsageLimitExceeded as error:
456 raise RuntimeError(
457 f"LLM task {self.name!r}: the model did not give a final answer "
458 f"after {lookups.made} lookups"
459 ) from error
460 except UnexpectedModelBehavior as error:
461 raise RuntimeError(
462 f"LLM task {self.name!r}: the model did not give a final answer "
463 f"({error})"
464 ) from error
466 async def _ask_all(self, contents: list[list[dict]]) -> list:
467 """Ask for every prompt, ``batch_size`` at a time; failures are returned."""
468 slots = asyncio.Semaphore(self.batch_size)
470 async def one(content):
471 async with slots:
472 return await self._ask(content)
474 return await asyncio.gather(*(one(c) for c in contents), return_exceptions=True)
476 def prefetch(self, entries: list[list]) -> None:
477 """Send the prompts for many entries to the model, ``batch_size`` at a time.
479 Results are cached by prompt content and consumed by ``run``, so usage
480 is recorded against the file that is actually being processed. A prompt
481 that fails here is simply left for ``run`` to retry on its own.
482 """
483 self._prefetched = {}
484 prompts: list[tuple[str, list]] = []
485 for entry in entries:
486 if not entry:
487 continue
488 try:
489 content = self._build_messages(tuple(entry))
490 except Exception as e:
491 logger.warning(
492 "LLM task '%s' could not prepare an entry: %s", self.name, e
493 )
494 continue
495 prompts.append((self._cache_key(content), content))
496 if not prompts:
497 return
498 self.agent # a setup problem is raised now, not logged for every prompt
499 results = _run(self._ask_all([content for _, content in prompts]))
500 for (key, _), result in zip(prompts, results):
501 if isinstance(result, Exception):
502 logger.warning(
503 "LLM task '%s' prompt failed, will retry alone: %s",
504 self.name,
505 result,
506 )
507 continue
508 self._prefetched.setdefault(key, []).append(result)
510 def clear_prefetch(self) -> None:
511 self._prefetched = {}
513 def _fields(self, parsed: BaseModel) -> dict[str, str]:
514 """The structured answer as ``{node name: text}``, in output order."""
515 values = {}
516 for index, name in enumerate(self.output_names):
517 value = getattr(parsed, f"field_{index}")
518 values[name] = "" if value in ('""', "''") else value.strip()
519 return values
521 def _record_usage(self, usage) -> None:
522 """Add one conversation's usage to the run's ledger and the usage file.
524 ``input_tokens`` includes the tokens read from and written to the cache.
525 """
526 if self.context.usage_ledger is not None:
527 self.context.usage_ledger.add(self.name, self.model, usage)
528 if not self.context.usage_file:
529 return
530 usage_file = self.context.usage_file
531 data = {
532 f"{self.name}": {
533 "input_tokens": usage.input_tokens,
534 "output_tokens": usage.output_tokens,
535 "total_tokens": usage.input_tokens + usage.output_tokens,
536 "cache_read_tokens": usage.cache_read_tokens,
537 "cache_write_tokens": usage.cache_write_tokens,
538 "requests": usage.requests,
539 }
540 }
541 # In US dollars; left out when the model's prices are not known.
542 if usage.cost is not None:
543 data[self.name]["cost_usd"] = float(usage.cost)
544 old_data = {}
545 if usage_file.exists():
546 with open(usage_file, "r") as f:
547 old_data = yaml.safe_load(f) or dict()
548 for key, value in old_data.items():
549 if key not in data:
550 data[key] = value
551 else:
552 for item, item_value in value.items():
553 data[key][item] = data.get(key, {}).get(item, 0) + item_value
554 if "cost_usd" in data[self.name]:
555 data[self.name]["cost_usd"] = round(data[self.name]["cost_usd"], 6)
556 usage_file.parent.mkdir(parents=True, exist_ok=True)
557 with open(usage_file, "w") as f:
558 yaml.dump(data, f)
560 def invoke(self, response=None) -> str | dict[str, str]:
561 """Ask the model (unless ``response`` is already in hand) and read the reply.
563 Returns text for a single output, or ``{node name: text}`` for several.
564 """
565 if response is None:
566 self.agent # a setup problem is raised here, in the caller's thread
567 response = _run(self._ask(self.messages[1]))
568 self._record_usage(response.usage)
569 if self.is_structured:
570 return self._fields(response.output)
571 output = response.output
572 return "" if output in ('""', "''") else output.strip()
574 def run(self, *args: Text | Image) -> Text | list[Text] | None:
575 """Fill the template with ``args``, ask the model and return its answer.
577 A failed call or an unreadable reply raises: the pipeline then records
578 the failure and saves no output, so the next run tries again. Returning
579 nothing would be saved as "found nothing" and never retried.
580 """
581 content = self._build_messages(args)
583 cached = self._prefetched.get(self._cache_key(content))
584 response = self.invoke(cached.pop(0) if cached else None)
586 if self.is_structured:
587 return [
588 self.text_output(value, name=node) for node, value in response.items()
589 ]
590 return self.text_output(response)