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.
- Frontend endpoint: Receives Responses requests from the agent and returns the format the agent expects.
- Backend client: Communicates with any Chat Completions-compatible service through
IChatClient. - 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.
#!/usr/bin/env dotnet#:sdk Microsoft.NET.Sdk.Web#:package Microsoft.Extensions.AI@<version>#:package Microsoft.Extensions.AI.OpenAI@<version>#:package OpenAI@<version>using System.ClientModel;using Microsoft.Extensions.AI;using OpenAI;var baseUrl = Environment.GetEnvironmentVariable("BACKEND_BASE_URL") ?? "http://localhost:11434/v1";var apiKey = Environment.GetEnvironmentVariable("BACKEND_API_KEY") ?? "not-needed";var model = Environment.GetEnvironmentVariable("BACKEND_MODEL") ?? "qwen2.5-coder";IChatClient chatClient = new OpenAIClient(new ApiKeyCredential(apiKey),new OpenAIClientOptions { Endpoint = new Uri(baseUrl) }).GetChatClient(model).AsIChatClient();var app = WebApplication.Create(args);record ChatMessageDto(string Role, string Content);record ChatRequest(string Model, List<ChatMessageDto> Messages);app.MapPost("/v1/chat/completions", async (ChatRequest req, CancellationToken ct) =>{var messages = req.Messages.Select(m => new ChatMessage(new ChatRole(m.Role), m.Content)).ToList();ChatResponse response = await chatClient.GetResponseAsync(messages, cancellationToken: ct);return Results.Ok(new{id = "chatcmpl-" + Guid.NewGuid(),@object = "chat.completion",created = DateTimeOffset.UtcNow.ToUnixTimeSeconds(),model = req.Model,choices = new[]{new{index = 0,message = new { role = "assistant", content = response.Text },finish_reason = "stop"}}});});// Listen on the local loopback address onlyapp.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:
curl http://127.0.0.1:8080/v1/chat/completions \-H "Content-Type: application/json" \-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
instructionsinto a singlesystemmessage. - When
inputis a string, convert it into a singleusermessage. - When
inputis an array, convert each item according to itsrole. contentmay 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_callsinto Responsesfunction_calloutput items, keepingcall_ididentical to the originalid. - Convert the agent’s
function_call_outputinto a message withroleset totool, carrying the sametool_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.contentmaps to oneresponse.output_text.delta. - Parameter fragments in
delta.tool_callsmap toresponse.function_call_arguments.delta. Tool parameters arrive split across multiple fragments, so you must accumulate them byindexand only emitresponse.output_item.doneonce a tool call is complete. - When
finish_reasonappears, sendresponse.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 |
