All articles

Pointing the OpenAI .NET SDK at LiteLLM: retries, keys and cost

You can point the official OpenAI .NET SDK at a LiteLLM proxy by setting Endpoint on OpenAIClientOptions and passing a LiteLLM virtual key as the credential, but three things need attention once you do. Turn the SDK's own retries off with new ClientRetryPolicy(maxRetries: 0), because the proxy already retries and the two layers multiply. Register one client per proxy key as a keyed service, so each flow is billed and limited on its own key. And read the cost the proxy charged from the x-litellm-response-cost response header, because the response body does not carry it.

Why keep the SDK at all

The service I was working on had two kinds of model call. Most flows already went through a small typed HttpClient that posts to the proxy's OpenAI-compatible endpoint. A handful still used the official SDK directly: ChatClient for chat completions and the Responses API client for calls that need built-in tools such as web search. Rewriting those onto raw HTTP would have meant re-implementing the Responses request and response shapes by hand, so the plan was to keep the SDK types and change only where they send requests.

That part is easy. The SDK lets you replace the base address, and LiteLLM speaks the same wire format, so the existing request-building code keeps working:

using System.ClientModel;
using System.ClientModel.Primitives;
using OpenAI;

static OpenAIClient ProxyClient(Uri proxyUrl, string virtualKey) =>
    new(new ApiKeyCredential(virtualKey), new OpenAIClientOptions
    {
        Endpoint = proxyUrl,
        RetryPolicy = new ClientRetryPolicy(maxRetries: 0),
    });

The model name you pass to GetChatClient becomes a LiteLLM model name or alias rather than an OpenAI one. Everything else about the call site stays the same. The interesting part is what changes around it.

Why SDK retries and proxy retries multiply

The OpenAI .NET SDK is built on System.ClientModel, and its client options inherit a retry policy from ClientPipelineOptions. By default that policy retries a failed request a few times with exponential backoff, for rate limits, server errors and network failures. Against api.openai.com that is a sensible default: there is nobody else between you and the model to retry for you.

A LiteLLM proxy is different. Its router can retry a failed upstream call itself, and in our setup it was configured to. So a single logical request from the service could fail upstream, be retried by the proxy, come back to the SDK as a 5xx, and then be sent again by the SDK, which starts the proxy's retries over. The number of upstream attempts is the product of the two retry counts, not the sum. Each attempt may be billed, each one holds a slot against the key's rate limit, and the caller waits for all of them before it sees the error.

The fix is one line per client, shown in the helper above: give the SDK a ClientRetryPolicy with maxRetries: 0, and let the proxy own retries. That keeps the retry budget in one place, where it is configured once for every consumer, instead of hidden in each service's client options. The same RetryPolicy property exists on the options class for the Responses client, and it needs the same setting; it is easy to fix one client and miss the other.

Why the retry test passed when it shouldn't have

The first wiring tests stood up a local HttpListener that recorded each request and replied with an error, then asserted on the path, the model and the Authorization header. They replied 400. That was deliberate at the time: the SDK does not retry a 400, so each test saw exactly one request and stayed fast.

It also meant no test could ever see a retry. A stub that only returns statuses the client never retries will pass whether retries are on or off. The test that pins the behaviour has to return a status the SDK would retry and assert that only one request arrived:

[Fact]
public async Task ProxyChatClient_DoesNotRetryAServerError()
{
    using var stub = new RecordingStub(statusCode: 500);
    ChatClient chat = ProxyClient(stub.BaseUrl, "test-key").GetChatClient("any-model");

    await Assert.ThrowsAsync<ClientResultException>(
        () => chat.CompleteChatAsync([new UserChatMessage("hi")]));

    Assert.Single(stub.Requests);
}

With the default policy this test fails with several recorded requests and takes a few seconds of backoff. With maxRetries: 0 it sees one. I'd write the same pair of tests for every client type that talks to the proxy.

One keyed client per proxy key

LiteLLM virtual keys are the unit of spend tracking, rate limiting and model access. Giving each flow its own key means its cost shows up on its own line and a runaway flow cannot exhaust another one's limit. It also means a key can be restricted to the aliases that flow uses, which catches a flow quietly asking for a model it was never meant to call.

With SDK clients, the key is baked into the client at construction, so one key means one client instance. .NET 8 keyed services fit this well:

services.AddKeyedSingleton("summaries", (sp, _) =>
{
    var o = sp.GetRequiredService<IOptions<ProxyOptions>>().Value;
    return ProxyClient(new Uri(o.BaseUrl), o.SummaryKey ?? o.DefaultKey)
        .GetChatClient("summaries");
});

public sealed class SummaryService([FromKeyedServices("summaries")] ChatClient chat)
{
    // ...
}

The fallback to a default key keeps local development simple; production sets the scoped one. A wiring test that resolves each keyed client from the container and checks which Authorization header reaches the stub is cheap, and it is the only place a swapped key would show up before production.

How to record the cost the proxy charged

Our calls are traced to Langfuse as generations. When a call goes straight to OpenAI, Langfuse can work out a cost from the model name and token counts. Behind a proxy that inference gets weaker: the model name in the request is an alias that may not match any entry in Langfuse's price table, and the proxy is the component that actually knows which upstream model ran and what it charged.

LiteLLM reports that figure in the x-litellm-response-cost response header, not in the JSON body, so the SDK's typed result does not expose it. The raw response does:

ClientResult<ChatCompletion> result = await chat.CompleteChatAsync(messages);

if (result.GetRawResponse().Headers.TryGetValue("x-litellm-response-cost", out string? raw)
    && double.TryParse(raw, NumberStyles.Float, CultureInfo.InvariantCulture, out double cost)
    && double.IsFinite(cost) && cost >= 0)
{
    activity?.SetTag("langfuse.observation.cost_details",
        JsonSerializer.Serialize(new Dictionary<string, double> { ["total"] = cost }));
}

Two details matter. Parse with CultureInfo.InvariantCulture: the header always uses a full stop as the decimal separator, and a host running under a culture that uses a comma will otherwise misread it or fail. And treat a missing, negative or non-finite value as "no cost" rather than zero, so a call the proxy didn't price doesn't look free. I also changed the provider recorded on these generations from OpenAI to LiteLLM, so a trace says which path the call took.

Key takeaways

  • The OpenAI .NET SDK can call a LiteLLM proxy unchanged by setting Endpoint on its client options and using a LiteLLM virtual key as the credential.
  • When the proxy retries upstream calls, set the SDK's RetryPolicy to new ClientRetryPolicy(maxRetries: 0) on every client type, or the two retry layers multiply attempts.
  • A test stub that only returns 400 can never reveal a retry; return a 500 and assert a single request.
  • Register one keyed SDK client per LiteLLM virtual key so each flow's spend, limits and model access stay separate.
  • Read the proxy's billed cost from the x-litellm-response-cost header through GetRawResponse(), parsed with the invariant culture.

Written by Artem Shymko, a senior software engineer in Belgium working on Drupal, .NET and LLM features. Get in touch if you are working on something similar.