Skip to main content
Hi there, I am Johnny
Posts All posts →

Microsoft extension AI

10 October 2024

Microsoft.Extensions.AI

Setup Azure OpenAI with

services.AddHttpClient(nameof(AzureOpenAIClient));
services.AddTransient<AzureOpenAIClient>(provider =>
    {
        var factory = provider.GetRequiredService<IHttpClientFactory>();
        var httpClient = factory.CreateClient(nameof(AzureOpenAIClient));
        var clientOptions = new AzureOpenAIClientOptions
        {
            Transport = new HttpClientPipelineTransport(httpClient)
        };
                 
        return new AzureOpenAIClient(new Uri(uri), new AzureKeyCredential(key), clientOptions);
     });

Setup IChatClient

services.AddChatClient(builder =>
    builder.Services.GetRequiredService<AzureOpenAIClient>()
    .AsChatClient("gpt-4o"));

Setup IEmbeddingGenerator

services.AddEmbeddingGenerator<string, Embedding<float>>(builder =>
    builder.Services.GetRequiredService<AzureOpenAIClient>()
    .AsEmbeddingGenerator("text-embedding-ada-002", default));

Sample code here