|
1 | | -# AI - Question 14 - How would you design a DI-friendly service that can swap between local LlamaEdge models and OpenAI cloud models without changing the business logic? |
| 1 | +# AI - Question 14 - How would you design a DI-friendly service that can swap between local LlamaEdge models and OpenAI cloud models without changing the business logic? |
| 2 | + |
| 3 | +**Use `Microsoft.Extensions.AI` abstractions** (`IChatClient` and `IEmbeddingGenerator<TInput, TEmbedding>`) for a clean, DI-friendly, provider-agnostic design. This allows seamless swapping between cloud OpenAI and local models (via Ollama for Llama models or LlamaEdge’s OpenAI-compatible server) without altering business logic. |
| 4 | + |
| 5 | +### Core Design Principle |
| 6 | +Code against the **abstractions** (`IChatClient`). Register the concrete implementation (OpenAI, Azure, Ollama, etc.) in the DI container via configuration or environment. Middleware (logging, retry, telemetry, function calling) applies uniformly. |
| 7 | + |
| 8 | +**Provider-Agnostic Architecture** |
| 9 | +```mermaid |
| 10 | +flowchart TD |
| 11 | + A[Business Services] --> B[IChatClient Interface] |
| 12 | + C["Middleware Pipeline<br/>(Logging, Caching, FunctionCalling, OTEL)"] --> D{Configuration} |
| 13 | + B --> C |
| 14 | + D -->|Production| E["OpenAIChatClient / Azure"] |
| 15 | + D -->|Development / Edge| F["OllamaChatClient / LlamaEdge via OpenAI endpoint"] |
| 16 | + E --> G[Cloud LLM] |
| 17 | + F --> H[Local Llama Model] |
| 18 | + style B fill:#90EE90 |
| 19 | +``` |
| 20 | + |
| 21 | +### DI Registration (Program.cs / Startup) |
| 22 | +```csharp |
| 23 | +using Microsoft.Extensions.AI; |
| 24 | +using Microsoft.Extensions.DependencyInjection; |
| 25 | +using Microsoft.Extensions.Configuration; |
| 26 | + |
| 27 | +var builder = WebApplication.CreateBuilder(args); |
| 28 | + |
| 29 | +// Read configuration |
| 30 | +var aiSettings = builder.Configuration.GetSection("AI").Get<AISettings>() ?? new(); |
| 31 | + |
| 32 | +IChatClient chatClient; |
| 33 | + |
| 34 | +if (aiSettings.UseLocalModel) |
| 35 | +{ |
| 36 | + // Local: Ollama (recommended for Llama models) |
| 37 | + chatClient = new OllamaChatClient( |
| 38 | + new Uri(aiSettings.LocalEndpoint ?? "http://localhost:11434"), |
| 39 | + aiSettings.LocalModel ?? "llama3.2"); |
| 40 | + |
| 41 | + // Alternative: LlamaEdge (OpenAI-compatible server) |
| 42 | + // chatClient = new OpenAIChatClient( |
| 43 | + // new OpenAIClient(new ApiKeyCredential("ignored"), new OpenAIClientOptions |
| 44 | + // { |
| 45 | + // Endpoint = new Uri(aiSettings.LocalEndpoint) |
| 46 | + // })) |
| 47 | + // .GetChatClient(aiSettings.LocalModel); |
| 48 | +} |
| 49 | +else |
| 50 | +{ |
| 51 | + // Cloud |
| 52 | + chatClient = new OpenAIChatClient(aiSettings.OpenAIModel, aiSettings.ApiKey); |
| 53 | + // Or Azure: new AzureOpenAIChatClient(...) |
| 54 | +} |
| 55 | + |
| 56 | +// Add to DI with middleware |
| 57 | +builder.Services.AddChatClient(chatClient) |
| 58 | + .UseLogging() |
| 59 | + .UseFunctionInvocation() // For tool calling / agents |
| 60 | + .UseOpenTelemetry(); // Observability |
| 61 | +
|
| 62 | +// Optional: Keyed services for multiple models |
| 63 | +// builder.Services.AddKeyedChatClient("local", localClient); |
| 64 | +// builder.Services.AddKeyedChatClient("cloud", cloudClient); |
| 65 | +``` |
| 66 | + |
| 67 | +**Configuration Example (appsettings.json):** |
| 68 | +```json |
| 69 | +{ |
| 70 | + "AI": { |
| 71 | + "UseLocalModel": true, |
| 72 | + "LocalEndpoint": "http://localhost:11434", |
| 73 | + "LocalModel": "llama3.2", |
| 74 | + "OpenAIModel": "gpt-4o", |
| 75 | + "ApiKey": "sk-..." |
| 76 | + } |
| 77 | +} |
| 78 | +``` |
| 79 | + |
| 80 | +### DI-Friendly Service (No Provider Awareness) |
| 81 | +```csharp |
| 82 | +public interface IRagService |
| 83 | +{ |
| 84 | + Task<string> AnswerQuestionAsync(string question, CancellationToken ct = default); |
| 85 | +} |
| 86 | + |
| 87 | +public class RagService : IRagService |
| 88 | +{ |
| 89 | + private readonly IChatClient _chatClient; |
| 90 | + private readonly IEmbeddingGenerator<string, Embedding<float>> _embeddingGenerator; // Optional for RAG |
| 91 | +
|
| 92 | + public RagService(IChatClient chatClient, IEmbeddingGenerator<string, Embedding<float>> embeddingGenerator) |
| 93 | + { |
| 94 | + _chatClient = chatClient; |
| 95 | + _embeddingGenerator = embeddingGenerator; |
| 96 | + } |
| 97 | + |
| 98 | + public async Task<string> AnswerQuestionAsync(string question, CancellationToken ct = default) |
| 99 | + { |
| 100 | + // Business logic stays identical regardless of provider |
| 101 | + var history = new ChatHistory(); |
| 102 | + history.AddUserMessage(question); |
| 103 | + |
| 104 | + // Optional: RAG retrieval using embeddings... |
| 105 | +
|
| 106 | + var response = await _chatClient.GetResponseAsync( |
| 107 | + history, |
| 108 | + new ChatOptions { Temperature = 0.7f }, |
| 109 | + ct); |
| 110 | + |
| 111 | + return response.Message.Text ?? string.Empty; |
| 112 | + } |
| 113 | +} |
| 114 | + |
| 115 | +// Registration |
| 116 | +builder.Services.AddScoped<IRagService, RagService>(); |
| 117 | +``` |
| 118 | + |
| 119 | +**Mermaid: Service Dependency Flow** |
| 120 | +```mermaid |
| 121 | +flowchart TD |
| 122 | + subgraph "Business Layer" |
| 123 | + A[RagService / Agents] --> B[IChatClient] |
| 124 | + A --> C[IEmbeddingGenerator] |
| 125 | + end |
| 126 | + subgraph "DI Container" |
| 127 | + B --> D[OpenAI Implementation] |
| 128 | + B --> E[Ollama / LlamaEdge Implementation] |
| 129 | + end |
| 130 | + D --> F[Cloud] |
| 131 | + E --> G[Local Llama] |
| 132 | +``` |
| 133 | + |
| 134 | +### Key Benefits |
| 135 | +- **Zero business logic changes** when switching providers. |
| 136 | +- **Middleware reuse** — logging, retry, caching, and function calling work for both local and cloud. |
| 137 | +- **Environment-specific** behavior via configuration (local for dev/privacy, cloud for production scale/quality). |
| 138 | +- **Streaming support** remains identical using `IAsyncEnumerable<StreamingChatCompletionUpdate>`. |
| 139 | +- **Semantic Kernel compatibility** — SK works natively on top of `IChatClient`. |
| 140 | + |
| 141 | +### Local Model Notes (Llama) |
| 142 | +- **Ollama** is the most common, stable choice for Llama models in .NET via `OllamaSharp` / `Microsoft.Extensions.AI.Ollama` (or successor packages). |
| 143 | +- **LlamaEdge** exposes an OpenAI-compatible endpoint, so the standard `OpenAIChatClient` with a custom `Endpoint` works perfectly. |
| 144 | +- For pure native execution without a server, consider LLamaSharp or ONNX Runtime GenAI with custom wrappers implementing `IChatClient`. |
| 145 | + |
| 146 | +This design follows official Microsoft recommendations for provider-agnostic .NET AI applications. It scales from development (fast local iteration) to production (cloud reliability) while keeping your core application code clean and maintainable. Always test model-specific behaviors (context length, tool calling quality) when swapping. Refer to Microsoft Learn documentation for `Microsoft.Extensions.AI` for the latest configuration patterns. |
0 commit comments