Repository navigation
Description
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 isif p == "ollama"/"claude"/("copilot", "openai", "gateway")at four sites (:252-274,:447-453,:768-774,:923-925).base.pyis a mixin base, not a two-adapter seam.- A second stack,
ai/providers/(BaseLLMProvider.generate, 5 providers;providers/ollama.pydoes its ownhttpx2.get/postat:59and:87) plus the pydantic_aiProviderre-exports, is used bypydantic_ai_bridge.resolve_pydantic_ai_model.tests/mock_provider.pyadapts this stack, notLLMClient. - 26 direct
LLMClient(...)constructions across 11 files; the factoryget_llm_clientlives inconfig/settings.py:1051and has 3 callers. - Zero source callers:
chat_structured,direct_request(_sync),model_request(_sync)and all ofai/direct.py. HttpClientBroker(ARCHITECTURE.md's one connection broker) is used only byhttp/andtelemetry/memory_profiler.py. The AI client,rag/embeddings.py(4httpx2.Client(,/api/embed),gateway.py(/v1/models,/api/tags) and 20 other source files openhttpx2.Clientdirectly.- Tests:
test_ai_client_security.pymonkeypatcheshttpx2.Client.post10 times; client tests reach about 41 private names (_validate_response_text7,_provider_http_error5,_validate_base_url4,_ollama_messages4).tests/llm_stream_fakes.route_client(an httpx2MockTransport) 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:
LLMClientbecomes 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_aiModel, embeddings and gateway probes are built from the same adapters.ai/providers,ai/direct.pyand the dead entry points are deleted. - Tests: the
httpx2.Client.postpatches and private-attribute tests move toroute_client;tests/mock_provider.pyandtest_providers.pybecome a fake at theLLMClientseam or go. - Key questions (open):
- Where does the factory live (not
config/)? - Does the pydantic_ai
ModelwrapLLMClientor share its adapters? - Do embeddings (fix(ai): reviews ask an unserved embedding model on every lookup and search with a hash fallback #945) sit behind the same adapters or keep a separate verb?
- Where does the factory live (not
- 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.pymust survive inside the adapters.
Strategic Alignment
- Milestone: Backlog (no release)
- Design: none
- Depends on: none
- Related: fix(ai): client timeouts, streamed response limits, model-resolution errors and dead round-robin state #960, fix(ai): streamed
devops ai chatturns send the user's message #874, fix(ai): reasoning request parameters follow the model's declared capability, not its name #888, feat(ai): finish reasons and stream completeness for model replies #599, fix(ai): reviews ask an unserved embedding model on every lookup and search with a hash fallback #945, feat(ai): one json repair seam that counts repairs per entry point #875 - Source: architecture review of 2026-10-02, AI core
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.pyhas 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. -
LLMClientoffers three verbs: messages to a reply, messages to a stream, and list models. Every caller insrcuses them. - One factory in
ai/client/builds clients per task. The 26LLMClient(...)constructions outside it go, andconfig/settings.py:get_llm_clientis 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.pyand the gateway probes inai/gateway.pyuse the adapters and open nohttpx2.Clientof their own for Ollama or the gateway. - Client and embedding tests stop patching
httpx2.Client.postor.streamclass-wide and useroute_clientor an adapter fake. At 38517a8 such patches sit intests/test_ai_client_security.py(10),test_ai_client_providers_and_embeddings.py(17),test_rag_embeddings.py(10),test_thinking_providers.py(6) andtest_review_embeddings_unserved.py(5). Client tests reach no underscored client name except the transport hooksroute_clientreplaces. - AGENTS.md's model-seam bullet (
:392, which refactor(ai): one agent runtime behind one construction point, with no silent fallback #1005 rewrites to nameLLMClient) names the adapters and the factory. It is edited in place, not regenerated.ai/instruction_generator.pychanges only if docs(agents): instruction surfaces state only what is true, anddevops ai agentsnever overwrites AGENTS.md #840's mirror rule gives it a counterpart. - The tests run offline.
-
changelog.d/1001.mdrecords the change under### Changed.CHANGELOG.mdis not edited. -
uv run devops cipasses. - (person-run)
devops ai chat, onedevops review pathanddevops rag queryrun against the gateway and against a local Ollama.
Key questions
- Where does the factory live (not
config/)? (proposed)ai/client/factory.py, next to the adapters, soconfig/imports nothing fromai/. - Does the pydantic_ai
ModelwrapLLMClientor share its adapters? (proposed) Neither, in this item. No production code builds a native pydantic_aiModelorAgentat 38517a8. refactor(ai): one agent runtime behind one construction point, with no silent fallback #1005 deletes that path first, so this item refactors one stack. A nativeModeladapter is a later feature, if a native runtime is ever adopted. - Do embeddings (fix(ai): reviews ask an unserved embedding model on every lookup and search with a hash fallback #945) sit behind the same adapters or keep a separate verb? (proposed) A fourth verb,
embed, on the Ollama and OpenAI-compatible adapters, which share the base URL, auth and slot leasing. fix(ai): reviews ask an unserved embedding model on every lookup and search with a hash fallback #945's single-lookup tests are the regression check. - Which item deletes
ai/providers,ai/direct.pyand the dead entry points? (proposed) refactor(ai): one agent runtime behind one construction point, with no silent fallback #1005, because only the native path it deletes reaches them. This item then depends on refactor(ai): one agent runtime behind one construction point, with no silent fallback #1005, not the reverse, and its deliverable drops that deletion.chat_structuredgoes with refactor(ai): one structured-output path for validate, repair, reflect and retry #1003. - When does it land? (proposed) After refactor(ai): one agent runtime behind one construction point, with no silent fallback #1005, fix(ai): client timeouts, streamed response limits, model-resolution errors and dead round-robin state #960 (v0.2.25) and fix(ai): streamed
devops ai chatturns send the user's message #874 (v0.2.27), which fix behaviour this item moves.
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).
- Ships the edge's fake under
tests/support/fakes/and its contract suite (fake and real side, the real side against recorded responses or a local tool, never a live service), per the ADR "Tests double only process edges, through seams" that docs(cli): docs/TESTING.md holds the test conventions, ADR 0005 records that tests double only process edges, and AGENTS.md and the contributor docs point to them #1308 delivers.
Strategic alignment (added).
- Parent: test(cli): tests double only process edges and mirror the source tree #1307 (phase D).
- Depends on (added): test(cli): tests find the repository root and fixtures from any depth, import no other test module and build test data with shared builders, and devops test maps a change to its mirror directory #1312. Blocks (added): test(ai): devops review, devops analyze and the devops ai commands are thin adapters tested over the model seam and edge fakes #1326, test(review): ai/review and review/ are tested through one public interface over the model, tool-executor and process fakes, with no mock detection in src #1328, test(mcp): mcp, agent and tool tests run on edge fakes #1330, test(ai): the remaining ai modules are tested through their public interfaces on edge fakes, and the legacy provider layer leaves src #1331, test(infra): infrastructure tests run on edge fakes #1335.
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:
-
Models. Each provider is a pydantic-ai
Modelover a pydantic-ai provider built withhttp_client=from the egress factory (fix(security): every HTTP client dials only addresses its egress level allows, checked at the connect and on every redirect #898, refactor(cli): Unify HTTP and DNS seams with shared fakes #1314, fix(security): move the remaining HTTP clients onto the egress-checked factory and delete the pre-flight resolve paths #1381):- OpenAI, Copilot and the gateway use
OpenAIChatModelwithOpenAIProvider(base_url=…); - Claude uses
AnthropicModelwithAnthropicProvider.
No hand-written base URL, header, payload, SSE decoder or response parser remains (fix(ai): the openai provider without ai.api_base_url calls the OpenAI API's /v1 routes, built by the openai SDK #1427, fix(ai): the claude provider sends what current Claude models accept, built by the anthropic SDK #1428).
- OpenAI, Copilot and the gateway use
-
Sync client.
LLMClientstays synchronous throughmodel_request_syncandmodel_request_stream_sync, so callers don't change. -
Capabilities. Thinking, effort, sampling and structured output come from pydantic-ai model settings and profiles, never from model-name checks. Structured output uses pydantic-ai's output modes; see feat(ai): constrain structured replies on the claude, openai and copilot providers #1419.
-
Retries. pydantic-ai's providers get the factory client with its tenacity transport, and no second retry layer, so fix(ai): the spend ledger records every attempt the gateway failed, including the retry transport's, and its gap to the gateway's count is measured first #1019's attempt counts hold.
-
Finish reasons. feat(ai): finish reasons and stream completeness for model replies #599's finish reasons map from pydantic-ai's
ModelResponse.finish_reason. -
Ollama. pydantic-ai's
OllamaProviderspeaks Ollama's OpenAI-compatible API, which ignores native options such asnum_ctx(fix(ai): sampling settings reach the model or are refused, review sessions record them, and the reply cache key includes them #1070). Settle in this item's first step whether Ollama goes through pydantic-ai, with the context size set on the server, or keeps a thin native adapter on the factory client. Record which, and why, in the task file. -
refactor(ai): one agent runtime behind one construction point, with no silent fallback #1005. The pydantic-ai provider route that refactor(ai): one agent runtime behind one construction point, with no silent fallback #1005 planned to delete (
resolve_pydantic_ai_model, the pydantic-ai providers inai/providers/__init__.py,ai/direct.py) becomes this seam, rebuilt on the factory client, rather than being deleted. The legacyBaseLLMProviderclasses (test(ai): the remaining ai modules are tested through their public interfaces on edge fakes, and the legacy provider layer leaves src #1331) still go.
Update 2026-10-08: refinement
The owner decision replaces these parts:
- Each provider is a pydantic-ai
Modelbuilt withhttp_client=fromdevops_cli.http.client;LLMClientwraps them throughmodel_request_syncandmodel_request_stream_sync. - This item keeps and rebuilds
ai/direct.pyandresolve_pydantic_ai_model; test(ai): the remaining ai modules are tested through their public interfaces on edge fakes, and the legacy provider layer leaves src #1331 deletes the legacy classes; no dependency on refactor(ai): one agent runtime behind one construction point, with no silent fallback #1005. LLMClientalready uses the factory (ai/client/base.py:71); embeddings and the gateway probes remain (fix(security): move the remaining HTTP clients onto the egress-checked factory and delete the pre-flight resolve paths #1381).chat_structuredhas callers; drop it from the deletion test (refactor(ai): one structured-output path for validate, repair, reflect and retry #1003 moves it).- No
pydantic_ai._import insrc(core/validation.py:17,http/egress.py:29,ai/durable.py:389). - fix(ai):
analyze --enhancedandai agentsuse theai.tasks.metadatamodel #1068'smetadatatask survives the factory move.
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone
Activity
dan-petty commentedon Oct 3, 2026
Lines cited at dcafadf.
Two rewritten items change the clients and replies this item's adapters carry.
fix(security): every HTTP client dials only addresses its egress level allows, checked at the connect and on every redirect #898 puts every raw
httpx2.Client(insrconto one client factory, whose transport checks each connection against the address actually dialled. Its second PR moves the AI clients:ai/client/base.py:72and:74,ai/rag/embeddings.py(:523,:553,:700,:817) and the gateway probes (ai/gateway.py:250,:384,:591). If fix(security): every HTTP client dials only addresses its egress level allows, checked at the connect and on every redirect #898 has landed, the adapters take their client from that factory. If not, build each adapter's client in one place so fix(security): every HTTP client dials only addresses its egress level allows, checked at the connect and on every redirect #898 swaps it there.fix(ai): replies carry their server as an httpx2 origin, so a password in an AI URL stays out of output, the spend ledger, metrics, spans and cache #1110 replaces the
type (host)string that_extract_server_from_backend_info(ai/client/unified.py:61-67) parses back with a field onLLMResponse(ai/client/models.py:88) holdinghttpx2.URL(base).origin. Whichever of this item and fix(ai): replies carry their server as an httpx2 origin, so a password in an AI URL stays out of output, the spend ledger, metrics, spans and cache #1110 lands second carries that field through the adapters."Every HTTP client" and this item's statement that it "does not move model or embedding traffic onto the broker" agree: fix(security): every HTTP client dials only addresses its egress level allows, checked at the connect and on every redirect #898's PR B gives the AI clients their client from its factory (checked at connect), and this item's adapters take that client while staying off the broker.
dan-petty commentedon Oct 8, 2026
Part of this item's premise is out of date (checked 2026-10-08 at 910b823):
chat_structuredis 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 insrcbreaks") fails for it.Suggested amendment:
chat_structuredfrom the "Zero source callers" line and from the deletion test.chat_structuredgoes with refactor(ai): one structured-output path for validate, repair, reflect and retry #1003" to "refactor(ai): one structured-output path for validate, repair, reflect and retry #1003 moves intake and refine onto the one structured-output path".This note covers only
chat_structured. I did not re-check the other entry points on that line.dan-petty commentedon Oct 8, 2026
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.
openai.OpenAI(OpenAI; 3.26.1, released 2026-10-08).anthropic.Anthropic(Anthropic; 1.12.1, released 2026-10-08).http_client=. fix(security): every HTTP client dials only addresses its egress level allows, checked at the connect and on every redirect #898's connect-time check therefore holds, andtests/llm_stream_fakes.route_client(an httpx2MockTransport) stays the HTTP-edge fake.max_retries=0, so the factory's tenacity transport remains the one retry layer and fix(ai): the spend ledger records every attempt the gateway failed, including the retry transport's, and its gap to the gateway's count is measured first #1019's attempt accounting holds.What this deletes:
ai/client/streaming.py:307-385);ai/client/openai.pyandai/client/claude.py;#599's finish reasons map from the SDKs'
finish_reasonandstop_reason. Slot leasing inai/client/network.pyis untouched.Two defects show the cost of the hand-written path today: provider
openaiposts tohttps://api.openai.com/chat/completionswithout/v1(config/constants.py:590), and theclaudepath sendsbudget_tokensand 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?LLMClient, needs anAsyncClientper thread, and reverses refactor(ai): one agent runtime behind one construction point, with no silent fallback #1005's plan to deleteai/direct.py.Found by the 2026-10-08 client-library audit.
8 remaining items
refactor(test): in-memory model fake and contract suite (Part of #1001)…
refactor(ai): provider adapters over pydantic-ai models with egress f…
refactor(ai): consolidate LLM client construction into client factory…
refactor(ai): model_fake fixture and factory seam registration (Part of
refactor(ai): complete model seam test migrations and client fake duc…
dan-petty commentedon Oct 19, 2026
What changed
#1707, merged into
release/v0.2.37as 20a0191.8 file(s) changed.
How it was verified
Check runs at 3345d7e:
Acceptance Criteria of
docs/agent/tasks/task-1001-one-model-seam.md:ModelFakeundertests/support/fakes/model.pyand re-exports intests/support/fakes/__init__.pywith__test__ = False.pydantic_ai.models.Modelinterface andLLMClientduck typing (sync completion, streaming, model listing, deterministic embeddings).tests/test_model_contract.pyvalidates fake and real implementations (TestModel,LLMClientover recorded mock frames) offline without network.create_pydantic_ai_providerinjectshttp_clientfrom the egress factory into pydantic-ai providers accepting it.src/devops_cli/ai/direct.pyattributes provider, server, served-by, tokens, and finish reason across sync, async, and streaming direct requests.pydantic_ai._run_contextand_models_by_idreferences insrc/devops_cli/ai/.src/devops_cli/ai/client/factory.pybuilds clients per task.config/settings.py:get_llm_clientis deleted, andget_llm_clientis re-exported fromdevops_cli.ai.client.LLMClient(...)constructions insrc/are routed toget_llm_client.model_fakeregistered intests/conftest.pywith factory seam integration.LLMClientpatches.changelog.d/1001.mdadded.devops ai chat, onedevops review path, anddevops rag queryrun against the gateway and against a local Ollama.feat(release): v0.2.37 (#1720)
refactor(ai): chat_structured is the one structured-output path (#2452)