Technical details
OpenAIClient
class from the official OpenAI nuget libraryGoal
Note: the values of the headers are not static. Each request can potentially have a different value.
Problem
I believe that the official SDK:
HttpClient
object nor a DelegatingHandler
(which they could be used to define custom headers)Questions
(!) 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)
}
);
});