-
Notifications
You must be signed in to change notification settings - Fork 8
Microsoft.Extensions.AI IChatClient Implementation
This document describes the GenerativeAIChatClient
class, which implements the IChatClient
interface from Microsoft.Extensions.AI
. This implementation allows developers to seamlessly integrate Google's Generative AI models, specifically Gemini, into applications built using Microsoft's AI abstractions and dependency injection patterns. To use this functionality, you will need to install the Google_GenerativeAI.Microsoft NuGet package. This document will detail how to use this package.
The GenerativeAIChatClient
class provides a wrapper around the core GenerativeModel
from the Google_GenerativeAI SDK, adapting it to the IChatClient
interface. This allows for a consistent and familiar way to interact with Gemini models within .NET applications that utilize the Microsoft.Extensions.AI
library.
-
IChatClient Implementation: The
GenerativeAIChatClient
class implements all the necessary methods and properties of theIChatClient
interface, includingCompleteAsync
,CompleteStreamingAsync
, and theMetadata
property. -
Constructor Overloads: The class offers constructors that accept either an API key or an
IPlatformAdapter
(for platform-specific configurations), providing flexibility in how the underlyingGenerativeModel
is initialized. AmodelName
parameter allows you to specify which Gemini model to use (defaults toGoogleAIModels.DefaultGeminiModel
). -
Asynchronous Operations: The
CompleteAsync
andCompleteStreamingAsync
methods are asynchronous, ensuring that your application remains responsive while interacting with the Generative AI models. -
Streaming Support: The
CompleteStreamingAsync
method enables streaming responses, allowing you to process and display the generated content as it becomes available. -
Chat History Handling: The
IChatClient
interface itself manages the chat history. You provide the current set ofChatMessage
objects, and the client handles the context internally. - Dependency Injection Integration: The client is designed to be easily registered with .NET's dependency injection container, making it simple to manage and use within your application.
using GenerativeAI.Microsoft;
using Microsoft.Extensions.AI;
// ... in your service registration ...
services.AddScoped<IChatClient>(provider =>
new GenerativeAIChatClient(Environment.GetEnvironmentVariable("GOOGLE_API_KEY")));
// ... in your application code ...
public async Task<string> GetResponseAsync(string userMessage)
{
var chatHistory = new List<ChatMessage> { new ChatMessage(AuthorRole.User, userMessage) };
ChatCompletion completion = await _chatClient.CompleteAsync(chatHistory);
return completion.Content;
}
using GenerativeAI.Microsoft;
using Microsoft.Extensions.AI;
// ... in your application code ...
public async IAsyncEnumerable<string> StreamResponseAsync(string userMessage)
{
var chatHistory = new List<ChatMessage> { new ChatMessage(AuthorRole.User, userMessage) };
await foreach (var update in _chatClient.CompleteStreamingAsync(chatHistory))
{
yield return update.Content;
}
}
using GenerativeAI.Microsoft;
using Microsoft.Extensions.AI;
// ... in your application code ...
public async Task<string> GetResponseWithOptionsAsync(string userMessage, ChatOptions options)
{
var chatHistory = new List<ChatMessage> { new ChatMessage(AuthorRole.User, userMessage) };
ChatCompletion completion = await _chatClient.CompleteAsync(chatHistory, options);
return completion.Content;
}
using GenerativeAI.Microsoft;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.DependencyInjection;
// ...
public void ConfigureServices(IServiceCollection services)
{
// Get API key from environment variables (recommended).
string apiKey = Environment.GetEnvironmentVariable("GOOGLE_API_KEY");
// Basic configuration:
services.AddScoped<IChatClient>(provider => new GenerativeAIChatClient(apiKey));
}
-
Installation: Before using this functionality, make sure you have installed the Google_GenerativeAI.Microsoft NuGet package. You can install it using the NuGet Package Manager or the .NET CLI:
Install-Package Google_GenerativeAI.Microsoft
- API Key Management: Store your API key securely. Avoid hardcoding it directly in your code. Environment variables or user secrets are recommended.
- Error Handling: Implement proper error handling to manage potential exceptions during API calls.
- Rate Limiting: Be mindful of the API rate limits and implement appropriate strategies to handle them.
- Context Window: Large conversations might exceed the model's context window. Consider strategies for managing conversation history and truncating older messages if necessary.
-
Model Selection: The
modelName
parameter allows you to select the appropriate Gemini model for your task. Consider the capabilities and cost implications of different models.