Principle:2aronS Duel Agents Default Injection Subclassing
| Knowledge Sources | |
|---|---|
| Domains | Framework_Integration, API_Design |
| Last Updated | 2026-10-27 14:00 GMT |
Overview
Pattern for integrating a routing proxy into an existing ML framework by subclassing an OpenAI-compatible base class and injecting default values (model, base URL, API key) via a framework-native validation hook, so users get the proxy's defaults without changing their existing code.
Description
ML orchestration frameworks like LangChain and LlamaIndex already have mature, well-tested chat model classes (`ChatOpenAI`, `OpenAILike`) that implement the OpenAI wire protocol, streaming, tool calling, and serialization. Re-implementing these for a new proxy would be a massive duplication of effort and a maintenance burden.
Default injection subclassing solves this by:
- Subclassing, not wrapping — the new class extends the existing base class, inheriting all its methods (`invoke`, `stream`, `complete`, `chat`) without reimplementation
- Framework-native default injection — rather than overriding methods, the subclass uses the framework's own validation/init hook to fill in defaults before the base class sees them:
- In LangChain (Pydantic v2), a `@model_validator(mode="before")` class method receives the raw input dict and uses `setdefault()` to fill in missing fields
- In LlamaIndex, the `__init__` method resolves env vars and passes the result to `super().__init__()`
- Environment-variable fallback — when the user does not pass an explicit key or URL, the hook reads from environment variables (`DUEL_API_KEY`, `DUEL_PROXY_URL`), so the class works out of the box in configured environments
- Secret declaration — for frameworks that serialize models (LangChain), the key field is mapped to an environment variable name via `lc_secrets`, so the key is not written to serialized output
The result is a class that drops into existing framework code with a one-line import change, and routes all traffic through the proxy by default.
Usage
Use this principle when:
- Integrating a proxy or custom endpoint into LangChain, LlamaIndex, or similar frameworks
- You want to inherit all upstream functionality (streaming, tools, async) without reimplementing it
- The only differences from the base class are default values (model name, base URL, key source)
- You want users to be able to override any default by passing it explicitly
Theoretical Basis
The LangChain variant uses a Pydantic v2 "before" validator, which runs on the raw input before Pydantic coerces types:
# Abstract algorithm (NOT real implementation)
class ChatDuel(ChatOpenAI):
@model_validator(mode="before")
@classmethod
def _set_duel_defaults(cls, values: Any) -> Any:
if not isinstance(values, dict):
return values
values.setdefault("model", "duel-auto")
values.setdefault("base_url", os.getenv("DUEL_PROXY_URL", DEFAULT_BASE))
if not values.get("api_key") and not values.get("openai_api_key"):
env_key = os.getenv("DUEL_API_KEY")
if env_key:
values["api_key"] = env_key
return values
The LlamaIndex variant overrides `__init__` and forwards to the superclass:
class DuelLLM(OpenAILike):
def __init__(self, model=DEFAULT_MODEL, api_base=DEFAULT_BASE,
api_key=None, is_chat_model=True, **kwargs):
api_base = os.getenv("DUEL_PROXY_URL", api_base)
api_key = api_key or os.getenv("DUEL_API_KEY")
super().__init__(model=model, api_base=api_base, api_key=api_key,
is_chat_model=is_chat_model, **kwargs)
Both share the same invariant: the base class receives fully-resolved arguments and behaves identically to a direct instantiation, only the defaults have changed.
The secret declaration in LangChain maps the key field to an env var name so serialization omits the plaintext:
@property
def lc_secrets(self) -> dict[str, str]:
return {"openai_api_key": "DUEL_API_KEY"}