GeminiSharp 0.0.1.8

dotnet add package GeminiSharp --version 0.0.1.8
                    
NuGet\Install-Package GeminiSharp -Version 0.0.1.8
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="GeminiSharp" Version="0.0.1.8" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="GeminiSharp" Version="0.0.1.8" />
                    
Directory.Packages.props
<PackageReference Include="GeminiSharp" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add GeminiSharp --version 0.0.1.8
                    
#r "nuget: GeminiSharp, 0.0.1.8"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package GeminiSharp@0.0.1.8
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=GeminiSharp&version=0.0.1.8
                    
Install as a Cake Addin
#tool nuget:?package=GeminiSharp&version=0.0.1.8
                    
Install as a Cake Tool

GeminiSharp - the C# library for the Google Gemini API

Comprehensive API for interacting with Google's Gemini models supporting text, chat, image generation, file uploads, grounding, code execution, model tuning, and more.

Frameworks supported

Dependencies

The DLLs included in the package may not be the latest version. We recommend using NuGet to obtain the latest version of the packages:

Install-Package Newtonsoft.Json
Install-Package JsonSubTypes
Install-Package System.ComponentModel.Annotations

Installation

dotnet add package GeminiSharp

Usage

Connections

Each ApiClass (properly the ApiClient inside it) will create an instance of HttpClient. It will use that for the entire lifecycle and dispose it when called the Dispose method.

To better manager the connections it's a common practice to reuse the HttpClient and HttpClientHandler (see here for details). To use your own HttpClient instance just pass it to the ApiClass constructor.

HttpClientHandler yourHandler = new HttpClientHandler();
HttpClient yourHttpClient = new HttpClient(yourHandler);
var api = new YourApiClass(yourHttpClient, yourHandler);

If you want to use an HttpClient and don't have access to the handler, for example in a DI context in Asp.net Core when using IHttpClientFactory.

HttpClient yourHttpClient = new HttpClient();
var api = new YourApiClass(yourHttpClient);

You'll loose some configuration settings, the features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. You need to either manually handle those in your setup of the HttpClient or they won't be available.

Here an example of DI setup in a sample web project:

services.AddHttpClient<YourApiClass>(httpClient =>
   new PetApi(httpClient));

Getting Started

using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using GeminiSharp.Api;
using GeminiSharp.Client;
using GeminiSharp.Model;
using Serilog;
using Serilog.Sinks.Console;

namespace Example
{
    public class Example
    {
        public static void Main()
        {
            // Configure Serilog
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug() // Set minimum logging level
                .WriteTo.Console()    // Output logs to console
                .CreateLogger();

            Configuration config = new Configuration();
            config.BasePath = "https://generativelanguage.googleapis.com";
            // Assign the logger to the configuration
            config.Logger = Log.Logger;
            // Configure API key authorization: ApiKeyHeader
            config.ApiKey.Add("x-goog-api-key", "YOUR_API_KEY");
            // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
            // config.ApiKeyPrefix.Add("x-goog-api-key", "Bearer");
            // Configure API key authorization: ApiKeyQuery
            config.ApiKey.Add("key", "YOUR_API_KEY");
            // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
            // config.ApiKeyPrefix.Add("key", "Bearer");

            // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes
            HttpClient httpClient = new HttpClient();
            HttpClientHandler httpClientHandler = new HttpClientHandler();
            var apiInstance = new GeminiApi(httpClient, config, httpClientHandler);
            var model = "model_example";  // string | 
            var batchEmbedContentsRequest = new BatchEmbedContentsRequest(); // BatchEmbedContentsRequest | 

            try
            {
                // Batch Embed Contents
                BatchEmbedContents200Response result = apiInstance.BatchEmbedContents(model, batchEmbedContentsRequest);
                Debug.WriteLine(result);
            }
            catch (ApiException e)
            {
                Debug.Print("Exception when calling GeminiApi.BatchEmbedContents: " + e.Message );
                Debug.Print("Status Code: "+ e.ErrorCode);
                Debug.Print(e.StackTrace);
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
    }
}

Advanced Features

This client includes several helpers to facilitate common tasks.

Retry Logic

The API client supports custom retry logic using the Polly library. You can define your own retry policies for handling transient network errors or other temporary issues.

For detailed instructions and examples, see the Retry Logic Documentation.

Logging

The client is instrumented with Serilog to provide detailed logging of API requests and responses. This is useful for debugging and monitoring. Logging is opt-in and can be configured by providing a logger instance.

For more details, see the Logging Documentation.

JSON Schema Generation

A utility is provided to generate JSON schemas from your C# model classes. This is especially useful for defining tools and functions for the Gemini API.

For more information, see the JSON Schema Generation Documentation.

File to Base64 Conversion

The client includes a helper to easily convert files and streams to base64-encoded strings, which is useful for embedding file data in API requests.

For usage examples, see the File to Base64 Conversion Documentation.

Documentation for API Endpoints

All URIs are relative to https://generativelanguage.googleapis.com

Class Method HTTP request Description
GeminiApi BatchEmbedContents POST /v1/models/{model}:batchEmbedContents Batch Embed Contents
GeminiApi CancelOperation DELETE /v1/operations/{name} Cancel Operation
GeminiApi CountTokens POST /v1/models/{model}:countTokens Count Tokens
GeminiApi CreateCachedContent POST /v1/cachedContents Create Cached Content
GeminiApi CreateChunk POST /v1/corpora/{corpus}/documents/{document}/chunks Create Chunk
GeminiApi CreateCorpus POST /v1/corpora Create Corpus
GeminiApi CreateDocument POST /v1/corpora/{corpus}/documents Create Document
GeminiApi CreateTunedModel POST /v1/tunedModels Create Tuned Model
GeminiApi DeleteCachedContent DELETE /v1/cachedContents/{name} Delete Cached Content
GeminiApi DeleteChunk DELETE /v1/corpora/{corpus}/documents/{document}/chunks/{chunk} Delete Chunk
GeminiApi DeleteCorpus DELETE /v1/corpora/{name} Delete Corpus
GeminiApi DeleteDocument DELETE /v1/corpora/{corpus}/documents/{document} Delete Document
GeminiApi DeleteFile DELETE /v1/files/{name} Delete File
GeminiApi DeleteTunedModel DELETE /v1/tunedModels/{name} Delete Tuned Model
GeminiApi EmbedContent POST /v1/models/{model}:embedContent Embed Content
GeminiApi GenerateContent POST /v1/models/{model}:generateContent Generate Content
GeminiApi GenerateImage POST /v1/models/{model}:generateImage Generate Image
GeminiApi GetCachedContent GET /v1/cachedContents/{name} Get Cached Content
GeminiApi GetChunk GET /v1/corpora/{corpus}/documents/{document}/chunks/{chunk} Get Chunk
GeminiApi GetCorpus GET /v1/corpora/{name} Get Corpus
GeminiApi GetDocument GET /v1/corpora/{corpus}/documents/{document} Get Document
GeminiApi GetFile GET /v1/files/{name} Get File
GeminiApi GetModel GET /v1/models/{model} Get Model
GeminiApi GetOperation GET /v1/operations/{name} Get Operation
GeminiApi GetTunedModel GET /v1/tunedModels/{name} Get Tuned Model
GeminiApi ListCachedContents GET /v1/cachedContents List Cached Contents
GeminiApi ListChunks GET /v1/corpora/{corpus}/documents/{document}/chunks List Chunks
GeminiApi ListCorpora GET /v1/corpora List Corpora
GeminiApi ListDocuments GET /v1/corpora/{corpus}/documents List Documents
GeminiApi ListFiles GET /v1/files List Files
GeminiApi ListModels GET /v1/models List Models
GeminiApi ListOperations GET /v1/operations List Operations
GeminiApi ListTunedModels GET /v1/tunedModels List Tuned Models
GeminiApi QueryCorpus POST /v1/corpora/{corpus}:query Query Corpus
GeminiApi StreamGenerateContent POST /v1/models/{model}:streamGenerateContent Stream Generate Content
GeminiApi UpdateCachedContent PATCH /v1/cachedContents/{name} Update Cached Content
GeminiApi UpdateChunk PATCH /v1/corpora/{corpus}/documents/{document}/chunks/{chunk} Update Chunk
GeminiApi UpdateCorpus PATCH /v1/corpora/{name} Update Corpus
GeminiApi UpdateDocument PATCH /v1/corpora/{corpus}/documents/{document} Update Document
GeminiApi UpdateTunedModel PATCH /v1/tunedModels/{name} Update Tuned Model
GeminiApi UploadFile POST /v1/files Upload File
GeminiApi UploadMedia POST /v1/media Upload Media

Documentation for Models

Documentation for Authorization

The API key can be provided in two ways: as a header or as a query parameter. You only need to use one of these methods.

1. As a Header (ApiKeyHeader)

  • Type: API key
  • Header Name: x-goog-api-key
  • Location: HTTP header

Example configuration:

var config = new Configuration();
config.ApiKey.Add("x-goog-api-key", "YOUR_API_KEY");

2. As a Query Parameter (ApiKeyQuery)

  • Type: API key
  • Parameter Name: key
  • Location: URL query string

Example configuration:

var config = new Configuration();
config.ApiKey.Add("key", "YOUR_API_KEY");

Contributing

We welcome contributions! To get started:

  1. Fork the repository.
  2. Create a new branch (feature-branch-name).
  3. Make your changes and commit them.
  4. Push your branch to your fork.
  5. Open a Pull Request (PR) with a clear description of your changes.

Visit the issues section to discuss ideas or report issues.

License

This project is licensed under the MIT License.

Author

Devi Prakash

Product Compatible and additional computed target framework versions.
.NET 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.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.0.1.8 184 8/26/2025
0.0.1.7 296 4/26/2025
0.0.1.4 210 2/16/2025