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
| Feature | Key Benefit |
|---|---|
| đŹ Chatbot | Built-in client, GPTâ4o, simple chat |
| đ¨ Image/Video | Use OpenAI models directly in .NET |
| đ§ RAG | Combine embeddings + LLM + your data |
| đ Local AI | Foundry 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
