Junaid.GoogleGemini.Net
4.0.0
dotnet add package Junaid.GoogleGemini.Net --version 4.0.0
NuGet\Install-Package Junaid.GoogleGemini.Net -Version 4.0.0
<PackageReference Include="Junaid.GoogleGemini.Net" Version="4.0.0" />
paket add Junaid.GoogleGemini.Net --version 4.0.0
#r "nuget: Junaid.GoogleGemini.Net, 4.0.0"
// Install Junaid.GoogleGemini.Net as a Cake Addin #addin nuget:?package=Junaid.GoogleGemini.Net&version=4.0.0 // Install Junaid.GoogleGemini.Net as a Cake Tool #tool nuget:?package=Junaid.GoogleGemini.Net&version=4.0.0
Junaid.GoogleGemini.Net
An open-source .NET library to use Gemini API based on Google�s largest and most capable AI model yet.
Installation of Nuget Package
.NET CLI:
> dotnet add package Junaid.GoogleGemini.Net
Package Manager:
PM > Install-Package Junaid.GoogleGemini.Net
Authentication
Get an API key from Google's AI Studio here.
Add the API key to appsettings.json
like this:
"Gemini": {
"Credentials": {
"ApiKey": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}
}
Or pass the API key as an environment variable named "GeminiApiKey".
Configuration
Configure the GeminiHttpClientOptions
first.
builder.Services.Configure<GeminiHttpClientOptions>(builder.Configuration.GetSection("Gemini"));
Then call AddGemini
extension method which configures a typed http client named GeminiClient
and library services.
builder.Services.AddGemini();
Services
There are five services:
- TextService
- VisionService
- ChatService
- ModelInfoService
- EmbeddingService
Each service has an interface. Obtain service instances by using their interfaces from the DI container.
The first three services from the above list contain the GenereateContentAsync
method to generate text-only content, the StreamGenereateContentAsync
method to provide a stream of text-only output and the CountTokensAsync
method to count tokens.
GenereateContentAsync
is used to generate content in textual form. The input parameters to this method vary from service to service, however, an optional input parameter namedconfiguration
of typeGenerateContentConfiguration
is common among all services. For information on its usage navigate to the configuration section of this page.The
GenereateContentAsync
method returns theGenerateContentResponse
object. To just get the text string inside this object, use the methodText()
as shown in the code snippets given below.The
StreamGenereateContentAsync
takes the same parameters asGenereateContentAsync
in their respective service, with an additional delegateAction<string>
.The
CountTokensAsync
method takes the same parameters asGenereateContentAsync
in their respective service. It does not take the optionalconfiguration
parameter.
The following sections show example code snippets that highlight how to use these services.
1. TextService
TextService
is used to generate content with text-only input. It has three methods.
The
GenereateContentAsync
method takes a mandatorystring
(text prompt) as input, an optionalGenerateContentConfiguration
(model parameters and safety settings) argument and returns theGenerateContentResponse
response object.app.MapGet("/", async (ITextService service) => { var result = await service.GenereateContentAsync("Say hello to me."); return result.Text(); });
The
StreamGenereateContentAsync
method is used to generate the stream of text-only content....... Action<string> handleStreamData = (data) => { Console.WriteLine(data); }; await service.StreamGenereateContentAsync("Write a story on Google AI.", handleStreamData);
The
CountTokensAsync
method is used to get the total tokens count. When using long prompts, it might be useful to count tokens before sending any content to the model....... var result = await service.CountTokensAsync("Write a story on Google AI."); Console.WriteLine(result.totalTokens);
2. VisionService
VisionService
is used to generate content with both text and image inputs. It has three methods.
The
GenereateContentAsync
method takes mandatorystring
(text prompt) andFileObject
(file bytes and file name), an optionalGenerateContentConfiguration
(model parameters and safety settings) argument and returns theGenerateContentResponse
response object.string filePath = "path/<imageName.imageExtension>"; var fileName = Path.GetFileName(filePath); byte[] fileBytes = Array.Empty<byte>(); try { using (var imageStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) using (var memoryStream = new MemoryStream()) { imageStream.CopyTo(memoryStream); fileBytes = memoryStream.ToArray(); } Console.WriteLine($"Image loaded successfully. Byte array length: {fileBytes.Length}"); } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); } var service = serviceProvider.GetService<IVisionService>(); var result = await service.GenereateContentAsync("Explain this image?", new FileObject(fileBytes, fileName)); Console.WriteLine(result.Text());
The
StreamGenereateContentAsync
method is used to generate the stream of text-only content....... Action<string> handleStreamData = (data) => { Console.WriteLine(data); }; await service.StreamGenereateContentAsync("Explain this image?", new FileObject(fileBytes, fileName), handleStreamData);
The
CountTokensAsync
method is used to get the total tokens count. When using long prompts, it might be useful to count tokens before sending any content to the model....... var result = await service.CountTokensAsync("Explain this image?", new FileObject(fileBytes, fileName)); Console.WriteLine(result.totalTokens);
3. ChatService
ChatService
is used to generate freeform conversations across multiple turns with chat history as input. It has three methods.
The
GenereateContentAsync
method takes an array ofMessageObject
as an argument, an optionalGenerateContentConfiguration
(model parameters and safety settings) argument and returns theGenerateContentResponse
response object.Each
MessageObject
contains two fields i.e. astring
named role (value can be either of "model" or "user" only) and anotherstring
named text (text prompt).var chat = new MessageObject[] { new MessageObject( "user", "Write the first line of a story about a magic backpack." ), new MessageObject( "model", "In the bustling city of Meadow brook, lived a young girl named Sophie. She was a bright and curious soul with an imaginative mind." ), new MessageObject( "user", "Write one more line." ), }; var service = serviceProvider.GetService<IChatService>(); var result = await service.GenereateContentAsync(chat); Console.WriteLine(result.Text());
The
StreamGenereateContentAsync
method is used to generate the stream of text-only content....... Action<string> handleStreamData = (data) => { Console.WriteLine(data); }; await service.StreamGenereateContentAsync(chat, handleStreamData);
The
CountTokensAsync
method is used to get the total tokens count. When using long prompts, it might be useful to count tokens before sending any content to the model....... var result = await service.CountTokensAsync(chat); Console.WriteLine(result.totalTokens);
Configuration
Configuration input can be used to control the content generation by configuring model parameters and by using safety settings.
An example of setting the configuration
parameter of type GenerateContentConfiguration
and passing it to the GenereateContentAsync
method of TextService
is as follows:
var configuration = new GenerateContentConfiguration
{
safetySettings = new []
{
new SafetySetting
{
category = CategoryConstants.DangerousContent,
threshold = ThresholdConstants.BlockOnlyHigh
}
},
generationConfig = new GenerationConfig
{
stopSequences = new List<string> { "Title" },
temperature = 1.0,
maxOutputTokens = 800,
topP = 0.8,
topK = 10
}
};
var result = await service.GenereateContentAsync("Write a quote by Aristotle.", configuration);
Console.WriteLine(result.Text());
4. ModelInfoService
ModelInfoService
is used to return information about the model being used to generate content. It has two methods.
The
ListModelsAsync
method lists all of the models available through the API, including both the Gemini and PaLM family models.app.MapGet("/", async (IModelInfoService service) => { var result = await service.ListModelsAsync(); });
The
GetModelAsync
takesstring
(model name) as input and returns information about that model such as version, display name, input token limit, etc....... var result = await service.GetModelAsync("gemini-pro-vision");
5. EmbeddingService
EmbeddingService
is used to represent information as a list of floating point numbers in an array. It has two methods.
EmbedContentAsync
takes astring
(model name) and anotherstring
(text prompt) as arguments. It returns theEmbedContentResponse
object.app.MapGet("/", async (IEmbeddingService service) => { var result = await service.EmbedContentAsync("embedding-001", "Write a story about a magic backpack."); });
BatchEmbedContentAsync
takes astring
(model name) and astring[]
(array of text prompts) as arguments. It returns theBatchEmbedContentResponse
object....... var result = await service.BatchEmbedContentAsync("embedding-001", new[] { "Write a story about a magic backpack.", "Say Hi to me!" });
GeminiClient
GeminiClient
is a "Typed HttpClient". A case may arise where a custom GeminiClient
is needed.
For example: Using proxy
In such a scenario, a custom HttpClient
object will be used to set proxy parameters. This object will then be used to initialize the GeminiClient
. To do so, several steps need to be performed:
Created a new Typed HttpClient
public class CustomClient : GeminiClient { public CustomClient(HttpClient httpClient) : base(httpClient) { } }
Add relevant configuration to the Typed HttpClient and register it with the DI container.
builder.Services.AddHttpClient<GeminiClient, CustomClient>((sp, client) => { var options = sp.GetRequiredService<IOptions<GeminiHttpClientOptions>>().Value; client.BaseAddress = options.Url; }) .ConfigurePrimaryHttpMessageHandler(() => { var proxy = new WebProxy { Address = new Uri("http://localhost:1080/") }; var httpClientHandler = new HttpClientHandler { Proxy = proxy, UseProxy = true }; //Not recommended for production httpClientHandler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; return httpClientHandler; }) .AddHttpMessageHandler<GeminiAuthHandler<GeminiHttpClientOptions>>();
Register the required service:
builder.Services.AddTransient<ITextService, TextService>();
Thanks for using this library.
Library needs improvements and the contributions are highly welcomed. Please read the contributing guidelines.
The API is being manually released on Nuget.org. The release notes file lists down the release notes.
Feel free to contact me via email if you have any questions or suggestions.
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net6.0 is compatible. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 is compatible. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. |
-
net6.0
- Microsoft.Extensions.Configuration.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Http (>= 8.0.0)
- Microsoft.Extensions.Options (>= 8.0.0)
-
net7.0
- Microsoft.Extensions.Configuration.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Http (>= 8.0.0)
- Microsoft.Extensions.Options (>= 8.0.0)
-
net8.0
- Microsoft.Extensions.Configuration.Abstractions (>= 8.0.0)
- Microsoft.Extensions.Http (>= 8.0.0)
- Microsoft.Extensions.Options (>= 8.0.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
- Using Dependency Injection.
- Using Typed HttpClient.
- Changed the way services are configured and consumed.