BaseLifecycleLLMClient

org.llm4s.llmconnect.BaseLifecycleLLMClient

Mixin trait providing standard lifecycle management and metrics wrapping for LLMClient implementations.

Tracks whether the client has been closed via an AtomicBoolean and provides:

  • validateNotClosed — a pre-check returning Left(ConfigurationError) once closed.
  • close() — an idempotent close that delegates to releaseResources() exactly once.
  • completeWithMetrics — combines lifecycle validation with metrics recording for Completion results, eliminating boilerplate in complete / streamComplete.

Concrete clients mix in this trait, supply provider and modelName, and optionally override releaseResources() to free provider-specific resources (HTTP clients, SDK connections, etc.).

Attributes

Source
BaseLifecycleLLMClient.scala
Graph
Supertypes
trait LLMClient
class Object
trait Matchable
class Any
Show all
Known subtypes

Members list

Value members

Abstract methods

protected def clientDescription: String

Human-readable label used in the "already closed" error message.

Human-readable label used in the "already closed" error message.

Attributes

Source
BaseLifecycleLLMClient.scala
protected def modelName: ModelName

The model identifier forwarded to the metrics collector.

The model identifier forwarded to the metrics collector.

Attributes

Source
BaseLifecycleLLMClient.scala
protected def provider: ProviderId

The provider this client calls (e.g. ProviderId("openai")): the provider id tracing reports, the metrics label, as its string, and the provider a cancellation names.

The provider this client calls (e.g. ProviderId("openai")): the provider id tracing reports, the metrics label, as its string, and the provider a cancellation names.

Attributes

Source
BaseLifecycleLLMClient.scala

Concrete methods

override def close(): Unit

Releases resources and closes connections to the LLM provider.

Releases resources and closes connections to the LLM provider.

Call when the client is no longer needed. After calling close(), the client should not be used. Default implementation is a no-op; override if managing resources like connections or thread pools.

Attributes

Definition Classes
Source
BaseLifecycleLLMClient.scala
protected def completeWithMetrics(operation: => Result[Completion]): Result[Completion]

Validates that the client is open, executes the operation, and records standard completion metrics (latency, token usage, estimated cost).

Validates that the client is open, executes the operation, and records standard completion metrics (latency, token usage, estimated cost).

Use this in complete and streamComplete implementations to avoid repeating the lifecycle-check + metrics-wrapping boilerplate.

An interrupted call - one that throws InterruptedException, or fails while the thread is interrupted - is returned as Left(CancelledError) with the interrupt flag kept, whatever the provider SDK did with it. A call made with the flag already set returns Left(CancelledError) at once, without running operation: an SDK that ignores the flag would otherwise send the (billed) request anyway.

Value parameters

operation

The provider-specific completion logic to execute. Called only when the client is open and the thread is not interrupted.

Attributes

Returns

The completion result with metrics recorded as a side-effect.

Source
BaseLifecycleLLMClient.scala
override def providerId: Option[ProviderId]

This client's provider.

This client's provider.

Attributes

Definition Classes
Source
BaseLifecycleLLMClient.scala
protected def releaseResources(): Unit

Hook for releasing provider-specific resources. Called at most once, inside close(). The default is a no-op.

Hook for releasing provider-specific resources. Called at most once, inside close(). The default is a no-op.

Attributes

Source
BaseLifecycleLLMClient.scala
protected def validateNotClosed: Result[Unit]

Attributes

Source
BaseLifecycleLLMClient.scala

Inherited methods

def completeStructured[A](conversation: Conversation, schema: ObjectSchema[A], options: CompletionOptions)(implicit reader: Reader[A]): Result[A]

Sends the conversation and parses the response into a typed value using the provided schema.

Sends the conversation and parses the response into a typed value using the provided schema.

Sets ResponseFormat.JsonSchema on the options. OpenAI, Azure OpenAI and Gemini enforce the schema at generation time, as does Ollama 0.5 or later through its format field. Requesty and the OpenAI-compatible providers (including Cohere) send it as response_format, but whether it is enforced is up to the server - for Requesty, a router, the backend model it routes to: one that ignores the field returns unconstrained text. Anthropic falls back to a best-effort system-prompt instruction, which is not schema-enforced. Clients that do not read responseFormat (watsonx, Bedrock) send no schema at all. Because models may wrap JSON in markdown code fences or surround it with prose, the response is normalised (fence stripped, first balanced {...} or [...] extracted) before being deserialised with uPickle into the expected type A. A is read from that text, so a Long field receives an integer above 2^53 exactly; a reader that goes through ujson.Value (such as a bridge to another JSON library) sees it rounded to the nearest double.

The reply is '''not''' validated against the schema: it is only deserialised. A constraint the reader does not check - an enum, a numeric or string bound, additionalProperties = false (extra keys are ignored) - can be violated by a reply that still returns Right(A). Check such constraints on the result yourself.

The schema is derived with strict = true, which lists '''every''' property as required, including a property declared optional with required = false. Only responseFormat is overridden: every other option you pass is forwarded unchanged to complete, where the provider client may adjust or drop options the model does not support, as for any other complete call. name and strict on the format are left at their defaults ("response" and true); call complete with your own ResponseFormat.JsonSchema to set them.

Type parameters

A

target type; must have a corresponding upickle.default.Reader[A]

Value parameters

conversation

conversation history

options

additional completion options (default: CompletionOptions())

reader

implicit uPickle reader for deserialising the JSON into A

schema

JSON-Schema description of the expected response object

Attributes

Returns

Right(A) on success. Left(ValidationError) with field structured_output when the reply is not JSON, is JSON null, or cannot be deserialised as A; any other Left is the provider call's own error, returned unchanged

Inherited from:
LLMClient
Source
LLMClient.scala

Calculates available token budget for prompts after accounting for completion reserve and headroom.

Calculates available token budget for prompts after accounting for completion reserve and headroom.

Formula: (contextWindow - reserveCompletion) * (1 - headroom)

Headroom provides a safety margin for tokenization variations and message formatting overhead.

Value parameters

headroom

safety margin as percentage of prompt budget (default: HeadroomPercent.Standard ~10%)

Attributes

Returns

maximum tokens available for prompt content

Inherited from:
LLMClient
Source
LLMClient.scala
def validate(): Result[Unit]

Checks this client against its provider with one cheap request: that the endpoint answers and accepts the client's credentials, and, where the provider has a lookup for one model, that the configured model exists. It sends no completion and uses no tokens. Each provider client documents the request it sends.

Checks this client against its provider with one cheap request: that the endpoint answers and accepts the client's credentials, and, where the provider has a lookup for one model, that the configured model exists. It sends no completion and uses no tokens. Each provider client documents the request it sends.

Right(()) means that request was sent and the provider accepted it: a client never returns it without having checked something (#2830). A check that fails is the Left a call would have failed with - an AuthenticationError for a rejected key, a NetworkError or ServiceError for an endpoint that does not answer, the provider's own error for a model it does not have.

A client with no such request returns Left(ValidationUnsupportedError), which is also this default: nothing was checked, and the client may well work. Match on it to tell the two apart. A wrapper delegates to the client it wraps.

Attributes

Returns

Right(()) when the provider accepted the validation request; Left(ValidationUnsupportedError) when the client has none; otherwise the Left the failed request mapped to

Inherited from:
LLMClient
Source
LLMClient.scala
protected def withMetrics[A](provider: ProviderId, model: ModelName, operation: => Result[A], extractUsage: A => Option[TokenUsage], extractCost: A => Option[Double]): Result[A]

Executes operation and records metrics for the call.

Executes operation and records metrics for the call.

Latency and outcome (success or classified error) are recorded for every call regardless of result. Token counts and cost are recorded on success. A Left result emits an Outcome.Error (org.llm4s.metrics.Outcome) event whose kind is derived from the org.llm4s.error.LLMError subtype via ErrorKind.fromLLMError, and records tokens only for a org.llm4s.error.ContentFilteredError carrying the usage the provider billed for the filtered call.

Value parameters

extractCost

Extracts the pre-computed cost (USD) from a successful result; return None to skip cost recording.

extractUsage

Extracts prompt/completion token counts from a successful result; return None to skip token recording.

model

The model called; its string is the model the collector receives.

operation

The LLM call to time and observe.

provider

The provider called; its string is the label the collector receives (e.g. "openai").

Attributes

Returns

The result of operation, unchanged.

Inherited from:
MetricsRecording
Source
MetricsRecording.scala

Inherited and Abstract methods

def complete(conversation: Conversation, options: CompletionOptions): Result[Completion]

Executes a blocking completion request and returns the full response.

Executes a blocking completion request and returns the full response.

Sends the conversation to the LLM and waits for the complete response. Use when you need the entire response at once or when streaming is not required.

Value parameters

conversation

conversation history including system, user, assistant, and tool messages

options

configuration including temperature, max tokens, tools, etc. (default: CompletionOptions())

Attributes

Returns

Right(Completion) with the model's response, or Left(LLMError) on failure

Inherited from:
LLMClient
Source
LLMClient.scala

Returns the maximum context window size supported by this model in tokens.

Returns the maximum context window size supported by this model in tokens.

The context window is the total tokens (prompt + completion) the model can process in a single request, including all conversation messages and the generated response.

Attributes

Returns

total context window size in tokens (e.g., 4096, 8192, 128000)

Inherited from:
LLMClient
Source
LLMClient.scala
protected def metrics: MetricsCollector

The org.llm4s.metrics.MetricsCollector that receives timing, token, and cost events.

The org.llm4s.metrics.MetricsCollector that receives timing, token, and cost events.

Injected by each concrete provider client. Defaults to MetricsCollector.noop in all public constructors, so callers that do not need metrics do not pay an allocation cost.

Attributes

Inherited from:
MetricsRecording
Source
MetricsRecording.scala

Returns the number of tokens reserved for the model's completion response.

Returns the number of tokens reserved for the model's completion response.

This value is subtracted from the context window when calculating available tokens for prompts. Corresponds to the max_tokens or completion token limit configured for the model.

Attributes

Returns

number of tokens reserved for completion

Inherited from:
LLMClient
Source
LLMClient.scala
def streamComplete(conversation: Conversation, options: CompletionOptions)(onChunk: StreamedChunk => Unit): Result[Completion]

Executes a streaming completion request, invoking a callback for each chunk as it arrives.

Executes a streaming completion request, invoking a callback for each chunk as it arrives.

Streams the response incrementally, calling onChunk for each token/chunk received. Enables real-time display of responses. Returns the final accumulated completion on success.

Value parameters

conversation

conversation history including system, user, assistant, and tool messages

onChunk

callback invoked for each chunk; called synchronously, avoid blocking operations

options

configuration including temperature, max tokens, tools, etc. (default: CompletionOptions())

Attributes

Returns

Right(Completion) with the complete accumulated response, or Left(LLMError) on failure

Inherited from:
LLMClient
Source
LLMClient.scala