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.
Attributes¶
LLM_CACHE_FORMAT_VERSION = 2
module-attribute
¶
T = TypeVar('T', bound=BaseModel)
module-attribute
¶
logger = logging.getLogger(__name__)
module-attribute
¶
Classes¶
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
Attributes¶
content = Field(description='Response text, already normalised.')
class-attribute
instance-attribute
¶
kwargs = Field(default_factory=dict, description='Invoke kwargs.')
class-attribute
instance-attribute
¶
prompt = Field(default='', description='Prompt that produced it.')
class-attribute
instance-attribute
¶
response_metadata = Field(default_factory=dict, description='Provider metadata, replayed on a hit.')
class-attribute
instance-attribute
¶
usage = Field(default=None, description='Token counts, replayed on a hit. None for older entries.')
class-attribute
instance-attribute
¶
LLMConfigurationError
¶
Bases: RuntimeError
The provider rejected the request itself, not this attempt at it.
A bad key, a model the account cannot reach, or a parameter value the model does not accept is a property of the deployment: identical for every content unit and every retry. Isolating it the way a bad render is isolated turns one configuration fault into N unit failures and a run that finishes, reports success, and writes nothing.
Deliberately not a sibling of :class:LLMRequestTimeoutError under a shared
base: an except (timeout, configuration) clause would re-issue a request
the provider has already said it will never accept.
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
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 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 | |
Attributes¶
budget_tracker = budget_tracker
class-attribute
instance-attribute
¶
cache = Field(default=None, exclude=True)
class-attribute
instance-attribute
¶
config = Field(default_factory=LLMConfig)
class-attribute
instance-attribute
¶
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. |
Methods:¶
__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
|
Any
|
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
|
Any
|
Additional keyword arguments for initialization. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
LLMTool |
'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
|
Any
|
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
|
Any
|
Additional keyword arguments for initialization. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
LLMTool |
'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
|
Any
|
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
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 789 | |
Functions:¶
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.