Introduction

Prerequisites

  • .NET 9 SDK
  • Azure subscription + AI Foundry project created at [ai.azure.com] (github.com, devblogs.microsoft.com)
  • NuGet packages: dotnet add package Azure.AI.Projects --prerelease dotnet add package Azure.Identity dotnet add package Microsoft.Extensions.AI dotnet add package Microsoft.Extensions.AI.OpenAI
  • Environment variables set for: AZURE_PROJECT_ENDPOINT AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET

Initializing the FoundryClient

using Azure.AI.Projects;
using Azure.Identity;

var endpoint = new Uri(Environment["AZURE_PROJECT_ENDPOINT"]!);
var cred = new DefaultAzureCredential();

var projectClient = new AIProjectClient(endpoint, cred);

This gives access to multiple sub-clients—Agents, Inference, OpenAI, Datasets, Indexes, etc. (learn.microsoft.com)


1️⃣ Use Case #1: Intelligent Chatbot

Leverages IChatClient to power a chat interface.

Setup

using Microsoft.Extensions.AI.OpenAI;

builder.Services.AddOpenAIChatClient("foundry",
    options =>
    {
        options.Endpoint = Environment["AZURE_PROJECT_ENDPOINT"];
        options.Credential = cred;
    });

Chat Loop Example

var chat = host.Services.GetRequiredService<IChatClient>("foundry");

var messages = new List<ChatMessage>
{
    new ChatMessage(ChatRole.System, "Be a helpful assistant.")
};
 
while(true)
{
    Console.Write("You: ");
    var input = Console.ReadLine();
    if (string.IsNullOrEmpty(input)) break;
    messages.Add(new ChatMessage(ChatRole.User, input));

    var resp = await chat.GetResponseAsync(messages);
    Console.WriteLine($"AI: {resp}"); 

    messages.Add(new ChatMessage(ChatRole.Assistant, resp));
}

✅ Instant chat experience using GPT‑4o or your connected model.


2️⃣ Use Case #2: Image/Video Generation

Using samples from Microsoft’s GitHub GenAI for .NET (devblogs.microsoft.com, learn.microsoft.com, github.com).

using Azure.AI.OpenAI;
using Azure.Core;

var client = new OpenAIClient(new Uri(Environment["AZURE_OPENAI_ENDPOINT"]), new AzureKeyCredential(Environment["AZURE_OPENAI_KEY"]));

var imgResponse = await client.GetImageGenerationsAsync("gpt-image-1", new ImageGenerationOptions { Prompt="a serene mountain lake at sunset", Size=ImageSize.Size1024 });
var url = imgResponse.Value.Data.First().Url;
Console.WriteLine($"Image URL: {url}");

For video with Azure Sora:

var vidResponse = await client.GetVideoGenerationAsync("sora-video-1", new VideoGenerationOptions { Prompt="fast-paced city timelapse", Resolution= "720p" });
var vidUrl = vidResponse.Value.Data.First().Url;
Console.WriteLine($"Video URL: {vidUrl}");

🎨 Perfect for dynamic visual content creation on the fly.


3️⃣ Use Case #3: Retrieval-Augmented Generation (RAG)

Combine embeddings + vector search (local or Azure) + LLM summarization.

Ingest & Embed Documents

var embeddingClient = host.Services.GetRequiredService<IEmbeddingGenerator>();
var store = new JsonVectorStore("vectorstore.json");

var text = File.ReadAllText("docs/guide.txt");
var embedding = await embeddingClient.GetEmbeddingAsync(text);
await store.UpsertAsync(new Document { Id="guide", Text=text, Vector=embedding });

Query RAG

var query = "How do I generate images with Sora?";
var qEmbed = await embeddingClient.GetEmbeddingAsync(query);
var results = await store.SearchAsync(qEmbed, new VectorSearchOptions { Limit = 3 });

var chat = host.Services.GetRequiredService<IChatClient>("foundry");
var prompt = $"You are an assistant. Use these docs:\n{string.Join("\n---\n", results.Select(r=>r.Text))}\nAnswer: {query}";
var resp = await chat.GetResponseAsync(new[]{ new ChatMessage(ChatRole.User,prompt)});
Console.WriteLine(resp);

🔍 Serve dynamic context-aware answers powered by your own data.


4️⃣ Bonus: Local AI with Foundry Local

Run Mistral on-device with Azure-compatible APIs (github.com, learn.microsoft.com, devblogs.microsoft.com, medium.com):

foundry model load mistralai-Mistral-7B-Instruct-v0-2-generic-cpu
foundry service status

C# client:

var chatClient = new ChatClient("mistralai-Mistral‑7B‑Instruct‑v0‑2‑generic‑cpu",
    new ApiKeyCredential("local"),
    new OpenAIClientOptions { Endpoint = new Uri("http://localhost:5273/v1") })
    .AsIChatClient();

Console.WriteLine(await chatClient.GetResponseAsync("Give me a summary of Hamlet."));

🔐 Fully offline, low-cost generative AI support.


🎯 Summary

FeatureKey Benefit
💬 ChatbotBuilt-in client, GPT‑4o, simple chat
🎨 Image/VideoUse OpenAI models directly in .NET
🧠 RAGCombine embeddings + LLM + your data
🏠 Local AIFoundry Local + OpenAI-compatible API

This guide illustrates how easy it is to harness .NET 9 + C# with Azure AI Foundry, Microsoft.Extensions.AI, and both local/cloud models. From chatbots and image/video generators to intelligent RAG assistants and offline AI, Microsoft’s unified stack empowers developers to build powerful generative-AI apps with minimal code.

Happy building!

Views: 45

🚀 Getting Started with .NET 9 + Azure AI Foundry

Johannes Rest


.NET Architekt und Entwickler


Beitragsnavigation


Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht verĂśffentlicht. Erforderliche Felder sind mit * markiert