Skip to content

refactor(ai): one model seam: llmclient over three wire adapters behind one factory, no second provider stack #1001

Closed

Description

@dan-petty

Context & Rationale

There are two provider stacks, and the one a call uses depends on which agent runtime it happened to pick. Checked at 9c879ae.

  • LLMClient(OllamaProviderMixin, ClaudeProviderMixin, OpenAICompatProviderMixin, StructuredOutputMixin) (ai/client/unified.py:157). Providers are mixins, not adapters; dispatch is if p == "ollama" / "claude" / ("copilot", "openai", "gateway") at four sites (:252-274, :447-453, :768-774, :923-925). base.py is a mixin base, not a two-adapter seam.
  • A second stack, ai/providers/ (BaseLLMProvider.generate, 5 providers; providers/ollama.py does its own httpx2.get/post at :59 and :87) plus the pydantic_ai Provider re-exports, is used by pydantic_ai_bridge.resolve_pydantic_ai_model. tests/mock_provider.py adapts this stack, not LLMClient.
  • 26 direct LLMClient(...) constructions across 11 files; the factory get_llm_client lives in config/settings.py:1051 and has 3 callers.
  • Zero source callers: chat_structured, direct_request(_sync), model_request(_sync) and all of ai/direct.py.
  • HttpClientBroker (ARCHITECTURE.md's one connection broker) is used only by http/ and telemetry/memory_profiler.py. The AI client, rag/embeddings.py (4 httpx2.Client(, /api/embed), gateway.py (/v1/models, /api/tags) and 20 other source files open httpx2.Client directly.
  • Tests: test_ai_client_security.py monkeypatches httpx2.Client.post 10 times; client tests reach about 41 private names (_validate_response_text 7, _provider_http_error 5, _validate_base_url 4, _ollama_messages 4). tests/llm_stream_fakes.route_client (an httpx2 MockTransport) is a real adapter at the wire seam, used by 5 files.

Deletion test: delete direct.py, chat_structured, direct_request* and model_request* and nothing in src breaks. Delete ai/providers and it reappears in one place only, the bridge: a pass-through today.

Scope & Deliverables

  • Deliverable: LLMClient becomes three verbs (messages to response, messages to stream, list models) over provider adapter objects (Ollama NDJSON, OpenAI SSE, Anthropic SSE) behind one factory. The native pydantic_ai Model, embeddings and gateway probes are built from the same adapters. ai/providers, ai/direct.py and the dead entry points are deleted.
  • Tests: the httpx2.Client.post patches and private-attribute tests move to route_client; tests/mock_provider.py and test_providers.py become a fake at the LLMClient seam or go.
  • Key questions (open):
  • Constraint: provider-specific finish reasons and stream completeness (feat(ai): finish reasons and stream completeness for model replies #599) and the slot leasing in client/network.py must survive inside the adapters.

Strategic Alignment

Scope added 2026-10-02: checked at 38517a8. The second provider stack has no production caller, so the claim that a call's stack depends on the runtime it picked does not hold in production. ai/providers is imported only by pydantic_ai_bridge._resolve_remote_inferred_model (ai/pydantic_ai_bridge.py:96) and by the re-export in ai/agents/pydantic_agent.py:359. Its only route in is resolve_pydantic_ai_model, whose callers are create_pydantic_ai_agent (:236, called only by get_persona_pydantic_agent, :297, which nothing calls), build_fallback_cascade_model (:354, called only by GatewayRouter.build_pydantic_cascade_model, ai/gateway.py:554, which nothing calls), create_durable_pydantic_agent (ai/durable.py:571, no caller) and ai/direct.py (no caller). Every production model call goes through LLMClient. get_llm_client (config/settings.py:1062) has 1 caller, not 3. AGENTS.md:392 asks for "abstract provider protocols under providers/ (e.g. BaseLLMProvider)". That bullet is not in ai/instruction_generator.py, whose template holds about 50 of AGENTS.md's 388 substantive lines. AGENTS.md is curated, not generated: devops ai agents writes that short template over it (ai/instruction_generator.py:412-427), which #840 (v0.2.27) guards behind --force. So the convention changes in AGENTS.md itself. Correction to the body: HttpClientBroker is not used only by http/ and telemetry/memory_profiler.py. Vault (security/vault_broker.py:106, :148, :168; security/vault_lease.py:50) and the agent web-fetch tool (ai/common_tools.py:377) also call get_broker(). This item does not move model or embedding traffic onto the broker. #960 (v0.2.25, in flight) changes client timeouts, streamed response limits and model-resolution errors in the same files.

Acceptance criteria

  • Provider dispatch happens once, when the client is built. ai/client/unified.py has no provider-name chain (today at :251-262, :272-276, :447-453, :768-774, :922-927). Each provider is an adapter object: Ollama NDJSON, OpenAI-compatible SSE (OpenAI, Copilot, the gateway) and Anthropic SSE.
  • LLMClient offers three verbs: messages to a reply, messages to a stream, and list models. Every caller in src uses them.
  • One factory in ai/client/ builds clients per task. The 26 LLMClient(...) constructions outside it go, and config/settings.py:get_llm_client is deleted.
  • Slot leasing (ai/client/network.py) and feat(ai): finish reasons and stream completeness for model replies #599's finish reasons and stream completeness live in the adapters. The existing finish-reason and streaming tests pass unchanged.
  • ai/rag/embeddings.py and the gateway probes in ai/gateway.py use the adapters and open no httpx2.Client of their own for Ollama or the gateway.
  • Client and embedding tests stop patching httpx2.Client.post or .stream class-wide and use route_client or an adapter fake. At 38517a8 such patches sit in tests/test_ai_client_security.py (10), test_ai_client_providers_and_embeddings.py (17), test_rag_embeddings.py (10), test_thinking_providers.py (6) and test_review_embeddings_unserved.py (5). Client tests reach no underscored client name except the transport hooks route_client replaces.
  • AGENTS.md's model-seam bullet (:392, which refactor(ai): one agent runtime behind one construction point, with no silent fallback #1005 rewrites to name LLMClient) names the adapters and the factory. It is edited in place, not regenerated. ai/instruction_generator.py changes only if docs(agents): instruction surfaces state only what is true, and devops ai agents never overwrites AGENTS.md #840's mirror rule gives it a counterpart.
  • The tests run offline.
  • changelog.d/1001.md records the change under ### Changed. CHANGELOG.md is not edited.
  • uv run devops ci passes.
  • (person-run) devops ai chat, one devops review path and devops rag query run against the gateway and against a local Ollama.

Key questions

Test design: the model fake (2026-10-07)

The owner decided on 2026-10-07, in the test design #1307, that tests double only process edges, each through one seam, and that every fake ships with a contract suite. This item's one factory, which builds every LLMClient over the provider adapters, is the seam for the model edge. The adapter fake its tests use becomes that edge's shared fake.

Routing the inline LLMClient(...) constructions through the factory stays this item's work, as its acceptance criteria already say. At 5c45b1e there are 24 of them in 11 modules, besides the factory's own call [code: config/settings.py:1244] and a docstring example [code: ai/agents/pipeline.py:8]. The package migrations (#1326, #1328, #1330, #1331 and #1335) only confirm that none remains in their packages.

Acceptance criteria (added).

Strategic alignment (added).

Update 2026-10-08: owner decision on the adapters

The key question from the 2026-10-08 client-library audit is answered: pydantic-ai models are the model seam, called through pydantic_ai.direct. This replaces both this item's hand-written wire adapters and the alternative of separate openai and anthropic SDK clients.

How the item changes:

Update 2026-10-08: refinement

The owner decision replaces these parts:

Activity

  1. added
    type/refactor
    scope/ai
    priority/p2-medium
    on Oct 2, 2026
  2. dan-petty commented on Oct 3, 2026

    @dan-petty
    OwnerAuthor

    Lines cited at dcafadf.

    Two rewritten items change the clients and replies this item's adapters carry.

  3. dan-petty commented on Oct 8, 2026

    @dan-petty
    OwnerAuthor

    Part of this item's premise is out of date (checked 2026-10-08 at 910b823): chat_structured is no longer a zero-caller entry point. Since v0.2.26, roadmap intake (src/devops_cli/roadmap/intake_model.py:184) and refine (src/devops_cli/roadmap/refine.py:344, :792) call it in the roadmap service. So the deletion test ("delete … chat_structured … and nothing in src breaks") fails for it.

    Suggested amendment:

    This note covers only chat_structured. I did not re-check the other entry points on that line.

  4. dan-petty commented on Oct 8, 2026

    @dan-petty
    OwnerAuthor

    Proposed re-scope from the 2026-10-08 client-library audit (checked at release/v0.2.29, 05e9388): the adapters should be the official SDKs, not hand-written SSE decoders.

    What this deletes:

    • the per-provider frame decoders (ai/client/streaming.py:307-385);
    • the payload builders and response parsers in ai/client/openai.py and ai/client/claude.py;
    • the status-code error mapping, replaced by the SDKs' typed exceptions.

    #599's finish reasons map from the SDKs' finish_reason and stop_reason. Slot leasing in ai/client/network.py is untouched.

    Two defects show the cost of the hand-written path today: provider openai posts to https://api.openai.com/chat/completions without /v1 (config/constants.py:590), and the claude path sends budget_tokens and sampling that current Claude models reject (ai/client/claude.py:45-68). Both are filed separately as bugs that land on the SDK clients first, so this item then moves those clients behind its factory.

    Key question for the owner: do the adapters use the SDK sync clients, or pydantic-ai models through pydantic_ai.direct?

    Found by the 2026-10-08 client-library audit.

  5. 8 remaining items

  6. added
    priority/p1-high
    and removed
    priority/p2-medium
    on Oct 18, 2026
  7. dan-petty commented on Oct 19, 2026

    @dan-petty
    OwnerAuthor

    What changed

    #1707, merged into release/v0.2.37 as 20a0191.

    Closes #1001

    8 file(s) changed.

    How it was verified

    Check runs at 3345d7e:

    • Audit Defect PR Hardening: skipping
    • Prune PR DevContainer Images: pass
    • zizmor: pass
    • devops-cli: pass
    • bandit: pass
    • CodeQL: pass
    • Analyze (python): pass
    • Tests & Coverage: pass
    • Rule Pack Tests: pass
    • Changed-Test Independence: pass
    • Fail-to-Pass Self-Check: pass
    • Fail-to-Pass Check: pass
    • Analyze (actions): pass
    • Static Analysis: pass
    • Service Image: skipping
    • Dependency Freshness: skipping
    • DevContainer Image: skipping

    Acceptance Criteria of docs/agent/tasks/task-1001-one-model-seam.md:

    • Ships ModelFake under tests/support/fakes/model.py and re-exports in tests/support/fakes/__init__.py with __test__ = False.
    • Implements both pydantic_ai.models.Model interface and LLMClient duck typing (sync completion, streaming, model listing, deterministic embeddings).
    • Contract suite in tests/test_model_contract.py validates fake and real implementations (TestModel, LLMClient over recorded mock frames) offline without network.
    • Each test call phase stays under 1.0 s, and all contract and fixture tests pass.
    • create_pydantic_ai_provider injects http_client from the egress factory into pydantic-ai providers accepting it.
    • Direct spend tracking in src/devops_cli/ai/direct.py attributes provider, server, served-by, tokens, and finish reason across sync, async, and streaming direct requests.
    • Retired private pydantic_ai._run_context and _models_by_id references in src/devops_cli/ai/.
    • One factory in src/devops_cli/ai/client/factory.py builds clients per task.
    • config/settings.py:get_llm_client is deleted, and get_llm_client is re-exported from devops_cli.ai.client.
    • All inline LLMClient(...) constructions in src/ are routed to get_llm_client.
    • Conftest fixture model_fake registered in tests/conftest.py with factory seam integration.
    • Migrated existing caller test suites away from internal LLMClient patches.
    • Changelog fragment changelog.d/1001.md added.
    • Pending a person: devops ai chat, one devops review path, and devops rag query run against the gateway and against a local Ollama.
  8. added a commit that references this issue on Oct 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority/p1-highscope/aitype/refactor

    Type

    No type

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions