AI Agent Dependency Injection 2026
Dependency injection for AI agents: Protocol-based interfaces, adapters, factory config, test doubles, and when an LLM gateway is the better answer.
📜 Table of Contents
📖 Keep reading
Dependency Injection for AI Agents: Swap Models Without Touching Code
Three hardcoded OpenAI calls inside one agent. Switching to a cheaper provider took an afternoon, two call sites were missed, and half the requests hit the old model. The bill doubled and the logs no longer reconciled.
That is structural, not carelessness: if "which model" lives inside business logic, every switch becomes a global search. Agents need injection more than most services because models, vector stores, tools and caches all change quarterly.
The one-sentence version
The agent should not know which model it uses, only that something accepts messages and returns text.
class Agent:
def __init__(self, llm):
self.llm = llm
Define capabilities with Protocol
from typing import Protocol, Sequence
class ChatModel(Protocol):
def chat(self, messages: Sequence[dict], **kw) -> str: ...
class Embedder(Protocol):
def embed(self, texts: Sequence[str]) -> list[list[float]]: ...
Protocols need no inheritance, so test doubles stay trivial. Keep interfaces to three methods or fewer; large interfaces become abstraction for its own sake.
Adapters normalize vendor differences
class DeepSeekChat:
def __init__(self, client, model="deepseek-chat"):
self.client, self.model = client, model
def chat(self, messages, **kw):
r = self.client.chat.completions.create(
model=self.model, messages=list(messages), **kw)
return r.choices[0].message.content
Return plain data, not vendor response objects, or the layer above stays coupled. Put retries, backoff and content-filter handling in the adapter so callers only distinguish success, retryable and fatal.
Factory plus config
llm:
provider: deepseek
model: deepseek-chat
timeout: 30
max_retries: 2
embedding:
provider: bge
model: bge-m3
def build_llm(cfg):
if cfg.provider == "deepseek":
return DeepSeekChat(make_client(cfg), cfg.model)
if cfg.provider == "ollama":
return OllamaChat(cfg.model, host=cfg.host)
raise ValueError(f"unknown provider: {cfg.provider}")
Validate config at startup. A misspelled provider should fail at boot, not on a user's first request.
Test doubles are the real payoff
class FakeLLM:
def __init__(self, reply): self.reply = reply
def chat(self, messages, **kw): return self.reply
def test_refund_flow():
agent = Agent(llm=FakeLLM("refund submitted"), tools=[FakeRefundTool()])
assert "refund" in agent.run("I want a refund").lower()
Millisecond tests, no network, no spend, no rate limits. Without injection, unit tests mock third-party libraries and break on every SDK upgrade.
Gateways are complementary
For multi-provider failover and centralized billing, an OpenAI-compatible gateway (LiteLLM, one-api) is faster: one base_url, one key.
| Approach | Good for | Bad for |
|---|---|---|
| In-code injection | per-call customization, multimodal differences | many teams and languages |
| Gateway | provider switching, quotas, unified logs | deep request-level customization |
| Both | large systems | small projects, over-engineering |
They compose: inject an interface whose implementation points at the gateway.
Seven things worth injecting
Model, vector store, retriever, reranker, cache layer, tool executor, clock and random seed. Clock and seed decide whether timeout and reproducibility tests can run at all.
FAQ
Does it add complexity? A few classes and a factory, against a global search on every switch.
Use a DI framework? Rarely in Python. Constructor arguments plus a factory do the job; framework magic hurts during incidents.
Where do defaults live? Config, so temperature, max tokens and timeouts change without a deploy.
Per-tenant models? Build from tenant config and cache instances, never per request.
Related
Written by our editorial team; tools listed here are tested or verified against public sources. Links point to official sites or GitHub repos for reference only — no paid placements.