How to Build AI Apps in .NET 10 with Microsoft.Extensions.AI

Meta Description: Learn how to build AI apps in .NET 10 using Microsoft.Extensions.AI. Step-by-step guide for developers to integrate AI seamlessly....

By · · Updated · 7 min read · intermediate

Meta Description: Learn how to build AI apps in .NET 10 using Microsoft.Extensions.AI. Step-by-step guide for developers to integrate AI seamlessly.


Introduction

Artificial Intelligence (AI) is transforming how we build applications, and .NET developers are no exception. With the release of .NET 10 and the introduction of Microsoft.Extensions.AI, integrating AI into your applications has never been easier. Whether you're building chatbots, recommendation engines, or intelligent search functionalities, this library provides a standardized way to work with AI models, prompts, and responses.

In this guide, we’ll walk you through the process of building AI-powered applications in .NET 10 using Microsoft.Extensions.AI. You’ll learn how to:

  • Set up your .NET 10 environment for AI development.
  • Integrate AI models using Microsoft.Extensions.AI.
  • Build and test a simple AI-driven application.

Let’s dive in!


## 1. Setting Up Your .NET 10 Environment for AI Development

Before you start building AI apps, you need to ensure your development environment is ready. Here’s how to set it up:

Prerequisites

  • .NET 10 SDK: Download and install the latest .NET 10 SDK from the official .NET website.
  • Visual Studio 2022 (or later): Ensure you have the latest version of Visual Studio with the .NET 10 workload installed. Alternatively, you can use Visual Studio Code with the C# extension.
  • Microsoft.Extensions.AI NuGet Package: This library provides the tools you need to integrate AI into your .NET applications.

Step-by-Step Setup

1. Create a New .NET 10 Project

Open your terminal or command prompt and run the following command to create a new console application:

dotnet new console -n AiDotNetApp
cd AiDotNetApp

2. Add Microsoft.Extensions.AI to Your Project

Install the Microsoft.Extensions.AI NuGet package by running:

dotnet add package Microsoft.Extensions.AI --prerelease

Note: As of now, this package may be in prerelease, so include the --prerelease flag.

3. Verify Your Setup

Open the project in Visual Studio or your preferred code editor and ensure the package is listed in your .csproj file:

<PackageReference Include="Microsoft.Extensions.AI" Version="1.0.0-preview.*" />

4. Configure Your Development Environment

  • Enable preview features in your project by adding the following to your .csproj file:
    <EnablePreviewFeatures>true</EnablePreviewFeatures>
    
  • Restore the project dependencies:
    dotnet restore
    

Your environment is now ready for AI development in .NET 10!


## 2. Integrating AI Models with Microsoft.Extensions.AI

Now that your environment is set up, let’s integrate an AI model into your application using Microsoft.Extensions.AI. This library provides a unified interface for working with AI models, making it easier to switch between providers like Azure AI, OpenAI, or Hugging Face.

Key Concepts

  • AIClient: The primary interface for interacting with AI models.
  • Prompt: The input you provide to the AI model.
  • Response: The output generated by the AI model.
  • ChatCompletion: A specific type of AI interaction for conversational AI.

Step-by-Step Integration

1. Configure the AI Client

In your Program.cs file, add the following code to configure the AI client:

using Microsoft.Extensions.AI;

// Create an AI client using OpenAI's GPT-4 model
var aiClient = new OpenAIClient(
    new OpenAIClientOptions
    {
        ApiKey = "your-api-key-here", // Replace with your API key
        ModelId = "gpt-4"
    });

2. Create a Prompt

Define a prompt to send to the AI model. For example, let’s create a simple chat completion prompt:

var chatPrompt = new ChatPrompt(
    new ChatMessage("system", "You are a helpful assistant."),
    new ChatMessage("user", "What is the capital of France?"));

3. Send the Prompt and Get a Response

Use the AIClient to send the prompt and receive a response:

var response = await aiClient.CompleteChatAsync(chatPrompt);

if (response.IsSuccess)
{
    Console.WriteLine(
quot;AI Response: {response.Message.Content}"); } else { Console.WriteLine(
quot;Error: {response.ErrorMessage}"); }

4. Handle Streaming Responses

For real-time applications, you can stream responses from the AI model:

await foreach (var chunk in aiClient.CompleteChatStreamingAsync(chatPrompt))
{
    if (chunk.IsSuccess)
    {
        Console.Write(chunk.Message.Content);
    }
    else
    {
        Console.WriteLine(
quot;Error: {chunk.ErrorMessage}"); } }

## 3. Building a Simple AI-Powered Application

Let’s put it all together by building a simple AI-powered console application that answers user questions. This example will use OpenAI’s GPT-4 model, but you can easily swap it out for another provider.

Step-by-Step Implementation

1. Create the AI Service

Add a new class called AiService.cs to encapsulate the AI logic:

using Microsoft.Extensions.AI;

public class AiService
{
    private readonly AIClient _aiClient;

    public AiService(AIClient aiClient)
    {
        _aiClient = aiClient;
    }

    public async Task<string> GetAiResponseAsync(string userInput)
    {
        var chatPrompt = new ChatPrompt(
            new ChatMessage("system", "You are a helpful assistant."),
            new ChatMessage("user", userInput));

        var response = await _aiClient.CompleteChatAsync(chatPrompt);

        return response.IsSuccess
            ? response.Message.Content
            : 
quot;Error: {response.ErrorMessage}"; } }

2. Configure the Application

Update your Program.cs file to use the AiService:

using Microsoft.Extensions.AI;
using Microsoft.Extensions.DependencyInjection;

// Configure dependency injection
var services = new ServiceCollection();

// Add the AI client
services.AddSingleton<AIClient>(new OpenAIClient(
    new OpenAIClientOptions
    {
        ApiKey = "your-api-key-here", // Replace with your API key
        ModelId = "gpt-4"
    }));

// Add the AI service
services.AddSingleton<AiService>();

var serviceProvider = services.BuildServiceProvider();
var aiService = serviceProvider.GetRequiredService<AiService>();

// Interactive loop
Console.WriteLine("AI Assistant is ready! Type your question or 'exit' to quit.");
while (true)
{
    Console.Write("You: ");
    var userInput = Console.ReadLine();

    if (userInput?.ToLower() == "exit")
    {
        break;
    }

    var response = await aiService.GetAiResponseAsync(userInput);
    Console.WriteLine(
quot;AI: {response}"); }

3. Run the Application

Execute the application using the .NET CLI:

dotnet run

4. Test the Application

  • Type a question like "What is the weather today?" and press Enter.
  • The AI assistant will respond with an answer generated by the AI model.
  • Type "exit" to quit the application.

## 4. Best Practices for Building AI Apps in .NET 10

Building AI-powered applications is exciting, but it’s important to follow best practices to ensure your apps are scalable, secure, and maintainable. Here are some key tips:

1. Use Dependency Injection

  • Always use dependency injection (DI) to manage your AI clients and services. This makes it easier to swap out implementations and mock services for testing.

2. Handle Errors Gracefully

  • AI models can fail or return unexpected results. Implement robust error handling to manage:
    • API rate limits.
    • Network issues.
    • Invalid responses.

3. Optimize Prompts

  • The quality of your AI responses depends on the prompts you provide. Follow these tips:
    • Be clear and specific in your instructions.
    • Use examples to guide the AI’s behavior.
    • Avoid ambiguous language.

4. Secure Your API Keys

  • Never hardcode API keys in your application. Instead:
    • Use environment variables or Azure Key Vault.
    • Restrict API key permissions to minimize risks.

5. Monitor and Log AI Interactions

  • Track AI interactions to:
    • Debug issues.
    • Improve prompt engineering.
    • Monitor costs (if using paid APIs).

6. Stay Updated

  • AI libraries and models evolve rapidly. Stay updated with:
    • The latest versions of Microsoft.Extensions.AI.
    • New features in .NET 10.
    • Best practices for AI development.

Conclusion

Building AI-powered applications in .NET 10 with Microsoft.Extensions.AI is a game-changer for developers. This library simplifies the process of integrating AI models into your applications, allowing you to focus on creating innovative solutions rather than wrestling with complex APIs.

In this guide, you learned how to:

  1. Set up your .NET 10 environment for AI development.
  2. Integrate AI models using Microsoft.Extensions.AI.
  3. Build a simple AI-powered console application.
  4. Follow best practices for scalable and secure AI apps.

Now it’s your turn to experiment! Start by building a small AI-driven feature, like a chatbot or recommendation engine, and gradually expand its capabilities.


Call to Action

Ready to take your .NET applications to the next level with AI? Here’s what you can do next:

  • Explore the Microsoft.Extensions.AI documentation to learn more about advanced features.
  • Experiment with different AI models like Azure AI, OpenAI, or Hugging Face.
  • Join the .NET community to share your experiences and learn from other developers.

Happy coding! 🚀