embabel-agent icon indicating copy to clipboard operation
embabel-agent copied to clipboard

Design: Capability-based model abstraction

Open jasperblues opened this issue 7 months ago • 16 comments

Overview

Design proposal for a capability-based model abstraction that replaces monolithic LLM interfaces with fine-grained, composable contracts. This enables vendor-neutral provider implementations where callers work against capabilities rather than specific frameworks.

Also known as the traits-based model API — "capability" is the term used throughout this issue.

Related: #1474, #1581

Design

Capability Interfaces

Fine-grained contracts for individual model capabilities:

interface TextCompletion {
    fun complete(prompt: String): String
}

interface StreamingTextCompletion {
    fun stream(prompt: String): Sequence<String>
}

interface ImageGen {
    fun generate(prompt: String): ByteArray
}

Named Higher-Level Shapes

Common combinations as composed interfaces:

interface ChatModel : TextCompletion, StreamingTextCompletion

interface MultimodalChatModel : ChatModel, ImageGen

Generic Model Wrapper

For dynamic capability querying when the concrete type isn't known at compile time:

import kotlin.reflect.KClass

class GenericModel(
    private val capabilities: Map<KClass<*>, Any>
) {
    @Suppress("UNCHECKED_CAST")
    fun <T : Any> get(type: KClass<T>): T? =
        capabilities[type] as? T

    inline fun <reified T : Any> get(): T? =
        get(T::class)

    inline fun <reified T : Any> getOrThrow(): T =
        get<T>() ?: error("Model does not support ${T::class.simpleName}")
}

Provider Implementations

Providers implement the capability interfaces directly:

class Gpt5Client : MultimodalChatModel {
    override fun complete(prompt: String) = "text"
    override fun stream(prompt: String) = sequenceOf("a", "b")
    override fun generate(prompt: String) = ByteArray(0)
}

class ClaudeClient : ChatModel {
    override fun complete(prompt: String) = "claude text"
    override fun stream(prompt: String) = sequenceOf("x", "y")
}

class SdxlClient : ImageGen {
    override fun generate(prompt: String) = ByteArray(0)
}

Factory With Both Styles

class ModelFactory {

    fun gpt5(): MultimodalChatModel = Gpt5Client()

    fun claude(): ChatModel = ClaudeClient()

    fun generic(modelId: String): GenericModel =
        when (modelId) {
            "gpt-5" -> {
                val client = Gpt5Client()
                GenericModel(
                    mapOf(
                        TextCompletion::class to client,
                        StreamingTextCompletion::class to client,
                        ImageGen::class to client,
                        ChatModel::class to client,
                        MultimodalChatModel::class to client
                    )
                )
            }
            "claude-sonnet" -> {
                val client = ClaudeClient()
                GenericModel(
                    mapOf(
                        TextCompletion::class to client,
                        StreamingTextCompletion::class to client,
                        ChatModel::class to client
                    )
                )
            }
            "sdxl" -> {
                val client = SdxlClient()
                GenericModel(
                    mapOf(
                        ImageGen::class to client
                    )
                )
            }
            else -> error("Unknown model: $modelId")
        }
}

Usage

Strongly typed (known model):

val gpt = factory.gpt5()
gpt.complete("Hello")
gpt.stream("Tell me a story")
gpt.generate("A cat in a spaceship")

Dynamic (generic model, requires capability query):

val model = factory.generic(config.modelId)

val text = model.getOrThrow<TextCompletion>()
text.complete("Hello")

model.get<ImageGen>()?.generate("Sunset over mountains")

Path From Here

  1. #1581 — Introduces LlmMessageStreamer, essentially StreamingTextCompletion scoped to message-based LLM calls
  2. Lift message preparation upstream of provider implementations so capability interfaces receive fully-prepared inputs
  3. Extract capability interfaces from the existing SPI (LlmMessageSender → TextCompletion, LlmMessageStreamer → StreamingTextCompletion)
  4. Introduce GenericModel wrapper for dynamic capability resolution

Relationship to Existing Tag Interfaces

The codebase already has StreamingCapability and ThinkingCapability as marker interfaces for runtime capability detection. These answer "can this thing stream?" but don't define how — they carry no method contracts.

This proposal is a different layer: capability interfaces with actual signatures (complete(), stream(), generate()) that providers implement directly, with composition via interface inheritance and dynamic resolution via GenericModel.

Tag Interfaces (existing) Capability Interfaces (proposed)
Purpose Runtime detection ("does it support X?") Provider contract ("how to do X")
Methods None (markers) Concrete signatures
Composition N/A ChatModel : TextCompletion, StreamingTextCompletion
Dynamic resolution instanceof check GenericModel.get<T>()

The two are complementary — tag interfaces could evolve into (or be replaced by) capability interfaces, since implementing StreamingTextCompletion inherently signals streaming support.

jasperblues avatar Apr 07 '26 21:04 jasperblues

capabilities also got expressed as "gerund"-like ops: creating, rendering, streaming, thinking (some of them also having "support" API). how propsal futs to "gerund" -like model.

igordayen avatar Apr 10 '26 00:04 igordayen

capabilities also got expressed as "gerund"-like ops: creating, rendering, streaming, thinking (some of them also having "support" API). how propsal futs to "gerund" -like model.

They sit at different layers, not in conflict.

Two layers

  • PromptRunner.Creating / Rendering / Streaming / Thinking are user-facing fluent operation modes at the agent API. They scope a configured PromptRunner to a particular mode of use — orchestrating examples, property filtering, validation, template rendering, thinking extraction. They are framework concepts that read naturally as gerunds because they describe what the runner is doing right now.

  • The proposed TextCompletion / StreamingTextCompletion / ImageGen are the interfaces a model vendor implements to plug in and provide capabilities in a compositional way:

    class Gpt5Client    : TextCompletion, StreamingTextCompletion, ImageGen { ... }
    class ClaudeClient  : TextCompletion, StreamingTextCompletion { ... }
    class SdxlClient    : ImageGen { ... }
    

    Each vendor declares the traits it implements; the trait set IS the model. These interfaces sit at the wire — receiving fully-prepared inputs — and read naturally as nouns because they describe what kind of thing a provider is.

    This is the layer the gerund layer dispatches to.

How they connect

ai().promptRunner().creating(MyClass).fromPrompt("...")
        ↓  (assembles messages, examples, tools, validation)
        ↓  (dispatches to)
    TextCompletion.complete(preparedMessages)

#1581 already does this for streaming — LlmMessageStreamer is essentially StreamingTextCompletion scoped to message-based calls. This proposal generalises the move to other modalities.

Gerund availability tracks the trait set

Which gerund accessors are valid on a given runner depends on which traits the underlying model implements. Some gerunds are 1:1 with traits, others are orchestration on top of a trait every model has.

Gerund (user API) Underlying trait(s) (SPI) Relationship
creating(MyClass) TextCompletion orchestration on top of one trait
rendering(template) TextCompletion orchestration on top of one trait
streaming() StreamingTextCompletion 1:1
thinking() thinking-capable TextCompletion 1:1 (gated, plus config check)

So traits are the wire and gerunds are the workshop built around the wire — not redundant. A trait gives you complete(preparedMessages); a gerund gives you creating(MyClass).withExamples(...).fromPrompt(...) which assembles those messages and parses the result.

The smoking gun: three drifting sources of truth

Today, capability detection on PromptRunner is spread across three things that can drift:

  1. A marker interface (StreamingCapability, ThinkingCapability)
  2. A supports*() bool
  3. An override-or-throw method on PromptRunner

PromptRunner.kt:558 literally has the footgun in a comment:

"Implementation error: supportsThinking() returned true but withThinking() not overridden."

Three sources of truth, no compiler help keeping them aligned, and an "implementation error" message in production code that the type system should have prevented.

Reimplementing supports*() as a projection

The trait check collapses the drift. At the SPI, no markers and no bools — vendors just declare which traits they implement, and that IS the answer. At the user API, supportsStreaming() stays (it's discoverable, reads naturally in branches, doesn't leak the trait registry into user code) but its body becomes a one-line projection:

// Vendor side — declare what you support, nothing else to keep in sync
class AnthropicClient : TextCompletion, StreamingTextCompletion { ... }

// PromptRunner — user-facing accessor stays, body is now a projection
fun supportsStreaming(): Boolean = model.get<StreamingTextCompletion>() != null

supportsThinking() is the same shape with an extra config-enabled check ANDed on — the structural form composes naturally with side conditions like that. Best of both: discoverable bool for users, single source of truth for maintainers, override-coordination footgun gone.

The existing tag interfaces can be deleted

The marker interfaces (StreamingCapability, ThinkingCapability) are exactly the seam where the two layers meet today — markers without method contracts. As capability traits land the markers can be deleted: implementing StreamingTextCompletion is itself the signal. (com.embabel.common.core.streaming.StreamingCapability is already deprecated in favour of the nested form, so this is a natural continuation.)

Why the noun and gerund forms aren't interchangeable

Try forcing each layer into the other's convention and the awkwardness shows up immediately.

Gerund at the SPI:

class AnthropicClient : TextCompleting, Streaming, ImageGenerating { ... }
// reads as: "AnthropicClient IS-A TextCompleting" — wrong tense for a type

Noun at the user API:

ai().promptRunner()
    .creation(NewsResult::class.java)   // a getter for a noun?
    .withExamples(...)
    .fromPrompt("...")

Versus the natural forms:

// SPI — declaring what a vendor IS
class AnthropicClient : TextCompletion, StreamingTextCompletion { ... }

// User API — describing what the runner is DOING
ai().promptRunner()
    .creating(NewsResult::class.java)
    .withExamples(...)
    .fromPrompt("...")

Same word root, different grammatical role: creating is a verb phrase for an in-flight operation; TextCompletion is a noun phrase for a trait a provider has. Forcing one convention across both layers loses information about which side of the API you're standing on.

jasperblues avatar Apr 10 '26 02:04 jasperblues

class Gpt5Client : TextCompletion, StreamingTextCompletion, ImageGen { ... } class ClaudeClient : TextCompletion, StreamingTextCompletion { ... } class SdxlClient : ImageGen { ... }

@jasperblues - getting more clarity. and more inquiries too:)

Problem statements: define set of capabilities for LLM Client Providers (per my understanding).

LLMMessagestreamer just follows already established pattern of LLMMessageSender. Followup inquiry: would not capabilities be factored into (possibly extended) LLMMessageSender as a target model?

Current XYZ Capabilities - being currently as "tagged" interfaces - can be enhanced as well. Tagging also helps with polymorphic filtering of runners by capabilities.

igordayen avatar Apr 10 '26 14:04 igordayen

@jasperblues - getting more clarity. and more inquiries too:)

Problem statements: define set of capabilities for LLM Client Providers (per my understanding).

LLMMessagestreamer just follows already established pattern of LLMMessageSender. Followup inquiry: would not capabilities be factored into (possibly extended) LLMMessageSender as a target model?

Current XYZ Capabilities - being currently as "tagged" interfaces - can be enhanced as well. Tagging also helps with polymorphic filtering of runners by capabilities.

On LlmMessageSender as the target model

For text-based capabilities, the paths converge — and that's already happening. LlmMessageSender IS a text completion capability (messages + tools → response), and LlmMessageStreamer from #1581 IS a streaming text completion capability with the same input shape but a reactive output.

But the key reason for separate traits — even within text-based capabilities — is that models differ in what they support. Some stream, some don't. Some support thinking extraction, some don't. Lumping everything into an extended LlmMessageSender forces providers to stub out unsupported methods with throw UnsupportedOperationException() — which is exactly the footgun the proposal eliminates. Fine-grained traits create clean seams: a provider implements only what it supports, and the type system enforces the boundary instead of runtime guards.

This also applies across modalities, where the input/output shapes diverge entirely:

Modality Existing SPI Proposed trait Relationship
Text completion LlmMessageSender.call(messages, tools) TextCompletion Converge — LlmMessageSender IS a text completion with a richer signature
Streaming text LlmMessageStreamer (#1581) StreamingTextCompletion Converge — same pattern, reactive output
Image generation — (doesn't exist) ImageGen Standalone — input/output shape doesn't fit LlmMessageSender
Embeddings EmbeddingService (already separate) — Already its own SPI, confirming the pattern

LlmMessageSender and LlmMessageStreamer are the text-modality capability traits. The proposal generalises the pattern to modalities where LlmMessageSender's signature doesn't apply — and creates the seams that prevent a god-class from forming even within text-based capabilities.

On enhancing existing tag interfaces

It doesn't matter whether you think of it as adding methods to the existing tags, or deprecating them in favour of capability interfaces — that's the same thing, as long as the names are communicative. Either way you end up with a type that carries the method contract AND serves as the polymorphic filter: runners.filterIsInstance<StreamingTextCompletion>() works the same as runners.filterIsInstance<StreamingCapability>() today. One source of truth instead of a marker-plus-bool.

Whether you end up with StreamingCapability { fun stream(...) } or StreamingTextCompletion { fun stream(...) } — that's naming, not architecture. The type system doesn't care what the interface is called; it cares that the contract exists.

jasperblues avatar Apr 10 '26 18:04 jasperblues

@jasperblues - Jasper, as continuing discussion - i think what we are discussing conceptually is Model Metadata.

Concept seems exists already : pleasee see LlmMetadata. Can be enhanced as needed.

Model Metadata can be sourced from LLM Database.

Also: suggesting perhaps to convert from Issue to Discussion in order to continue discusion. Thanks.

igordayen avatar Apr 10 '26 18:04 igordayen

@jasperblues - Jasper, as continuing discussion - i think what we are discussing conceptually is Model Metadata.

Concept seems exists already : pleasee see LlmMetadata. Can be enhanced as needed.

Model Metadata can be sourced from LLM Database.

Also: suggesting perhaps to convert from Issue to Discussion in order to continue discusion. Thanks.

Metadata vs capabilities

LlmMetadata is descriptive data — name, provider, pricing, cutoff date. It answers "what is this model?" Capabilities answer a different question: "what can I do with this model?" The two are complementary but they're different kinds of thing:

// Metadata — passive, serializable, could come from a database
interface LlmMetadata {
    val name: String
    val provider: String
    val knowledgeCutoffDate: LocalDate?
    val pricingModel: PricingModel?
}

// Capability — behavioral contract, enforced by the type system
interface StreamingTextCompletion {
    fun stream(messages: List<Message>): Flux<String>
}
// Metadata — used for selection and display (passive, data)
val model = registry.find { it.metadata.provider == "Anthropic" }
println("Using ${model.metadata.name}, cutoff: ${model.metadata.knowledgeCutoffDate}")

// Capability — used to actually do something (active, compiler-checked)
if (model is StreamingTextCompletion) {
    model.stream(messages).collect { print(it) }
}

Metadata helps you find the right model. Capabilities let you use it. Both are needed; neither replaces the other.

A model registry or LLM database could list which capabilities a model supports — that's metadata about capabilities. But the capability itself is a contract with a method signature that the compiler enforces. model is StreamingTextCompletion is a compile-time type check, not a database lookup. Collapsing both into LlmMetadata would make a serializable data class also carry behavioral contracts — mixing the two concerns.

This is also the direction #1581 is already heading — LlmMessageStreamer is a behavioral capability contract for streaming, not metadata about whether streaming is available. This proposal is the natural continuation of that same pattern across other modalities.

Recommend to keep this as an issue as the format is working well to address design concerns in a structured way.

jasperblues avatar Apr 10 '26 19:04 jasperblues

i would like to comment that some capabilities might require dynamic detection, which means 3 levels of detection:

  • static metadata
  • contractual metadata, cimpiler-time support
  • dynamic validation.

igordayen avatar Apr 10 '26 19:04 igordayen

i would like to comment that some capabilities might require dynamic detection, which means 3 levels of detection:

  • static metadata
  • contractual metadata, compiler-time support
  • dynamic validation.

Three levels — and how they map

Good framework. These three levels are already covered in the proposal:

1. Static metadata — the shape of a record for searching in a repository. This is LlmMetadata today: name, provider, pricing, cutoff date. It answers "what models are available and what are their characteristics?" Data you query, filter, and display.

2. Capability traits — the contractual, composition-based architecture. This is the core of the proposal: TextCompletion, StreamingTextCompletion, ImageGen, etc. Providers implement the traits they support; the type system enforces the contract at compile time. A model's capability set is the aggregate of the types it adopts — no stubs, no runtime surprises.

3. Dynamic validation — helper methods or projections that make the gerund-based user API fluent. The proposal greatly simplifies these because they become one-line projections of the trait check:

fun supportsStreaming(): Boolean =
    model.get<StreamingTextCompletion>() != null

fun supportsThinking(): Boolean =
    model.get<ThinkingCapable>() != null && llm.thinking != Thinking.NONE

No separate markers, no bools to keep in sync — just a projection of what traits are present, optionally ANDed with config state. This is the layer that collapses the three-sources-of-truth drift described earlier in the thread.

The three levels are complementary: metadata helps you find a model, traits define what you can do with it, projections make capability checks fluent in user code.

jasperblues avatar Apr 10 '26 19:04 jasperblues

thanks, @jasperblues, and yes, there exists dynamic streaming detection capability in the current agent codebase.

igordayen avatar Apr 10 '26 21:04 igordayen

Metadata and traits are duals

Worth noting: the two layers aren't just separate — they're connected by a clean transform in both directions:

Metadata → traits (code generation): if a model registry says "GPT-5 supports text completion, streaming, image gen", you can generate the composition class:

class Gpt5Client : TextCompletion, StreamingTextCompletion, ImageGen { ... }

Traits → metadata (reflection): given a concrete provider, you can derive the capability list:

val capabilities = model::class.interfaces
    .filter { it.isSubclassOf(Capability::class) }
// → [TextCompletion, StreamingTextCompletion, ImageGen]

This validates the point about sourcing from an LLM database — the database is the source of truth for what capabilities a model has; traits are the compile-time form of how those capabilities work. The two connect via code gen in one direction and reflection in the other. Collapsing them into one class would lose the ability to transform between the two cleanly.

The separation is also important for the model lifecycle. The trait system allows users to use long-tail or unknown models before they exist in any database — you just implement the capability interfaces directly. The database can then use metadata to produce a composition of well-known traits into a concrete type, for convenience. A model that starts on the edge and gradually becomes popular follows a natural path: manual trait composition first, then a PR into the database, then a code-gen'd type. If capabilities were collapsed into metadata, unknown models would be blocked until someone adds them to the database.

I mentioned this direction — of exploring traits as a way to invoke an LLM — to Will as a potential path for the LLM database. He was open to exploring it, though I'm not sure how far that got.

jasperblues avatar Apr 10 '26 22:04 jasperblues

@jasperblues

Talking about Metadata:

Any plans for extensible model metadata definition? We would like to assign some models characteristics e.g. the maximum context window, the effective context window (found through evals and used to inform memory strategies in conversational setups), supported document file types ...

stefanks-px avatar May 05 '26 11:05 stefanks-px

@stefanks-px - is my undestanding proper - you might be interested to configure SlidingWindowTransformer with model propeties, as example. thanks

igordayen avatar May 05 '26 14:05 igordayen

@igordayen

Yes, this is something we are currently looking at. We are evaluating whether a token count based approach would be more suitable for us. The idea is to keep the context length below a sweetspot (found through evals or papers) per model. ToolLoopTransformer looks promising.

The other use case is about document analysis. Not every provider supports the same document types and we need to select the appropriate model for a request. The model could expresses the supportedDocumentTypes via metadata attribut. Extensible is sensible, as you as embabel maintainers won't be able hard code every characteristic user of the framework might need.

All in all this has a lower priority for us. We could also define the characteristics outside embabel by configuration properties. It just would be nicer to have it all in one place.

stefanks-px avatar May 05 '26 15:05 stefanks-px

@stefanks-px - if you are interested in using image, take a look at UserInput constucted of:

ContentPart.kt


data class ImagePart(
    val mimeType: String,
    val data: ByteArray
) : ContentPart 

Although name is ImagePart, ByteArray can be used for any Byte64 encoding, including PDF.

Though, current control on mime Type is image-specific. Thanks

igordayen avatar May 06 '26 03:05 igordayen

The stack for this is in #2185, with slides: https://claude.ai/artifact/QGbw7o3eEUAX19XTZmZF5W

Merge in order:

  1. #2180: adds the ModelCapability root; ModelType is frozen by a test.
  2. #2181: adds ChatCompletion and StreamingChatCompletion; LlmService no longer declares streaming.
  3. #2182: adds ModelRegistry, one selector for any capability; DecisionServiceRegistry is built on it.
  4. #2183: one generic resolver SPI keyed by an open ModelKind, and ModelPlatform, one per provider, which builds a model for a credential, kind and model name.
  5. #2184: adds the ModelFamily selection engine; ConfigurableModelProvider uses one selection per kind.
  6. #2187: names the well-known platforms (OpenAI, Mistral AI, DeepSeek, Anthropic) and adds OpenAiCompatiblePlatform for any other endpoint.
  7. #2186: thinking support on a prompt runner becomes a type, ThinkingPromptRunner, so the "Implementation error" path is gone.

jasperblues avatar Oct 23 '26 02:10 jasperblues

Jasper, I'm adding more decision providers and hit a gap in the capability stack. Writing it up here so we can sort it out in your design.

The case

DecisionService is one capability type. Several models implement it at once, and they differ inside the type.

Provider Protocol Questions per call Other differences
TypeSafe (Jev) System One 64
Cloudflare (Clef) System One 64 2 to 255 options, 2 to 10 rating levels, its own envelope
Ollama and other local servers System One set by the host
OpenAI Decisions API 400 per-call options such as a prompt cache key

More hosts of both protocols are coming. With four or more configured, "which model can answer this call" is the everyday question.

What happens today (read at capability-traits/5-thinking, 94ac3e67f)

  • ModelRegistry.select(type) finds every model with the type. ServiceSelector then offers defaultService(), named(), byRole() and using(). Nothing picks among models that share the type.
  • Two decision providers and no default gives AMBIGUOUS_DEFAULT at lookup.
  • DecisionCapabilities holds question kinds only. The registry reads it at build to write a log line. A mismatch shows up when the ask runs.
  • Cloudflare's limits live inside CloudflareBinding, so nothing outside can select on them.

Suggestions

  1. Selection by requirement. Something like selector.supporting(requirement): the default if it qualifies, otherwise the first eligible model that does, otherwise an error that says what each candidate lacks. named() and byRole() never reroute.
  2. Finer capability data per kind. The trait says a model can answer decisions. A question limit or an accepted option isn't a type, so it needs data next to the trait. stefanks-px asked for the same thing for chat in this thread (context window, document types). One mechanism could serve both.
  3. Capabilities declared in the provider catalog, with a startup check. It's already on the follow-up list in #2268. Decision models need it because a hosted model can't report its own limits.
  4. #2168. The decision registry caches one service per name, and it lives in -ai while the selection types live in -api. Selection by requirement depends on both, so I'd do it as part of that move.

Where I am

I'm holding the provider work (OpenAI decisions and the other hosts) until this settles. I want it to use your selector. Structured input for decisions is going ahead separately in #2263 to #2265.

Which of these do you want in the stack, and which as follow-ups?

jimador avatar Nov 19 '26 14:11 jimador