ontocast.tool.llm¶
Language Model (LLM) integration tool for OntoCast.
This module provides integration with various language models through LangChain, supporting OpenAI, Ollama, Anthropic (Claude), and Google (Gemini) providers. It enables text generation and structured data extraction capabilities with optional caching support.
Cache Usage
The LLM tool supports caching of responses to avoid redundant API calls. Caching uses a shared Cacher instance that manages cache directories for all tools. The cache directory is managed by the shared Cacher class and follows these rules:
from ontocast.tool.llm import LLMTool
from ontocast.config import LLMConfig
from ontocast.tool.cache import Cacher
# Create shared cache instance
shared_cache = Cacher()
# Create LLM tool with shared cache
llm_tool = await LLMTool.acreate(
config=LLMConfig(...),
cache=shared_cache
)
Default cache locations: - Tests: .test_cache/llm/ in the current working directory - Windows: %USERPROFILE%AppDataLocalontocastllm - Unix/Linux: ~/.cache/ontocast/llm/ (or $XDG_CACHE_HOME/ontocast/llm/)
Cache files are stored as JSON files with filenames based on SHA256 hashes of the prompt and LLM configuration. This ensures that identical prompts with the same configuration will return cached responses.
The shared Cacher automatically manages subdirectories for different tools, ensuring organized cache storage while maintaining a single cache instance.
CachedResponse
¶
Bases: BaseModel
A stored LLM response.
cache_format_version in the key guarantees entries were written by this
version of the code, so the shape is known rather than sniffed.
Source code in ontocast/tool/llm.py
LLMRequestTimeoutError
¶
Bases: RuntimeError
A provider call exceeded LLM_REQUEST_TIMEOUT_SECONDS.
Deliberately not an :class:asyncio.TimeoutError: the unit loops catch
Exception to fail a single unit gracefully, and a cancellation-flavoured
error escaping asyncio.gather would take the whole fan-out down with it.
Source code in ontocast/tool/llm.py
LLMTool
¶
Bases: Tool
Tool for interacting with language models.
This class provides a unified interface for working with different language model providers (OpenAI, Ollama, Anthropic, Google) through LangChain. It supports both synchronous and asynchronous operations.
Attributes:
| Name | Type | Description |
|---|---|---|
config |
LLMConfig
|
LLMConfig object containing all LLM settings. |
cache |
Any
|
Cacher instance for caching LLM responses. |
Source code in ontocast/tool/llm.py
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 | |
llm
property
¶
Get the underlying language model instance.
Returns:
| Name | Type | Description |
|---|---|---|
BaseChatModel |
BaseChatModel
|
The configured language model. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the LLM has not been properly initialized. |
__call__(*args, **kwds)
async
¶
__init__(cache=None, budget_tracker=None, **kwargs)
¶
Initialize the LLM tool.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cache
|
Cacher | None
|
Optional shared Cacher instance. If None, creates a new one. |
None
|
budget_tracker
|
Any
|
Optional budget tracker instance for usage statistics. |
None
|
**kwargs
|
Additional keyword arguments passed to the parent class. |
{}
|
Source code in ontocast/tool/llm.py
acall(*args, **kwds)
async
¶
acreate(config, cache=None, budget_tracker=None, **kwargs)
async
classmethod
¶
Create a new LLM tool instance asynchronously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
LLMConfig
|
LLMConfig object containing LLM settings. |
required |
cache
|
Cacher | None
|
Optional shared Cacher instance. |
None
|
budget_tracker
|
Any
|
Optional budget tracker instance for usage statistics. |
None
|
**kwargs
|
Additional keyword arguments for initialization. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
LLMTool |
A new instance of the LLM tool. |
Source code in ontocast/tool/llm.py
aget_cache_stats()
async
¶
Async :meth:get_cache_stats, with the directory walk off the loop.
Source code in ontocast/tool/llm.py
complete(prompt, **kwargs)
async
¶
Generate a completion for the given prompt.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt
|
str
|
The prompt to complete. |
required |
**kwargs
|
Forwarded to the provider and folded into the cache key. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The response text, normalised from provider content blocks. |
Source code in ontocast/tool/llm.py
create(config, cache=None, budget_tracker=None, **kwargs)
classmethod
¶
Create a new LLM tool instance synchronously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
LLMConfig
|
LLMConfig object containing LLM settings. |
required |
cache
|
Cacher | None
|
Optional shared Cacher instance. |
None
|
budget_tracker
|
Any
|
Optional budget tracker instance for usage statistics. |
None
|
**kwargs
|
Additional keyword arguments for initialization. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
LLMTool |
A new instance of the LLM tool. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If called from inside a running event loop; use
:meth: |
Source code in ontocast/tool/llm.py
extract(prompt, output_schema, **kwargs)
async
¶
Extract structured data from the prompt according to a schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt
|
str
|
The prompt describing what to extract. |
required |
output_schema
|
Type[T]
|
Pydantic model the response is parsed into. |
required |
**kwargs
|
Forwarded to the provider and folded into the cache key. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
T |
T
|
The parsed model instance. |
Source code in ontocast/tool/llm.py
get_cache_stats(include_disk=True)
¶
Return in-memory hit/miss counters and, optionally, on-disk file stats.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include_disk
|
bool
|
Whether to walk the cache directory. The walk stats
every file, so callers on a hot path (or on an event loop)
should pass False or use :meth: |
True
|
Source code in ontocast/tool/llm.py
record_span(name, seconds)
¶
Charge a latency span to this call's budget tracker.
Uses the same context-local tracker as usage accounting, so per-unit
attribution under asyncio.gather is correct for free, and falls back
to this tool's own tracker for direct library use. Callers without an
:class:LLMTool instance should use :func:record_active_span.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Duration key, e.g. |
required |
seconds
|
float
|
Elapsed seconds to accumulate. |
required |
Source code in ontocast/tool/llm.py
setup()
async
¶
Set up the language model based on the configured provider.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the provider is not supported. |
Source code in ontocast/tool/llm.py
llm_cache_config(config, **extra)
¶
Cache-key inputs for a given LLM configuration.
Every field here changes the provider's response, so it must take part in
the key. This is the single definition: :class:LLMTool and the batch
import in :mod:ontocast.tool.llm_batch both call it, and any divergence
between them silently produces entries that are written but never read.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
LLMConfig
|
The LLM configuration a response would be produced under. |
required |
**extra
|
Any
|
Additional discriminators (e.g. an output schema name). |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict[str, str | int | float | bool | None]
|
JSON-serialisable mapping used as the cache key's config part. |
Source code in ontocast/tool/llm.py
record_active_count(name, n=1)
¶
Charge a named event count to the running task's budget tracker, if any.
The counting sibling of :func:record_active_span, and a no-op when no
tracker is bound -- so the parse layer can report how often it repaired or
abandoned a response without holding an :class:LLMTool, and test stubs
that substitute a plain callable keep working.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Counter key, e.g. |
required |
n
|
int
|
Amount to add. |
1
|
Source code in ontocast/tool/llm.py
record_active_span(name, seconds)
¶
Charge a latency span to the running task's budget tracker, if any.
A no-op when no tracker is bound. This reads the context variable directly
rather than going through an :class:LLMTool, so stages that fan out
around the LLM (e.g. chunk section classification) can report queue waits
without holding a real tool instance -- which also keeps test stubs that
substitute a plain callable for the LLM working.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Duration key, e.g. |
required |
seconds
|
float
|
Elapsed seconds to accumulate. |
required |
Source code in ontocast/tool/llm.py
token_usage_from_openai_payload(payload)
¶
Parse an OpenAI-shaped usage object into a :class:TokenUsage.
Shared with the Batch-API prefill in :mod:ontocast.tool.llm_batch, whose
JSONL carries the same object under response.body.usage -- so a
prewarmed cache entry accounts for tokens exactly like a live one.
Source code in ontocast/tool/llm.py
use_budget_tracker(budget_tracker)
¶
Charge LLM usage inside this block to budget_tracker.