Building a Multi-Model Protocol Adapter Layer in 50 Lines of Code

    This article addresses the protocol mismatch that locks editor agents into a single backend. It shows how to build a local adapter that exposes a Responses-style endpoint while translating requests to Chat Completions, using file-based .NET execution, a vendor-neutral chat abstraction, dual routes, and automatic local configuration generation. Readers will learn the architecture, key implementation points, and security considerations for switching freely between local and cloud models.

    1. The Problem: Protocol Lock-In in Editor Agents

    Modern AI coding tools, especially editor-agent products, are already quite mature in terms of experience. They typically offer shell command execution, patch-based code edits, and plan tracking, closing the loop of read code, edit code, run tests, and fix issues within a single session. Architecturally, however, these tools are often tightly coupled to one backend protocol. The most common case is a design built around a Responses-style API: requests revolve around stateful reasoning units, while tool calls, incremental output, and session context are carried by server-side semantics.

    A large number of available model services follow a different route: the Chat Completions-style API. Local inference runtimes, model aggregation gateways, and self-hosted inference services mostly implement only the latter. The two protocols differ in request body structure, tool-call representation, and streaming event formats, so connecting them directly will inevitably fail.

    This creates a familiar pain point: the agent tool works well, but only with one vendor or one class of models. If you want to use a local model or another model from an aggregation platform, there is no path forward. This article tackles that protocol mismatch and offers a reusable, general solution.

    2. Core Idea: Treat It as Protocol Adaptation, Not Tool Modification

    Many people’s first instinct is to modify the agent tool itself. That path is costly and breaks with every upgrade. A better abstraction is this: the agent tool only recognizes protocols, not vendors. Since it allows you to point its configuration at any server that conforms to the Responses-style specification, you can run a local protocol adapter that presents itself externally as a Responses-style API and internally translates to Chat Completions. The agent tool then becomes a unified frontend for multiple models.

    The adapter must satisfy three constraints at once:

    • Protocol compatibility: expose a Responses-style endpoint for the agent tool, and optionally a Chat Completions-style endpoint for other editor plugins and scripts to reuse.
    • Vendor neutrality: access models internally through a unified abstraction, so switching backends changes only configuration, not business code.
    • Zero-friction onboarding: automatically generate the local configuration directory and files the agent tool needs, so developers never hand-assemble JSON.

    3. Technology Choices: Single-File Execution and Vendor-Neutral Abstraction

    In the .NET ecosystem, this approach can be compressed into a very small amount of code, relying on two key features:

    1. File-based programs: recent .NET versions can run a single code file directly as a program, removing project files and compilation boilerplate.
    2. Vendor-neutral chat abstraction: a unified chat client interface (commonly known as an IChatClient-style abstraction) hides differences between vendors. With the matching builder extensions, a single chained configuration attaches a backend.

    Illustrative code (structure only, not a specific product API):

    1. // Read backend URL and key from environment variables
    2. var baseUrl = Environment.GetEnvironmentVariable("MODEL_BASE_URL");
    3. var apiKey = Environment.GetEnvironmentVariable("MODEL_API_KEY");
    4. var model = Environment.GetEnvironmentVariable("MODEL_NAME");
    5. // Build a vendor-neutral chat client
    6. IChatClient client = new ChatClientBuilder()
    7. .UseOpenAIChat(baseUrl, apiKey) // Point to any Chat Completions-compatible service
    8. .Build(model);
    9. // Start a local service hosting both endpoint types
    10. await Host.RunAsync(client);

    This deliberately binds to no specific vendor: as long as the target service is Chat Completions-compatible, you only swap the base URL, key, and model name.

    4. Dual-Endpoint Design: One Core, Two Protocols

    The adapter exposes two core routes:

    • POST /v1/chat/completions: for general editing tools and scripts, using Chat Completions semantics.
    • POST /v1/responses: built for Responses-style agent tools. Internally, it translates a Responses request into several Chat Completions calls, then repackages the result into a Responses event stream.

    Both endpoints share the same configured chat client instance, so switching the backend model leaves the wire protocol completely unchanged, with zero changes on the agent tool side. Key implementation points include:

    • Request translation: map the instructions, context, and tool definitions in a Responses request into the message array and tool array of Chat Completions.
    • Tool-call loop: agent tools rely on tool calls to drive shell and patch capabilities. The adapter must restore tool calls returned by completions into Responses format and feed tool execution results back to continue reasoning.
    • Streaming conversion: reassemble Chat Completions incremental fragments into Responses incremental events, keeping frontend rendering free of flicker and dropped frames.
    • Session state: Responses-style APIs often carry a session identifier. The adapter can maintain context with a local mapping table to avoid repeatedly concatenating history.

    5. Zero-Friction Configuration: Automatic Local Config Generation

    Agent tools usually read backend information from a local configuration directory. A script can create the directory and write the config at startup, pointing the adapter at a local loopback port and declaring the Responses protocol. Example:

    1. var cfgDir = Path.Combine(
    2. Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
    3. ".config", "agent-cli");
    4. Directory.CreateDirectory(cfgDir);
    5. File.WriteAllText(Path.Combine(cfgDir, "config.toml"),
    6. $"""
    7. [model]
    8. base_url = "http://127.0.0.1:8080/v1"
    9. wire_api = "responses"
    10. model = "{model}"
    11. """);

    Note that a field like wire_api is an illustrative name; follow the tool’s documentation for the actual field. The core idea is: run a local service, write the config automatically, and declare the Responses protocol.

    6. Security and Engineering Considerations

    • Keep keys out of the repository: inject them via environment variables or a secret management service; the config file contains only the local address.
    • Listen on loopback only: bind the adapter to 127.0.0.1 by default to avoid exposing an unauthenticated model entry point to the public internet.
    • Timeouts and retries: local model inference is slower, so relax timeouts and apply a limited number of backoff retries.
    • Observability: use general logging and monitoring/alerting categories to record request latency, tool-call counts, and failure reasons.
    • Concurrency and rate limiting: local runtimes have limited concurrency, so queue requests to prevent concurrent agent subtasks from exhausting GPU or memory.

    7. Extension Directions

    This skeleton can evolve further: integrate object storage to save session snapshots; use a message queue to decouple long-running tasks; package multi-backend capabilities for unified delivery through a container platform; and apply routing policies per model (long context to a large-window model, code completion to a small model to reduce latency). If you use a cloud model service, you only replace the base URL and key, and the architecture stays the same.

    8. Conclusion

    Protocol mismatch is not a capability problem but a missing abstraction layer. With about 50 lines of code, a dual-endpoint protocol adapter, a vendor-neutral chat abstraction, and automatic config generation can turn an editor agent from a single-backend tool into a unified multi-model frontend, switching freely between local and cloud models while preserving the original agent experience and regaining the freedom to choose models.