LLM access

besser.llm holds what every LLM call in BESSER shares: the OpenAI chat transport, the one retry policy, the SDK clients, reading JSON out of a reply, the upstream error, the model catalog and the per-model token prices. It imports none of its callers and works from a base install; the openai and anthropic SDKs (the agents extra) are imported only when an SDK client is built. besser.utilities.llm_utils re-exports the names it used to define.

The model catalog (besser.llm.catalog, BESSER_MODEL_CATALOG merged over besser/llm/data/model_catalog.json) and the prices (besser.llm.pricing, from the catalog and the vendored public list in besser/llm/data/model_prices.json) live here. The Spec-Driven Agent’s provider clients themselves are still in besser.spec_driven_agent.providers.llm_client (they use besser.llm.retry and the prices); they move here with its split.

OpenAI chat completions over HTTP, from a base install.

Every OpenAI chat request outside the Spec-Driven Agent goes through post_openai_chat(): it enforces a timeout, never echoes the upstream response body to a caller, and retries (when asked) with the policy every LLM call in BESSER shares, besser.llm.retry. It uses requests (a base dependency) rather than the openai SDK, which is the optional agents extra.

besser.llm.openai_chat.OPENAI_CHAT_ENDPOINT = 'https://api.openai.com/v1/chat/completions'

OpenAI chat-completions endpoint used by the helpers below.

besser.llm.openai_chat.DEFAULT_OPENAI_MODEL = 'gpt-4o'

Model used when a caller does not name one. Defined here, in the lowest layer that talks to OpenAI, so the notation code, the LLM KG converter and the backend all share one value and cannot drift apart.

besser.llm.openai_chat.DEFAULT_REQUEST_TIMEOUT = 120

Seconds before an upstream request is abandoned. Callers that run inside a web request should additionally keep the call off the event loop.

besser.llm.openai_chat.post_openai_chat(api_key: str, payload: dict, *, http_post: Callable[[...], Any] | None = None, timeout: float = 120, endpoint: str = 'https://api.openai.com/v1/chat/completions', max_retries: int = 0) → str[source]

POST a chat-completions payload and return the assistant content.

The transport half of every OpenAI chat call outside the Spec-Driven Agent: it applies a timeout, turns every failure into LLMUpstreamError, and never puts the provider’s response body in an exception message. The payload is the caller’s, untouched, because it differs by use (a text prompt, or a vision request with image parts and max_tokens).

Parameters:
  • api_key – Bearer token. It is stripped, and redacted from anything logged.

  • payload – The complete request body.

  • http_post – Transport override for tests. None looks up requests.post() at call time, so monkeypatching it works.

  • timeout – Seconds before each attempt is abandoned. Always applied.

  • max_retries – Retries after the first attempt, on a connection error, a timeout or a retryable status (408, 409, 429, 5xx), waiting as besser.llm.retry.backoff_seconds() says (Retry-After honoured, capped). A spent quota (insufficient_quota) is not retried. 0 (the default) makes one attempt.

Returns:

The content string, which may be empty. Deciding whether an empty completion is an error is the caller’s business.

Raises:

LLMUpstreamError – on a transport failure, a non-2xx status, a body that is not JSON, or a JSON error object. See the class docstring for what the message does and does not contain.

besser.llm.openai_chat.call_openai_chat_json(api_key: str, model: str, system_msg: str, user_msg: str, *, http_post: Callable[[...], Any] | None = None, timeout: float = 120, endpoint: str = 'https://api.openai.com/v1/chat/completions', temperature: float = 0.0, max_completion_tokens: int = 4000) → str[source]

Send one system+user text prompt and return the assistant content.

A thin payload builder over post_openai_chat(); see there for the error contract.

The retry policy every LLM call in BESSER shares.

Which statuses are worth retrying, how long to wait, and which 429s are a spent quota that no retry will fix. The functions read an error the way the provider SDKs raise it: an HTTP status on the error or on its response, the response’s headers, and the provider’s message in str(error).

besser.llm.retry.RETRYABLE_STATUS_CODES = {408, 409, 429, 500, 502, 503, 504}

Statuses retried besides every 5xx.

besser.llm.retry.status_code(error: Exception) → int | None[source]

HTTP status of a provider error: SDK attribute first, then the text.

besser.llm.retry.is_retryable_status(status: int) → bool[source]

Every 5xx, as the SDKs’ own retry did (529 and a tunnel’s 52x are transient), and 408/409/429.

besser.llm.retry.is_rate_limit(error: Exception) → bool[source]

True if the error is a provider rate-limit (HTTP 429).

besser.llm.retry.is_quota_exhausted(error: Exception) → bool[source]

True when a 429 is a DAILY/period quota exhaustion, not a transient throttle.

E.g. Command Code’s free LongCat returns 429 "You've used all 100 free LongCat 2.0 requests for today. Your quota resets at …", and OpenAI 429 insufficient_quota. That will not recover inside a retry window, so the 5-attempt backoff (0.5s → 30s cap) just burns ~15-40s per call before the fallback finally engages. Classify it so callers skip retries and fall back (or fail) immediately — and can tell the user why.

besser.llm.retry.retry_after_seconds(error: Exception) → float | None[source]

Extract a server-provided Retry-After hint (seconds), if any.

The OpenAI/Mistral and Anthropic SDK error objects (and requests’ HTTPError) carry the HTTP response, whose headers may include retry-after (delta-seconds). Returns None when no usable hint is present.

besser.llm.retry.backoff_seconds(error: Exception, attempt: int) → float[source]

Seconds to wait before the next retry.

Honors a server-provided Retry-After (capped), otherwise uses exponential backoff. Rate-limit (429) responses get a higher ceiling so a throttled provider isn’t abandoned after a sub-second wait.

Clients of the official openai and anthropic SDKs.

The SDKs are the optional agents extra, so they are imported when a client is built, not when this module is. The keyword arguments go to the SDK unchanged: each caller keeps its own timeout, retry count and base URL.

besser.llm.sdk.openai_client(**kwargs: Any) → Any[source]

An openai.OpenAI client built with kwargs.

Raises:

ImportError – the openai package is not installed.

besser.llm.sdk.anthropic_client(**kwargs: Any) → Any[source]

An anthropic.Anthropic client built with kwargs.

Raises:

ImportError – the anthropic package is not installed.

Reading the JSON out of a model’s reply.

besser.llm.replies.clean_json_response(response: str) → str[source]

Strip markdown fences from a JSON response produced by an LLM.

besser.llm.replies.parse_json_safely(json_text: str) → Any | None[source]

Parse JSON, returning None on decode errors instead of raising.

besser.llm.replies.extract_json(text: str, kind: type = <class 'dict'>) → Any | None[source]

The JSON value of type kind (dict or list) an LLM reply holds.

The whole reply or a fenced block is the answer when it parses, even an empty one. Otherwise only top-level values in the prose are considered (each is decoded with JSONDecoder.raw_decode and skipped past, so the values nested inside it are never candidates), empty ones are not an answer, and the longest wins over a citation such as [1]. A value that is still open when the text ends means the reply was truncated: None, never a fragment of it.

The error every LLM call in BESSER surfaces to its caller.

exception besser.llm.errors.LLMUpstreamError(message: str, *, status: int | None = None)[source]

The LLM provider failed, or answered with something unusable.

The message is safe to show to an end user: it names the failure and, for an HTTP error, the status code, but never the provider’s response body (which can echo request fragments such as part of the API key). The body is logged on the server instead.

Subclasses RuntimeError so existing except RuntimeError handlers keep working.

The LLM model catalog: which providers and models a deployment offers.

The key dialog’s provider and model lists, the endpoint of a gateway provider (e.g. pia) and the rates a gateway bills are configuration, not code. BESSER ships a public default (data/model_catalog.json); a deployment points BESSER_MODEL_CATALOG at its own JSON file, which is merged over it:

  • providers.<id> replaces that provider’s entry; null removes it; a new id is appended.

  • route_prices.<host> replaces that host’s rate table; null removes it.

  • "replace": true drops the default catalog entirely.

Keys starting with _ are notes and are ignored.

A provider entry:

{"label": "PIA (LIST)", "hint": "...", "key_prefix": "sk-",
 "base_url": "https://gateway.example/v1",
 "models": [{"id": "m", "label": "M", "default": true,
             "price": {"input": 1.0, "output": 5.0,
                       "cache_read": 1.0, "cache_write": 1.0}}]}

base_url makes the provider a gateway: the server sends its calls there over the OpenAI-compatible protocol, so the browser never holds the host. Prices are USD per 1M tokens; a missing cache rate bills at the input rate. Public vendor list prices stay in data/model_prices.json; a model’s price here overrides them on that provider’s route (see besser.llm.pricing). A model marked "default": true is the provider’s default when a request names none. An optional "request" object sets the model’s request quirks (forced_tool_choice, thinking_can_be_disabled, reasoning_effort_for_tools) over the Spec-Driven Agent’s built-in row (spec_driven_agent/providers/model_settings.py), so a new model with a known quirk needs no release.

exception besser.llm.catalog.ModelCatalogError[source]

The catalog file is missing or malformed.

class besser.llm.catalog.ModelCatalog(providers: 'dict[str, dict[str, Any]]', route_prices: 'dict[str, dict[str, dict[str, float]]]', listed_prices: 'dict[str, dict[str, float]]', request_overrides: 'dict[str, dict[str, Any]]')[source]
base_url(provider: str) → str | None[source]

The endpoint of a gateway provider, or None.

flagged_default(provider: str) → str | None[source]

The model the catalog marks "default": true for provider.

route_price(model_id: str, route: str | None) → dict[str, float] | None[source]

The rate a gateway bills for model_id on route (URL or host).

request_override(model_id: str) → dict[str, Any][source]

Request quirks the catalog sets for model_id (possibly empty).

listed_price(model_id: str) → dict[str, float] | None[source]

A rate the catalog sets for a vendor model (no gateway).

public_providers() → list[dict[str, Any]][source]

The providers as the key dialog needs them: no endpoint, no rates.

besser.llm.catalog.load_model_catalog() → ModelCatalog[source]

The default catalog with the deployment’s file merged over it.

Cached for the process: editing the file takes a restart. Raises ModelCatalogError for a missing or malformed file, so a broken deployment catalog fails at startup instead of silently dropping a provider.

Per-model token prices, for cost tracking and the per-run cost cap.

get_pricing() answers USD per 1M tokens (input, output, cache_write, cache_read) from, in order: the rate a gateway bills (model catalog route_prices), $0 for self-hosted and free models, a rate the deployment’s catalog sets, the vendored public list prices (data/model_prices.json) and the hand-typed MODEL_PRICING.

besser.llm.pricing.is_free_local_model(model_lower: str) → bool[source]

True for models that cost the platform $0 — self-hosted, or free tiers.

Getting this wrong is expensive in both directions: a false positive prices a paid model at $0 and SILENTLY DISABLES the cost cap, while a false negative bills a self-hosted run that is actually free.

The decision therefore keys on how the model is IDENTIFIED, not on its family: the gateway resells open-weight families, so Qwen/Qwen3.8-Max and deepseek/deepseek-v4-pro are billed cloud models that a family allow-list priced at $0.

  1. an explicit free marker (:free / -free) – always free;

  2. an Ollama name:tag id with no vendor namespace – self-hosted;

  3. a vendor-namespaced id (vendor/model) – a gateway model, billed;

  4. otherwise fall back to the family list, which still covers tagless self-hosted ids.

besser.llm.pricing.vendored_prices() → dict[str, dict[str, float]][source]

Published per-model rates, keyed by exact model id.

Vendored from litellm’s model_prices_and_context_window.json (MIT), reduced to the providers we call and the four fields we read. The data file rather than the package: an import litellm would break the offline on-prem install. Refresh with:

curl -s https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json

then keep rows whose litellm_provider is anthropic/openai/mistral/ nebius/bedrock and the *_cost_per_token fields.

The modeling-agent prices its calls from a byte-identical copy (src/llm/tracking/data/model_prices.json there): copy the refreshed file over it in the same change.

Returns {} if the file is missing (a wheel built without it), which falls the caller through to MODEL_PRICING rather than to $0 — an absent price must never read as free, or the cost cap stops existing.

besser.llm.pricing.get_pricing(model_id: str, billed: bool = False, route: str | None = None) → dict[str, float][source]

Get the per-1M-token rates for a model ID.

Published per-model rates come first, from the vendored table. The hand-typed MODEL_PRICING below it is a fallback for ids nobody publishes, and its Anthropic rows are coarse tiers: they cannot tell claude-sonnet-4-6 ($3/$15) from claude-sonnet-5 ($2/$10), and the opus row still carries Claude-3-era $15/$75 — 3x over every current Opus, which trips max_cost_usd at a third of the intended spend. Prices are external facts that drift silently, so prefer the table that is refreshed over the one that is remembered.

Order matters in the OpenAI loop — longer / more-specific keys must come first so e.g. gpt-5.5 doesn’t get mis-matched to gpt-5 (which is a substring) and silently billed at the cheaper tier. Falls back to gpt-4o so an unknown paid model gets a reasonable middle-tier rate; self-hosted/open models are detected first and priced at $0.

billed is set when the route itself is a paid vendor API (Anthropic, official OpenAI, Mistral, Nebius): the id-shape free heuristic is skipped there, since codestral-2508 on Mistral’s API is not a local checkout.

Environment configuration of the LLM layer.

The Spec-Driven Agent’s AgentSettings extends LLMSettings, so each variable is still declared once.

class besser.llm.settings.LLMSettings(_case_sensitive: bool | None = None, _nested_model_default_partial_update: bool | None = None, _env_prefix: str | None = None, _env_prefix_target: EnvPrefixTarget | None = None, _env_file: DotenvType | None = PosixPath('.'), _env_file_encoding: str | None = None, _env_file_depth: int | None = None, _env_ignore_empty: bool | None = None, _env_nested_delimiter: str | None = None, _env_nested_max_split: int | None = None, _env_parse_none_str: str | None = None, _env_parse_enums: bool | None = None, _cli_prog_name: str | None = None, _cli_parse_args: bool | list[str] | tuple[str, ...] | None = None, _cli_settings_source: CliSettingsSource[Any] | None = None, _cli_parse_none_str: str | None = None, _cli_hide_none_type: bool | None = None, _cli_avoid_json: bool | None = None, _cli_enforce_required: bool | None = None, _cli_use_class_docs_for_groups: bool | None = None, _cli_show_env_vars: bool | None = None, _cli_exit_on_error: bool | None = None, _cli_prefix: str | None = None, _cli_flag_prefix_char: str | None = None, _cli_implicit_flags: bool | 'dual' | 'toggle' | None = None, _cli_ignore_unknown_args: bool | None = None, _cli_kebab_case: bool | 'all' | 'no_enums' | None = None, _cli_shortcuts: Mapping[str, str | list[str]] | None = None, _secrets_dir: PathType | None = None, _build_sources: tuple[tuple[PydanticBaseSettingsSource, ...], dict[str, Any]] | None = None, *, BESSER_MODEL_CATALOG: str = '')[source]

The LLM layer’s environment variables (all optional).

model_config : ClassVar[SettingsConfigDict] = {'arbitrary_types_allowed': True, 'case_sensitive': True, 'cli_avoid_json': False, 'cli_enforce_required': False, 'cli_exit_on_error': True, 'cli_flag_prefix_char': '-', 'cli_hide_none_type': False, 'cli_ignore_unknown_args': False, 'cli_implicit_flags': False, 'cli_kebab_case': False, 'cli_parse_args': None, 'cli_parse_none_str': None, 'cli_prefix': '', 'cli_prog_name': None, 'cli_shortcuts': None, 'cli_show_env_vars': False, 'cli_use_class_docs_for_groups': False, 'enable_decoding': True, 'env_file': None, 'env_file_depth': 0, 'env_file_encoding': None, 'env_ignore_empty': False, 'env_nested_delimiter': None, 'env_nested_max_split': None, 'env_parse_enums': None, 'env_parse_none_str': None, 'env_prefix': '', 'env_prefix_target': 'variable', 'extra': 'ignore', 'json_file': None, 'json_file_encoding': None, 'nested_model_default_partial_update': False, 'protected_namespaces': (), 'secrets_case_sensitive': None, 'secrets_dir': None, 'secrets_dir_max_size': None, 'secrets_dir_missing': None, 'secrets_nested_delimiter': None, 'secrets_nested_subdir': None, 'secrets_prefix': None, 'toml_file': None, 'validate_default': False, 'yaml_config_section': None, 'yaml_file': None, 'yaml_file_encoding': None}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].