|
1 |
| -# © 2024 Phan Xuan Quang / Gemini.NET |
2 |
| -  |
| 1 | +# Gemini.NET - Lightweight .NET SDK for Gemini API |
3 | 2 |
|
4 |
| - |
| 3 | +[](https://www.nuget.org/packages/Gemini.NET) |
| 4 | +[](https://www.nuget.org/packages/Gemini.NET) |
5 | 5 |
|
6 |
| -Gemini.NET is a lightweight SDK that enables integration of Gemini for .NET 8 in a simple way. This SDK provides a set of tools and utilities to interact with the Gemini API, allowing developers to generate content, perform tasks, and manage API requests and responses efficiently. |
| 6 | + |
7 | 7 |
|
8 |
| -## Features |
| 8 | +**Gemini.NET** is a lightweight and user-friendly .NET SDK designed to simplify the integration of Google's Gemini API into your .NET applications. It provides a straightforward and efficient way to generate content, manage API requests, and leverage Gemini's powerful features. |
9 | 9 |
|
10 |
| -- Easy-to-use API request builder |
11 |
| -- Support for latest Gemini model versions |
12 |
| -- Grounding and safety settings configuration |
13 |
| -- JSON and plain text response handling |
14 |
| -- Validation methods for API keys and model versions |
15 |
| -- Enable inputing multiple media files |
16 |
| -- Enable customizing system instruction |
17 |
| -- Support function calling |
18 |
| -- Provide pre-optimized built-in utilities including image OCR, audio/video transcription, text sumarization, translation, dictionary, and JSON conversion. |
| 10 | +## **✨ Key Features** |
19 | 11 |
|
20 |
| -## Installation |
| 12 | +* **Simple API Request Builder:** Easily construct Gemini API requests with a fluent and intuitive interface. |
| 13 | +* **Latest Gemini Models:** Supports the most recent Gemini model versions, ensuring access to the latest advancements. |
| 14 | +* **Flexible Configuration:** Customize grounding and safety settings to tailor API behavior to your needs. |
| 15 | +* **Versatile Response Handling:** Handles both JSON and plain text responses seamlessly. |
| 16 | +* **API Key Validation:** Built-in methods to validate your API keys for secure and reliable usage. |
| 17 | +* **Multi-Image Input:** Enables inputting multiple images for richer content generation. |
| 18 | +* **Customizable System Instructions:** Fine-tune Gemini's behavior with custom system instructions. |
21 | 19 |
|
22 |
| -You can install the Gemini.NET package via **NuGet Package Manager** in Visual Studio: |
| 20 | +### TO DO: |
23 | 21 |
|
24 |
| - |
| 22 | +* **Pre-built Utilities:** Includes optimized utilities for common tasks like: → |
| 23 | + * **Image OCR:** Extract text from images. |
| 24 | + * **Audio/Video Transcription:** Convert audio and video to text. |
| 25 | + * **Text Summarization:** Condense lengthy text into concise summaries. |
| 26 | + * **Translation:** Translate text between languages. |
| 27 | + * **Dictionary:** Look up word definitions. |
| 28 | + * **JSON Conversion:** Work with JSON data effectively. |
25 | 29 |
|
26 |
| -Or using command prompts mentioned on the Gemini.NET's [NuGet Gallery site](https://www.nuget.org/packages/Gemini.NET): |
| 30 | +## **📦 Installation** |
27 | 31 |
|
28 |
| - |
| 32 | +Install Gemini.NET using the **NuGet Package Manager** in Visual Studio or the .NET CLI. |
| 33 | + |
| 34 | +**NuGet Package Manager:** |
| 35 | + |
| 36 | + |
| 37 | + |
| 38 | +1. Open your project in Visual Studio. |
| 39 | +2. Go to **Tools > NuGet Package Manager > Manage NuGet Packages for Solution...** |
| 40 | +3. Search for `Gemini.NET` and install the package. |
| 41 | + |
| 42 | +**.NET CLI:** |
| 43 | + |
| 44 | +```bash |
| 45 | +dotnet add package Gemini.NET |
| 46 | +``` |
| 47 | + |
| 48 | +For more detailed instructions, visit the Gemini.NET's [NuGet Gallery page](https://www.nuget.org/packages/Gemini.NET). |
29 | 49 |
|
30 | 50 | ---
|
31 | 51 |
|
32 |
| -## Usage |
33 |
| -- *Updating* |
| 52 | +## 🚀 Getting Started |
| 53 | + |
| 54 | +Here's a quick example to get you started with generating content using Gemini.NET: |
| 55 | + |
| 56 | +```csharp |
| 57 | +using Gemini.NET; |
| 58 | +using Models.Request; |
| 59 | +using Models.Enums; |
| 60 | + |
| 61 | +// Initialize the Generator with your API key |
| 62 | +var generator = new Generator("YOUR_API_KEY"); |
| 63 | + |
| 64 | +// Build an API request |
| 65 | +var apiRequest = new ApiRequestBuilder() |
| 66 | + .WithPrompt("Write a short poem about the stars.") |
| 67 | + .WithDefaultGenerationConfig(temperature: 0.7F, responseMimeType: ResponseMimeType.PlainText) |
| 68 | + .Build(); |
| 69 | + |
| 70 | +// Generate content using the latest stable model |
| 71 | +var modelVersion = Generator.GetLatestStableModelVersion(); |
| 72 | +var response = await generator.GenerateContentAsync(apiRequest, modelVersion); |
| 73 | + |
| 74 | +// Print the generated content |
| 75 | +Console.WriteLine("Generated Poem:\n" + response.Result); |
| 76 | +``` |
| 77 | + |
| 78 | +Replace `"YOUR_API_KEY"` with your actual Gemini API key and run this code in your .NET 8 project. |
| 79 | + |
| 80 | +--- |
| 81 | + |
| 82 | +## **🛠️ Usage Guidance** |
| 83 | + |
| 84 | +### ApiRequestBuilder Class |
| 85 | + |
| 86 | +The `ApiRequestBuilder` class provides a fluent API to create and configure `ApiRequest` objects. |
| 87 | + |
| 88 | +**Available Methods:** |
| 89 | + |
| 90 | +* **`WithSystemInstruction(string systemInstruction)`:** Sets instructions for Gemini's behavior. |
| 91 | +* **`WithGenerationConfig(GenerationConfig config)`:** Provides detailed generation settings (temperature, top_p, etc.). |
| 92 | +* **`EnableGrounding()`:** Enables grounding to get source attribution. |
| 93 | +* **`WithSafetySettings(IEnumerable<SafetySetting> safetySettings)`:** Configures content safety filters. |
| 94 | +* **`DisableAllSafetySettings()`:** Disables all safety filters (use with caution). |
| 95 | +* **`WithDefaultGenerationConfig(float temperature = 1.0F, ResponseMimeType responseMimeType = ResponseMimeType.PlainText)`:** Sets common generation parameters. |
| 96 | +* **`WithPrompt(string prompt)`:** Sets the primary text prompt for the API. |
| 97 | +* **`WithChatHistory(IEnumerable<ChatMessage> chatMessages)`:** Provides conversation history for chat-based models. |
| 98 | +* **`WithBase64Images(IEnumerable<string> images)`:** Includes Base64 encoded images as input. |
| 99 | +* **`Build()`:** Constructs the `ApiRequest` object. |
| 100 | + |
| 101 | +**Example Usage:** |
| 102 | + |
| 103 | +```csharp |
| 104 | +using Models.Request; |
| 105 | +using Models.Enums; |
| 106 | +using System.Collections.Generic; |
| 107 | + |
| 108 | +var apiRequestBuilder = new ApiRequestBuilder() |
| 109 | + .WithSystemInstruction("Act as a helpful assistant.") |
| 110 | + .WithPrompt("Translate 'Hello world' to Spanish.") |
| 111 | + .WithDefaultGenerationConfig(temperature: 0.6F, responseMimeType: ResponseMimeType.Json) |
| 112 | + .EnableGrounding() |
| 113 | + .WithSafetySettings(new List<SafetySetting> { new SafetySetting { Category = "Harassment", Threshold = "BLOCK_MEDIUM_AND_ABOVE" } }) |
| 114 | + .Build(); |
| 115 | + |
| 116 | +// apiRequestBuilder is now ready to be used with Generator.GenerateContentAsync() |
| 117 | +``` |
| 118 | + |
| 119 | +### Generator Class |
| 120 | + |
| 121 | +The `Generator` class is the primary entry point for interacting with the Gemini API. It handles API key management, request execution, and response processing. |
| 122 | + |
| 123 | +#### Initialization |
| 124 | + |
| 125 | +You can initialize the `Generator` using either an API key or Google Cloud project credentials. |
| 126 | + |
| 127 | +**Using API Key:** |
| 128 | + |
| 129 | +```csharp |
| 130 | +using Gemini.NET; |
| 131 | + |
| 132 | +var generator = new Generator("YOUR_API_KEY"); |
| 133 | +``` |
| 134 | + |
| 135 | +**Using Google Cloud Project Credentials:** |
| 136 | + |
| 137 | +```csharp |
| 138 | +using Gemini.NET; |
| 139 | + |
| 140 | +var generator = new Generator("YOUR_CLOUD_PROJECT_NAME", "YOUR_CLOUD_PROJECT_ID", "YOUR_BEARER_TOKEN"); |
| 141 | +``` |
| 142 | + |
| 143 | +#### API Key Validation |
| 144 | + |
| 145 | +Verify your API key's validity using `IsValidApiKeyAsync()`: |
| 146 | + |
| 147 | +```csharp |
| 148 | +bool isValid = await generator.IsValidApiKeyAsync(); |
| 149 | +if (isValid) |
| 150 | +{ |
| 151 | + Console.WriteLine("API key is valid."); |
| 152 | +} |
| 153 | +else |
| 154 | +{ |
| 155 | + Console.WriteLine("API key is invalid or expired."); |
| 156 | +} |
| 157 | +``` |
| 158 | + |
| 159 | +#### Configuring Response Details (Grounding & Search) |
| 160 | + |
| 161 | +Control the inclusion of grounding details and search entry points in the API response. |
| 162 | + |
| 163 | +```csharp |
| 164 | +// Include Grounding Detail in response |
| 165 | +generator.IncludesGroundingDetailInResponse(); |
| 166 | + |
| 167 | +// Exclude Grounding Detail from response (default) |
| 168 | +generator.ExcludesGroundingDetailFromResponse(); |
| 169 | + |
| 170 | +// Include Search Entry Point in response |
| 171 | +generator.IncludesSearchEntryPointInResponse(); |
| 172 | + |
| 173 | +// Exclude Search Entry Point from response (default) |
| 174 | +generator.ExcludesSearchEntryPointFromResponse(); |
| 175 | +``` |
| 176 | + |
| 177 | +#### Generating Content |
| 178 | + |
| 179 | +1. **Create an `ApiRequest`:** Use `ApiRequestBuilder` to construct your request. |
| 180 | +2. **Call `GenerateContentAsync()`:** Send the request to the Gemini API. |
| 181 | + |
| 182 | +**Example:** |
| 183 | + |
| 184 | +```csharp |
| 185 | +using Models.Request; |
| 186 | +using Models.Enums; |
| 187 | + |
| 188 | +// Build API Request |
| 189 | +var apiRequest = new ApiRequestBuilder() |
| 190 | + .WithPrompt("Explain quantum physics in simple terms.") |
| 191 | + .WithDefaultGenerationConfig(temperature: 0.5F, responseMimeType: ResponseMimeType.PlainText) |
| 192 | + .Build(); |
| 193 | + |
| 194 | +// Select Model Version |
| 195 | +var modelVersion = ModelVersion.Gemini_20_Flash; // Or use Generator.GetLatestStableModelVersion() |
| 196 | +
|
| 197 | +// Generate Content |
| 198 | +var response = await generator.GenerateContentAsync(apiRequest, modelVersion); |
| 199 | + |
| 200 | +Console.WriteLine("Generated Explanation:\n" + response.Result); |
| 201 | + |
| 202 | +if (response.GroundingDetail != null) // Check for grounding details |
| 203 | +{ |
| 204 | + Console.WriteLine("\nGrounding Detail (HTML):\n" + response.GroundingDetail.RenderedContentAsHtml); |
| 205 | +} |
| 206 | +``` |
| 207 | + |
| 208 | +#### Getting the Latest Stable Model Version |
| 209 | + |
| 210 | +Retrieve the latest recommended model version: |
| 211 | + |
| 212 | +```csharp |
| 213 | +var latestModelVersion = Generator.GetLatestStableModelVersion(); |
| 214 | +Console.WriteLine("Latest Stable Model Version: " + latestModelVersion); |
| 215 | +``` |
| 216 | + |
| 217 | +### Validator Class |
| 218 | + |
| 219 | +The `Validator` class offers utility methods for checking model capabilities and API key formats. |
| 220 | + |
| 221 | +**Methods:** |
| 222 | + |
| 223 | +* **`SupportsGrouding(ModelVersion modelVersion)`:** Checks if a model version supports grounding. |
| 224 | +* **`SupportsJsonOutput(ModelVersion modelVersion)`:** Checks if a model version supports JSON output. |
| 225 | +* **`CanBeValidApiKey(string apiKey)`:** Validates the format of a Gemini API key. |
| 226 | + |
| 227 | +**Example Usage:** |
| 228 | + |
| 229 | +```csharp |
| 230 | +using Models.Enums; |
| 231 | +using Gemini.NET; |
| 232 | + |
| 233 | +bool groundingSupported = Validator.SupportsGrouding(ModelVersion.Gemini_20_Flash); |
| 234 | +Console.WriteLine($"Gemini Flash supports grounding: {groundingSupported}"); |
| 235 | + |
| 236 | +bool jsonOutputSupported = Validator.SupportsJsonOutput(ModelVersion.Gemini_20_Flash); |
| 237 | +Console.WriteLine($"Gemini Flash supports JSON output: {jsonOutputSupported}"); |
| 238 | + |
| 239 | +bool apiKeyFormatValid = Validator.CanBeValidApiKey("YOUR_API_KEY"); |
| 240 | +Console.WriteLine($"API Key format is valid: {apiKeyFormatValid}"); |
| 241 | +``` |
| 242 | + |
| 243 | +## **🤝 Contributing** |
| 244 | + |
| 245 | +We welcome contributions to Gemini.NET! Whether you're fixing a bug, suggesting a new feature, improving documentation, or writing code, your help is appreciated. |
| 246 | + |
| 247 | +**How to Contribute:** |
| 248 | + |
| 249 | +1. **Fork the repository:** Start by forking the Gemini.NET repository to your own GitHub account. |
| 250 | +2. **Create a branch:** Create a new branch for your contribution (e.g., `feature/new-utility` or `fix/bug-ocr`). |
| 251 | +3. **Make your changes:** Implement your feature, bug fix, or documentation update. |
| 252 | +4. **Test your changes:** Ensure your changes are working correctly and don't introduce regressions. |
| 253 | +5. **Submit a pull request:** Once you're happy with your contribution, submit a pull request to the main repository, explaining your changes in detail. |
| 254 | + |
| 255 | +**Types of Contributions We Appreciate:** |
| 256 | + |
| 257 | +* **Bug Reports:** If you find a bug, please report it by creating an issue. Provide clear steps to reproduce the bug and any relevant details about your environment. |
| 258 | +* **Feature Requests:** Have a great idea for a new feature or utility? Open an issue to discuss it! |
| 259 | +* **Code Contributions:** We welcome code contributions that add new features, improve existing functionality, or fix bugs. |
| 260 | +* **Documentation Improvements:** Help us make the documentation clearer, more comprehensive, and easier to understand. |
| 261 | +* **Examples and Tutorials:** Creating examples and tutorials can help other developers get started with Gemini.NET more quickly. |
| 262 | + |
| 263 | +**Contribution Guidelines:** |
| 264 | + |
| 265 | +* Follow the existing code style and conventions. |
| 266 | +* Write clear and concise commit messages. |
| 267 | +* Ensure your code is well-tested. |
| 268 | +* Be respectful and considerate in your interactions with other contributors. |
| 269 | + |
| 270 | +Please note that by contributing to Gemini.NET, you agree to abide by the project's Code of Conduct (if applicable, otherwise standard open source community guidelines apply). |
| 271 | + |
| 272 | +We look forward to your contributions! |
0 commit comments