Building an Adapter Layer to Connect Coding Agents to Multiple Models via Chat Completions

    A minimal .NET implementation of an adapter layer that lets Responses-style coding agents talk to any Chat Completions-compatible backend. This article covers the key protocol differences, a minimal working skeleton, the mappings needed for tool calls and streaming events, and a troubleshooting checklist.

    Scoping the Work First

    A skeleton of about 50 lines only handles non-streaming, single-turn conversations. To make a Responses-style coding agent fully functional, you also need to handle streaming events, bidirectional mapping of tool calls, and error responses. This part typically takes several hundred lines of code, depending on which event types the agent uses. This article covers the skeleton and the missing pieces separately.

    Differences Between the Two Protocols

    Both protocols describe “multi-turn messages going in and out of a model,” but their field structures differ. The table below lists the differences coding agents encounter most often. Verify these before implementing any mapping.

    Dimension Responses style Chat Completions style
    Request endpoint POST /v1/responses POST /v1/chat/completions
    Input content input, which can be a string or an array messages, where each element has role and content
    System instructions Top-level instructions field A message with role set to system
    Tool definitions name and parameters at the top level of each tool item Nested inside a function object
    Tool call output A function_call output item containing call_id A tool_calls array in the assistant message
    Tool result return A function_call_output input item A message with role set to tool, containing tool_call_id
    Streaming events Semantic events such as response.output_text.delta data: blocks with content in choices[0].delta
    End signal A response.completed event data: [DONE]

    The Three Parts of an Adapter Layer

    The adapter layer consists of three parts.

    1. Frontend endpoint: Receives Responses requests from the agent and returns the format the agent expects.
    2. Backend client: Communicates with any Chat Completions-compatible service through IChatClient.
    3. Mapping logic: Converts messages, tool definitions, tool call results, and streaming events between the two protocols.

    The frontend handles the protocol shape, the backend handles model calls, and the mapping logic is the only place that needs to understand the details of both sides.

    Minimal Skeleton

    You need the .NET 10 SDK to run this. WebApplication requires the Web SDK, so the file header uses Microsoft.NET.Sdk.Web. Replace the package versions with the ones you use. The IChatClient method names have changed between previews: earlier previews used CompleteAsync, while newer versions use GetResponseAsync. Check the documentation for your version.

    1. #!/usr/bin/env dotnet
    2. #:sdk Microsoft.NET.Sdk.Web
    3. #:package Microsoft.Extensions.AI@<version>
    4. #:package Microsoft.Extensions.AI.OpenAI@<version>
    5. #:package OpenAI@<version>
    6. using System.ClientModel;
    7. using Microsoft.Extensions.AI;
    8. using OpenAI;
    9. var baseUrl = Environment.GetEnvironmentVariable("BACKEND_BASE_URL") ?? "http://localhost:11434/v1";
    10. var apiKey = Environment.GetEnvironmentVariable("BACKEND_API_KEY") ?? "not-needed";
    11. var model = Environment.GetEnvironmentVariable("BACKEND_MODEL") ?? "qwen2.5-coder";
    12. IChatClient chatClient = new OpenAIClient(
    13. new ApiKeyCredential(apiKey),
    14. new OpenAIClientOptions { Endpoint = new Uri(baseUrl) })
    15. .GetChatClient(model)
    16. .AsIChatClient();
    17. var app = WebApplication.Create(args);
    18. record ChatMessageDto(string Role, string Content);
    19. record ChatRequest(string Model, List<ChatMessageDto> Messages);
    20. app.MapPost("/v1/chat/completions", async (ChatRequest req, CancellationToken ct) =>
    21. {
    22. var messages = req.Messages
    23. .Select(m => new ChatMessage(new ChatRole(m.Role), m.Content))
    24. .ToList();
    25. ChatResponse response = await chatClient.GetResponseAsync(messages, cancellationToken: ct);
    26. return Results.Ok(new
    27. {
    28. id = "chatcmpl-" + Guid.NewGuid(),
    29. @object = "chat.completion",
    30. created = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
    31. model = req.Model,
    32. choices = new[]
    33. {
    34. new
    35. {
    36. index = 0,
    37. message = new { role = "assistant", content = response.Text },
    38. finish_reason = "stop"
    39. }
    40. }
    41. });
    42. });
    43. // Listen on the local loopback address only
    44. app.Run("http://127.0.0.1:8080");

    Save the file as adapter.cs and run it with dotnet run adapter.cs. Use the following command for a smoke test:

    1. curl http://127.0.0.1:8080/v1/chat/completions \
    2. -H "Content-Type: application/json" \
    3. -d '{"model":"qwen2.5-coder","messages":[{"role":"user","content":"Hello"}]}'

    This skeleton does not implement the /v1/responses endpoint, streaming output, or tool calls. The next section explains what needs to be added for these three parts.

    Mapping the Responses Endpoint

    The mapping falls into three categories. Each category needs at least one working example and corresponding test cases.

    Message roles and content

    • Convert instructions into a single system message.
    • When input is a string, convert it into a single user message.
    • When input is an array, convert each item according to its role.
    • content may be a string or an array of content parts, so normalize it by concatenating into text.

    Tool definitions

    A Responses tool item like { "type": "function", "name": "...", "parameters": {...} } must be expanded into the Chat Completions shape { "type": "function", "function": { "name": "...", "parameters": {...} } }. The parameters JSON Schema can be kept as-is, but you should check whether the backend supports the keywords used in that schema.

    Tool call round trips

    • Convert the backend’s tool_calls into Responses function_call output items, keeping call_id identical to the original id.
    • Convert the agent’s function_call_output into a message with role set to tool, carrying the same tool_call_id.

    Converting Streaming Events

    Responses streaming output includes events such as response.created, response.output_text.delta, response.function_call_arguments.delta, response.output_item.done, and response.completed. Chat Completions streaming output is a sequence of data: blocks ending with data: [DONE].

    The conversion rules are as follows.

    • Each delta.content maps to one response.output_text.delta.
    • Parameter fragments in delta.tool_calls map to response.function_call_arguments.delta. Tool parameters arrive split across multiple fragments, so you must accumulate them by index and only emit response.output_item.done once a tool call is complete.
    • When finish_reason appears, send response.completed.

    Event names and fields must match the version the agent uses. The most reliable approach is to capture the requests the agent actually sends, or read the parsing logic in its source code.

    Troubleshooting Guide

    Symptom Likely cause How to diagnose
    The agent keeps waiting and never finishes A missing end event or [DONE] Check the last event in the adapter logs
    Tool parameter parsing fails Fragments concatenated in the wrong order, or not accumulated by index Print each fragment as it arrives and verify the merge order