Core API¶
llm_base¶
Generic LLM interface.
A single BaseLLM describes what every model backend must be able to do, and each
provider specializes it. Three methods form the public surface and are meant to be overloaded:
BaseLLM.from_config()– build an instance from a YAML configuration file.BaseLLM.query()– connect to the model and send a message (optionally with images).BaseLLM.prepare()– load few-shot examples from a folder (not implemented yet).
Generation parameters are not hard-coded here. Whatever sits under LLM_CONFIG in the YAML
file is forwarded to the provider request as-is, so a model that wants max_completion_tokens
and one that wants max_tokens are both expressed by their own configuration file rather than
by a flag in the code. As an example, consider a configuration file like this
LLM_VERSION : "gpt-5.2-chat"
API_KEY_NAME : "AZURE_OPENAI_API_KEY"
ENDPOINT_ENV : "AZURE_OPENAI_ENDPOINT"
API_VERSION : "2024-12-01-preview"
SYSTEM_FINGERPRINT : "None"
LLM_CONFIG:
max_completion_tokens: 16384
seed: 42
- llm_base.configure_env(env_path=None, load=True)[source]¶
Choose the environment file the LLM layer reads, for the rest of the process.
Lets an entry point propagate its own choice:
samgpt.py --env-file other.envcalls this so the backends readother.envtoo, rather than silently falling back to the project root’s.envand picking up credentials the caller meant to replace.--no-env-filecalls it withload=False, which honours “use the shell environment and nothing else” everywhere rather than only in the entry point.- Parameters:
env_path (str or Path, optional) – File to read.
Nonerestores the default, the.envnext to this module.load (bool, optional) – When False, no environment file is read at all and
env_pathis ignored.
- Return type:
None
- llm_base.default_env_path()[source]¶
Return the environment file path the LLM layer reads.
Whatever
configure_env()was given, or else the.envin the directory containing this module.- Returns:
Path of the configured file, or of the
.envin the directory containing this module.- Return type:
str
- llm_base.load_llm_env(env_path=None)[source]¶
Load LLM environment variables and return the path used.
- Parameters:
env_path (Optional[str], optional) – Environment file to read. Defaults to
default_env_path().- Returns:
Path of the environment file that was loaded, or None when
configure_env()disabled reading one and no explicit path was given.- Return type:
Optional[str]
- llm_base.resolve_config_value(config, key, default=None, env_key=None, allow_bare_env=False)[source]¶
Resolve a config value, allowing KEY_ENV, ${ENV_VAR}, or bare env names.
- Parameters:
config (Dict[str, Any]) – Parsed configuration.
key (str) – Configuration key to resolve.
default (Any, optional) – Value returned when the key is absent.
env_key (Optional[str], optional) – Companion key naming an environment variable. Defaults to
"<key>_ENV".allow_bare_env (bool, optional) – Read a plain upper-case value as an environment variable name.
- Returns:
The configured value, read from the environment when the configuration points to it.
- Return type:
Any
- Raises:
ValueError – If a referenced environment variable is unset or empty.
- llm_base.load_config_file(config_file)[source]¶
Load a YAML configuration file and return it as a dictionary.
- Parameters:
config_file (Union[str, Path]) – Path to the YAML configuration file.
- Returns:
Parsed configuration.
- Return type:
Dict[str, Any]
- Raises:
FileNotFoundError – If the file does not exist or is not a YAML file.
ValueError – If the file does not contain a mapping.
- llm_base.normalize_messages(messages, disable_system=False)[source]¶
Flatten messages into plain-text roles.
Used by local backends, which render the conversation into a single prompt and therefore cannot carry structured content.
- Parameters:
messages (List[Dict[str, Any]]) – Messages in the shared chat format.
disable_system (bool, optional) – Rewrite every
systemmessage as auser/assistantpair, for chat templates without a system role.
- Returns:
Messages whose content is always a string.
- Return type:
List[Dict[str, str]]
- llm_base.encode_image(image, image_format='PNG')[source]¶
Encode an image as base64.
- Parameters:
image (ImageInput) – A
PIL.Image.Image, or the path of an image file.image_format (str, optional) – Format used when re-encoding an in-memory image.
- Returns:
The MIME type and the base64-encoded payload.
- Return type:
Tuple[str, str]
- Raises:
TypeError – If the image is neither a PIL image nor a readable path.
FileNotFoundError – If a path is given but does not exist.
- llm_base.image_data_url(image, image_format='PNG')[source]¶
Return an image encoded as a
data:URL.- Parameters:
image (ImageInput) – A
PIL.Image.Image, or the path of an image file.image_format (str, optional) – Format used when re-encoding an in-memory image.
- Returns:
The image as a
data:<mime>;base64,<payload>URL.- Return type:
str
- class llm_base.BaseLLM(model, params=None, config=None, config_file=None, examples=None)[source]¶
Bases:
ABCCommon interface shared by every LLM backend.
Subclasses describe a provider by setting the class attributes below and by implementing the connection hooks. The three public methods (
from_config(),query(),prepare()) already work for any backend that implements those hooks, and can be overloaded when a provider needs something different.- Parameters:
model (str)
params (Dict[str, Any] | None)
config (Dict[str, Any] | None)
config_file (str | Path | None)
examples (str | Path | None)
- PROVIDER¶
Slug used by the factory to select this backend.
- Type:
str
- DEFAULT_PARAMS¶
Request parameters applied when the config omits them.
- Type:
Dict[str, Any]
- PARAM_ALIASES¶
Renames applied to
LLM_CONFIGkeys, so that a config written with a generic name still reaches the provider under the name it expects.- Type:
Dict[str, str]
- NON_REQUEST_PARAMS¶
LLM_CONFIGkeys consumed by the backend itself and never forwarded to the provider request.- Type:
Tuple[str, …]
- classmethod from_config(config_file, examples=None, **overrides)[source]¶
Instantiate the backend from a YAML configuration file.
The configuration file carries everything the model needs: its name, how to reach it, and the request parameters under
LLM_CONFIG. Those parameters are forwarded verbatim, so a model expectingmax_completion_tokensand one expectingmax_tokensdiffer only by their configuration file.- Parameters:
config_file (Union[str, Path]) – Path to the YAML configuration file.
examples (Optional[Union[str, Path]], optional) – Folder with few-shot examples.
**overrides (Any) – Values overriding the configuration, e.g.
model="..."orparams={"temperature": 0.2}(merged on top ofLLM_CONFIG).
- Returns:
A configured backend instance.
- Return type:
- Raises:
FileNotFoundError – If the configuration file does not exist or is not YAML.
ValueError – If the configuration does not name a model.
- static model_from_config(config)[source]¶
Return the model name declared by a configuration dictionary.
- Parameters:
config (Dict[str, Any]) – Parsed configuration.
- Returns:
The first of
LLM_VERSION,MODELandMODEL_NAMEthat is set, orNone.- Return type:
Optional[str]
- param(name, default=None)[source]¶
Return a configured parameter, or
defaultwhen it is not set.- Parameters:
name (str) – Parameter name.
default (Any, optional) – Value returned when the parameter is missing.
- Returns:
The configured value, or
default.- Return type:
Any
- request_params()[source]¶
Return the parameters to forward to the provider request.
- Returns:
The configured parameters without the
NON_REQUEST_PARAMSkeys.- Return type:
Dict[str, Any]
- _setup()[source]¶
Read provider-specific keys from
self.config. Hook for subclasses.- Return type:
None
- connect()[source]¶
Return the live connection to the model, creating it on first use.
For API backends this builds the SDK client; for local backends it loads the model. The result is cached, so repeated
query()calls reuse the same connection.- Returns:
The provider client or the loaded local model handle.
- Return type:
Any
- abstract _create_client()[source]¶
Create the provider client (or load the local model).
- Returns:
The provider client or the loaded local model handle.
- Return type:
Any
- abstract _send(client, messages)[source]¶
Send a prepared message list and return the raw provider response.
- Parameters:
client (Any) – The connection returned by
connect().messages (List[Dict[str, Any]]) – Messages in the shared chat format.
- Returns:
The raw provider response.
- Return type:
Any
- abstract _extract_text(response)[source]¶
Extract the assistant text from a raw provider response.
- Parameters:
response (Any) – Raw provider response.
- Returns:
The assistant answer.
- Return type:
str
- _extract_usage(response)[source]¶
Extract token usage from a raw provider response.
- Parameters:
response (Any) – Raw provider response.
- Returns:
Keys
prompt_tokensandcompletion_tokens; zeros when the provider does not report usage.- Return type:
Dict[str, int]
- close()[source]¶
Release the connection. Backends holding real resources should override this.
- Return type:
None
- query(message, images=None, role='user', max_retry=3, end_when_error=False, keep_history=False)[source]¶
Connect to the model and send a query.
- Parameters:
message (str) – The message sent to the model.
images (Optional[Sequence[ImageInput]], optional) – Images to send along with the message, as
PIL.Image.Imageinstances (paths are also accepted). Only backends withSUPPORTS_IMAGESset accept them.role (str, optional) – Role of the message. Defaults to
"user".max_retry (int, optional) – How many times to attempt the request before giving up.
end_when_error (bool, optional) – Stop at the first failure instead of retrying.
keep_history (bool, optional) – Append the exchange to
messages, so the next query continues the same conversation.
- Returns:
Whether the request succeeded, and the model’s answer.
- Return type:
Tuple[bool, str]
- Raises:
NotImplementedError – If images are given to a text-only backend.
- build_messages(message, images=None, role='user')[source]¶
Build the full message list for a query, including examples and system message.
- Parameters:
message (str) – The message sent to the model.
images (Optional[Sequence[ImageInput]], optional) – Images to attach to the message.
role (str, optional) – Role of the message.
- Returns:
Messages in the shared chat format.
- Return type:
List[Dict[str, Any]]
- build_content(message, images=None)[source]¶
Build the content of a single message.
Without images the content is the plain string. With images it becomes the list of parts expected by the provider, built through
image_part().- Parameters:
message (str) – The text of the message.
images (Optional[Sequence[ImageInput]], optional) – Images to attach.
- Returns:
Provider-ready message content.
- Return type:
Any
- image_part(image)[source]¶
Return a single image encoded the way the provider expects it.
- Parameters:
image (ImageInput) – The image to encode.
- Returns:
A provider-specific content part.
- Return type:
Any
- Raises:
NotImplementedError – If the backend does not support images.
- prepare(examples_dir)[source]¶
Load few-shot examples from a folder.
The folder is expected to contain a
main.yamlfile. That file may declare afilesfield listing further YAML files to include, and each of those may declare afilesfield of its own, so examples can be split across a tree of files. Paths are resolved relative to the file declaring them. Loaded examples end up inmessagesand are sent ahead of every query.- Parameters:
examples_dir (Union[str, Path]) – Folder containing
main.yaml.- Raises:
NotImplementedError – Always, for the moment.
- Return type:
None
llm_factory¶
Pick the right backend for a configuration file.
The configuration decides which class is used: an explicit PROVIDER key when present, and a
handful of heuristics on the remaining keys otherwise. create_llm() then hands the file to
that class’ from_config().
- llm_factory.create_llm(config_file, examples=None, **overrides)[source]¶
Build the backend described by a configuration file.
- Parameters:
config_file (Union[str, Path]) – Path to the YAML configuration file.
examples (Optional[Union[str, Path]], optional) – Folder with few-shot examples.
**overrides (Any) – Forwarded to the backend’s
from_config.
- Returns:
A configured backend instance.
- Return type:
- llm_factory.default_config_dir()[source]¶
Return the directory holding the bundled configuration files.
- Returns:
Path of the
conffolder sitting next to this module.- Return type:
str
- llm_factory.infer_provider(config)[source]¶
Infer the provider from a loaded configuration.
- Parameters:
config (Dict[str, Any]) – Parsed configuration.
- Returns:
Canonical provider slug.
- Return type:
str
- Raises:
ValueError – If the provider cannot be determined.
- llm_factory.infer_provider_from_file(config_file)[source]¶
Infer the provider from a configuration file path.
- Parameters:
config_file (Union[str, Path]) – Path to the YAML configuration file.
- Returns:
Canonical provider slug.
- Return type:
str
- Raises:
FileNotFoundError – If the file does not exist or is not a YAML file.
ValueError – If the provider cannot be determined.
- llm_factory.list_config_files(config_dir=None)[source]¶
List the YAML configuration files of a directory.
- Parameters:
config_dir (Optional[Union[str, Path]], optional) – Directory to scan. Defaults to
LLM/conf.- Returns:
Sorted configuration file paths.
- Return type:
List[str]
- Raises:
FileNotFoundError – If the directory does not exist.
- llm_factory.normalize_provider(provider)[source]¶
Normalize a provider name to its canonical slug.
- Parameters:
provider (str) – Provider name, in any of its accepted spellings.
- Returns:
Canonical provider slug.
- Return type:
str
- Raises:
ValueError – If the provider is unknown.
- llm_factory.resolve_class(provider)[source]¶
Import and return the backend class for a provider.
- Parameters:
provider (str) – Provider name or slug.
- Returns:
The backend class.
- Return type:
Type[BaseLLM]
- Raises:
ValueError – If the provider is unknown.
ImportError – If the backend module cannot be imported.
- llm_factory.resolve_class_from_file(config_file)[source]¶
Return the backend class a configuration file asks for.
- Parameters:
config_file (Union[str, Path]) – Path to the YAML configuration file.
- Returns:
The backend class.
- Return type:
Type[BaseLLM]
- Raises:
FileNotFoundError – If the file does not exist or is not a YAML file.
ValueError – If the provider cannot be determined.
ImportError – If the backend module cannot be imported.
- llm_factory.select_llm(config_dir=None, selection=None, examples=None, input_fn=<built-in function input>, print_fn=<built-in function print>, **overrides)[source]¶
Pick a configuration file from a directory and build its backend.
- Parameters:
config_dir (Optional[Union[str, Path]], optional) – Directory to pick from. Defaults to
LLM/conf.selection (Optional[Union[int, str]], optional) – A 1-based index, a file name or path, or
Noneto ask interactively.examples (Optional[Union[str, Path]], optional) – Folder with few-shot examples.
input_fn (Callable[[str], str], optional) – Input function used in interactive mode.
print_fn (Callable[[str], None], optional) – Print function used in interactive mode.
**overrides (Any) – Forwarded to the backend’s
from_config.
- Returns:
A configured backend instance.
- Return type:
- Raises:
FileNotFoundError – If no configuration file matches.
ValueError – If an interactive selection is cancelled.