.net-core.net-6.0dotnet-httpclientopenai-api

Define custom headers using .NET 6 OpenAI SDK


Technical details

Goal

Note: the values of the headers are not static. Each request can potentially have a different value.

Problem

I believe that the official SDK:

Questions


Solution

  • (!) Disclaimer: This is merely a solution to the initial requirement of adding custom headers. I am not knowledgeable enough to assess whether the solution is affecting the OpenAiClient capabilities in any way (!)

    The trick was to use a Pipeline policy (via the HttpClientPipelineTransport).

            services.AddTransient<CustomHeadersHandler>(); //this is a standard 'DelegatingHandler' implementation that adds HTTP headers
            services.AddHttpClient("OpenAiHttpClient", client =>
            {
                client.Timeout = TimeSpan.FromMilliseconds(apiTimeout);
            })
            .AddHttpMessageHandler<CustomHeadersHandler>();
    
            services.AddSingleton(services =>
            {
                var httpClientFactory = services.GetRequiredService<IHttpClientFactory>();
                var httpClient = httpClientFactory.CreateClient("OpenAiHttpClient");
    
                return new OpenAIClient(
                    new ApiKeyCredential(apiKey),
                    new OpenAIClientOptions
                    {
                        Endpoint = new Uri(apiUri),
                        NetworkTimeout = TimeSpan.FromMilliseconds(apiTimeout),
                        Transport = new HttpClientPipelineTransport(httpClient)
                    }
                );
            });