GeminiSharp 0.0.1.8
dotnet add package GeminiSharp --version 0.0.1.8
NuGet\Install-Package GeminiSharp -Version 0.0.1.8
<PackageReference Include="GeminiSharp" Version="0.0.1.8" />
<PackageVersion Include="GeminiSharp" Version="0.0.1.8" />
<PackageReference Include="GeminiSharp" />
paket add GeminiSharp --version 0.0.1.8
#r "nuget: GeminiSharp, 0.0.1.8"
#:package GeminiSharp@0.0.1.8
#addin nuget:?package=GeminiSharp&version=0.0.1.8
#tool nuget:?package=GeminiSharp&version=0.0.1.8
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
- Json.NET - 13.0.2 or later
- JsonSubTypes - 1.8.0 or later
- System.ComponentModel.Annotations - 5.0.0 or later
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
- Model.ApiErrorResponse
- Model.ApiErrorResponseError
- Model.AttributionSourceId
- Model.BatchEmbedContents200Response
- Model.BatchEmbedContentsRequest
- Model.BatchEmbedContentsRequestRequestsInner
- Model.CachedContent
- Model.CachedContentUsageMetadata
- Model.Candidate
- Model.CandidateLogprobs
- Model.Chunk
- Model.ChunkData
- Model.CitationMetadata
- Model.CitationSource
- Model.CodeExecutionResult
- Model.Condition
- Model.ContentEmbedding
- Model.Corpus
- Model.CountTokens200Response
- Model.CreateTunedModelRequest
- Model.CustomMetadata
- Model.Dataset
- Model.Document
- Model.DynamicRetrievalConfig
- Model.EmbedContentRequest
- Model.ExecutableCode
- Model.File
- Model.FileData
- Model.FunctionCall
- Model.FunctionCallingConfig
- Model.FunctionDeclaration
- Model.FunctionResponse
- Model.GeminiModel
- Model.GenerateContentRequest
- Model.GenerateContentResponse
- Model.GenerateImageRequest
- Model.GenerateImageResponse
- Model.GeneratedImage
- Model.GenerationConfig
- Model.GoogleSearchRetrieval
- Model.GroundingAttribution
- Model.GroundingChunk
- Model.GroundingChunkWeb
- Model.GroundingMetadata
- Model.GroundingPassageId
- Model.GroundingSupport
- Model.Hyperparameters
- Model.InlineData
- Model.ListCachedContents200Response
- Model.ListChunks200Response
- Model.ListCorpora200Response
- Model.ListDocuments200Response
- Model.ListFiles200Response
- Model.ListModels200Response
- Model.ListOperations200Response
- Model.ListTunedModels200Response
- Model.LogprobsResult
- Model.MetadataFilter
- Model.Operation
- Model.PromptFeedback
- Model.QueryCorpusRequest
- Model.QueryCorpusResponse
- Model.RelevantChunk
- Model.RequestContent
- Model.RequestContentPart
- Model.ResponseContent
- Model.ResponseContentPart
- Model.RetrievalMetadata
- Model.SafetyRating
- Model.SafetySetting
- Model.SearchEntryPoint
- Model.Segment
- Model.SemanticRetrieverChunk
- Model.Status
- Model.StringList
- Model.Tool
- Model.ToolConfig
- Model.TopCandidates
- Model.TunedModel
- Model.TunedModelSource
- Model.TuningExample
- Model.TuningExamples
- Model.TuningSnapshot
- Model.TuningTask
- Model.UploadFileRequestMetadata
- Model.UsageMetadata
- Model.VideoMetadata
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:
- Fork the repository.
- Create a new branch (
feature-branch-name
). - Make your changes and commit them.
- Push your branch to your fork.
- 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
Product | Versions 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. |
-
net7.0
- JsonSubTypes (>= 2.0.1)
- Newtonsoft.Json (>= 13.0.3)
- Newtonsoft.Json.Schema (>= 4.0.1)
- Polly (>= 8.1.0)
- Serilog (>= 3.1.1)
- Serilog.Sinks.Console (>= 5.0.1)
-
net8.0
- JsonSubTypes (>= 2.0.1)
- Newtonsoft.Json (>= 13.0.3)
- Newtonsoft.Json.Schema (>= 4.0.1)
- Polly (>= 8.1.0)
- Serilog (>= 3.1.1)
- Serilog.Sinks.Console (>= 5.0.1)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.