Koog Provider Layer — LLM Integration Architecture
Audience: developers and AI agents modifying Book’s LLM integration (
core/providers/koog), or adding a new LLM provider.How Book talks to LLMs: the Koog framework provides streaming/executors; this layer adapts them to Book’s domain model so the rest of the codebase is provider-agnostic.
Module Position
:providers:koog is an outer-ring adapter (module dependencies).
Domain defines what an LLM is; this module defines how to get one:
| Domain type (imported, never reimplemented) | Koog-layer implementation |
|---|---|
|
|
|
|
|
effort applied in prompt/executor setup |
|
translated to Koog prompt types at the boundary |
Domain files may never import ai.koog.*. All Koog types are confined to this
module and :jvm:cli glue.
Agent Interface (domain contract)
interface Agent {
var model: String?
/** Streams the next turn from the LLM. */
fun nextTurn(
messages: List<Message>,
tools: List<Tool>,
sessionLogger: SessionLogger = NoOpSessionLogger
): Flow<AgentEvent>
suspend fun listModels(): List<ModelMetadata>
fun lookupMetadata(modelId: String): ModelMetadata? = null
}
KoogAgent implements this; AgentLoop depends on the interface only — that is the
seam that makes the whole agent loop testable (fake Agent in tests, see
Agent Loop).
KoogAgent
Orchestrator wiring executor + model + tools per turn. Constructor receives
LLMClientAPI (Koog abstraction, provided by Metro as BifrostOpenAILLMClient),
ProviderConfig (holding injected provider API keys and base URL), and emits
AgentEvent`s via `StreamOrchestrator. Provider configuration fields are read directly
from the injected ProviderConfig instance without setting global JVM system properties
(System.setProperty).
StreamOrchestrator — Stream Lifecycle Contract
Owns the entire stream lifecycle of a single agent turn. The contract, preserved from
the original KoogAgent.nextTurn:
-
Pre-stream failure (stream factory throws before any frame): exactly one
AgentEvent.Error("Failed to initiate stream: …"), flow completes — no fallbackCompleted. -
Mid-stream non-cancellation failure: one
AgentEvent.Error("Streaming error: …"), thenfinallyemits a fallbackCompletedif content accumulated (else an additionalError+ emptyCompleted). -
Mid-stream cancellation:
-
Caller-job cancellation (Ctrl+C): rethrows
CancellationExceptionto unwind. -
Watchdog-only cancellation (inactivity timeout): logs a warning, does not rethrow;
finallyemits the fallbackCompleted— the watchdog soft-stop contract.
Also: collects frames via StreamFrameHandler, arms the InactivityWatchdog,
discriminates cancellation vs. real errors, handles fallback completion, and dispatches
the after_provider_response extension event.
StreamFrameHandler
Maps Koog `StreamFrame`s to domain `AgentEvent`s: text/thinking deltas, tool-call argument accumulation, paired-frame de-duplication for double-emitting gateways. Details: Agent Loop — Streaming Pipeline.
BifrostOpenAILLMClient
Book’s OpenAI-compatible client wrapper (LLMClientAPI). Exists to route requests
through Bifrost (proxy/model-registry) with Book-specific defaults, so any
OpenAI-compatible backend (OpenAI, vLLM, Ollama-bridges, Bifrost itself) can serve
Book without a bespoke client.
PromptExecutorFactory
Open class; create(provider, config): PromptExecutorAPI. Two built-ins:
-
anthropic→AnthropicLLMClient+ retry wrapper -
anything else →
OpenAILLMClientagainst a normalised base URL:
val configBaseUrl = config.openAiBaseUrl.removeSuffix("/")
val baseUrl = if (configBaseUrl.endsWith("/v1")) {
configBaseUrl.removeSuffix("/v1")
} else {
configBaseUrl
}
Retry is applied via Koog’s toRetryingClient(RetryConfig) — injected, not hardcoded.
open on the class is intentional: tests override create with fakes.
Adding a Provider
-
Add a branch in
PromptExecutorFactory.createwrapping the Koog client in a retrying executor -
If the backend is OpenAI-compatible, prefer reusing
BifrostOpenAILLMClientwith a new base URL — no new client class needed -
Extend
ProviderConfig/core/infrastructureconfig parsing (API key env var, base URL). Provider credentials are resolved at startup in the CLI layer and injected viaProviderConfigwithout globalSystem.setPropertymutations. -
Add model registry entries so
listModels()/lookupMetadata()return pricing metadata (ModelPricingpowers the cost tracker — see Configuration) -
No changes outside this module — that’s the point of the boundary
InactivityWatchdog
Cancels a stream that produces no frames for the configured window (soft-stop semantics
above). Watchdog-only cancellation is distinguishable from user cancellation inside
StreamOrchestrator — do not collapse the two paths.
Related
-
Agent Loop — the consumer of this module; guards, compaction, streaming details
-
DI & Wiring — how
KoogAgent,LLMClientAPI, and executors are provided via Metro -
Domain Package Reference —
ReasoningAgent,EffortLevel,Agentdefinitions