{"id":18113399,"url":"https://github.com/mscraftsman/generative-ai","last_synced_at":"2025-04-04T15:09:00.368Z","repository":{"id":224923882,"uuid":"764024461","full_name":"mscraftsman/generative-ai","owner":"mscraftsman","description":"Gemini AI SDK for .NET and ASP.NET Core enables developers to use Google's state-of-the-art generative AI models to build AI-powered features and applications.","archived":false,"fork":false,"pushed_at":"2024-10-29T20:41:07.000Z","size":81312,"stargazers_count":50,"open_issues_count":10,"forks_count":10,"subscribers_count":7,"default_branch":"main","last_synced_at":"2024-10-29T22:50:47.347Z","etag":null,"topics":["dotnet","dotnetcore","gemini","gemini-api","generative-ai","google-ai","google-api","hacktoberfest","imagen","sdk","vertex-ai"],"latest_commit_sha":null,"homepage":"https://mscraftsman.github.io/generative-ai/","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mscraftsman.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":["jochenkirstaetter","mscraftsman"]}},"created_at":"2024-02-27T10:48:16.000Z","updated_at":"2024-10-29T20:41:12.000Z","dependencies_parsed_at":"2024-11-13T12:34:15.307Z","dependency_job_id":null,"html_url":"https://github.com/mscraftsman/generative-ai","commit_stats":null,"previous_names":["mscraftsman/generative-ai"],"tags_count":89,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mscraftsman%2Fgenerative-ai","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mscraftsman%2Fgenerative-ai/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mscraftsman%2Fgenerative-ai/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mscraftsman%2Fgenerative-ai/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mscraftsman","download_url":"https://codeload.github.com/mscraftsman/generative-ai/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247198460,"owners_count":20900080,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dotnet","dotnetcore","gemini","gemini-api","generative-ai","google-ai","google-api","hacktoberfest","imagen","sdk","vertex-ai"],"created_at":"2024-11-01T02:08:12.329Z","updated_at":"2025-04-04T15:09:00.349Z","avatar_url":"https://github.com/mscraftsman.png","language":"C#","funding_links":["https://github.com/sponsors/jochenkirstaetter","https://github.com/sponsors/mscraftsman"],"categories":["Plugins"],"sub_categories":[],"readme":"# Gemini AI Client for .NET and ASP.NET Core\n[![GitHub](https://img.shields.io/github/license/mscraftsman/generative-ai)](https://github.com/mscraftsman/generative-ai/blob/main/LICENSE)\n![GitHub last commit](https://img.shields.io/github/last-commit/mscraftsman/generative-ai)\n[![MsccGenerativeAI](https://github.com/mscraftsman/generative-ai/actions/workflows/dotnetcore.yml/badge.svg?branch=main)](https://github.com/mscraftsman/generative-ai/actions/workflows/dotnetcore.yml)\n[![GitHub stars](https://img.shields.io/github/stars/mscraftsman/generative-ai)](https://github.com/mscraftsman/generative-ai/stargazers)\n\nAccess and integrate the Gemini API into your .NET applications. This SDK allows you to connect to the Gemini API through either [Google AI Studio](https://aistudio.google.com/prompts/new_chat?model=gemini-2.0-flash-exp) or [Vertex AI](https://cloud.google.com/vertex-ai/generative-ai/docs/gemini-v2).\nThe SDK is fully compatible with all Gemini API models and features, including recent additions like improved tool usage (code execution, function calling and integrated Google search grounding), and media generation (Imagen).\n\n| Name                                                   | Package                                                                                 | Status                                                                                                                                                                                                                                                                        |\n|--------------------------------------------------------|-----------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| Client for .NET                                        | [Mscc.GenerativeAI](https://www.nuget.org/packages/Mscc.GenerativeAI/)                  | [![NuGet Version](https://img.shields.io/nuget/v/Mscc.GenerativeAI)](https://www.nuget.org/packages/Mscc.GenerativeAI/)[![NuGet Downloads](https://img.shields.io/nuget/dt/Mscc.GenerativeAI)](https://www.nuget.org/packages/Mscc.GenerativeAI/)                             |\n| Client for ASP.NET (Core)                              | [Mscc.GenerativeAI.Web](https://www.nuget.org/packages/Mscc.GenerativeAI.Web/)          | [![NuGet Version](https://img.shields.io/nuget/v/Mscc.GenerativeAI.Web)](https://www.nuget.org/packages/Mscc.GenerativeAI.Web/)[![NuGet Downloads](https://img.shields.io/nuget/dt/Mscc.GenerativeAI.Web)](https://www.nuget.org/packages/Mscc.GenerativeAI.Web/)             |\n| Client for .NET using Google API Client Library        | [Mscc.GenerativeAI.Google](https://www.nuget.org/packages/Mscc.GenerativeAI.Google/)    | [![NuGet Version](https://img.shields.io/nuget/v/Mscc.GenerativeAI.Google)](https://www.nuget.org/packages/Mscc.GenerativeAI.Google/)[![NuGet Downloads](https://img.shields.io/nuget/dt/Mscc.GenerativeAI.Google)](https://www.nuget.org/packages/Mscc.GenerativeAI.Google/) |\n| Client for Microsoft.Extensions.AI and Semantic Kernel | [Mscc.GenerativeAI.Microsoft](https://www.nuget.org/packages/Mscc.GenerativeAI.Microsoft/) | [![NuGet Version](https://img.shields.io/nuget/v/Mscc.GenerativeAI.Microsoft)](https://www.nuget.org/packages/Mscc.GenerativeAI.Microsoft/)[![NuGet Downloads](https://img.shields.io/nuget/dt/Mscc.GenerativeAI.Microsoft)](https://www.nuget.org/packages/Mscc.GenerativeAI.Microsoft/) |\n\nRead more about [Mscc.GenerativeAI.Web](./src/Mscc.GenerativeAI.Web) and how to add it to your ASP.NET (Core) web applications.\nRead more about [Mscc.GenerativeAI.Google](./src/Mscc.GenerativeAI.Google).\nRead more about [Mscc.GenerativeAI.Microsoft](./src/Mscc.GenerativeAI.Microsoft) and how to use it with Semantic Kernel.\n\n## Install the package 🖥️\n\nInstall the package [Mscc.GenerativeAI](https://www.nuget.org/packages/Mscc.GenerativeAI/) from NuGet. You can install the package from the command line using either the command line or the NuGet Package Manager Console. Or you add it directly to your .NET project.\n\nAdd the package using the `dotnet` command line tool in your .NET project folder.\n\n```text\n\u003e dotnet add package Mscc.GenerativeAI\n```\n\nWorking with Visual Studio use the NuGet Package Manager to install the package Mscc.GenerativeAI.\n\n```text\nPM\u003e Install-Package Mscc.GenerativeAI\n```\n\nAlternatively, add the following line to your `.csproj` file.\n\n```text\n  \u003cItemGroup\u003e\n    \u003cPackageReference Include=\"Mscc.GenerativeAI\" Version=\"2.4.1\" /\u003e\n  \u003c/ItemGroup\u003e\n```\n\nYou can then add this code to your sources whenever you need to access any Gemini API provided by Google. This package works for Google AI (Google AI Studio) and Google Cloud Vertex AI.\n\n## Features (as per Gemini analysis) ✦\n\nThe provided code defines a C# library for interacting with Google's Generative AI models, specifically the Gemini models. It provides functionalities to:\n\n- **List available models**: This allows users to see which models are available for use.\n- **Get information about a specific model**: This provides details about a specific model, such as its capabilities and limitations.\n- **Generate content**: This allows users to send prompts to a model and receive generated text in response. \n- **Generate content stream**: This allows users to receive a stream of generated text from a model, which can be useful for real-time applications. \n- **Generate a grounded answer**: This allows users to ask questions and receive answers that are grounded in provided context. \n- **Generate embeddings**: This allows users to convert text into numerical representations that can be used for tasks like similarity search. \n- **Count tokens**: This allows users to estimate the cost of using a model by counting the number of tokens in a prompt or response. \n- **Start a chat session**: This allows users to have a back-and-forth conversation with a model.\n- **Create tuned models**: This allows users to provide samples for tuning an existing model. Currently, only the `text-bison-001` and `gemini-1.0-pro-001` models are supported for tuning\n- **File API**: This allows users to upload large files and use them with Gemini 1.5.\n\nThe package also defines various helper classes and enums to represent different aspects of the Gemini API, such as model names, request parameters, and response data.\n\n## Authentication use cases 👥\n\nThe package supports the following use cases to authenticate.\n\n| API       | Authentication                                                                                                                              | Remarks                                                          |\n|-----------|---------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------|\n| Google AI | [Authentication with an API key](https://ai.google.dev/tutorials/setup)                                                                     |                                                                  |\n| Google AI | [Authentication with OAuth](https://ai.google.dev/docs/oauth_quickstart)                                                                    | required for tuned models                                        |\n| Vertex AI | [Authentication with Application Default Credentials (ADC)](https://cloud.google.com/docs/authentication/provide-credentials-adc#local-dev) |                                                                  |\n| Vertex AI | [Authentication with Credentials by Metadata Server](https://cloud.google.com/docs/authentication/rest#metadata-server)                     | requires access to a metadata server                             |\n| Vertex AI | [Authentication with OAuth]()                                                                                                               | using [Mscc.GenerativeAI.Google](./src/Mscc.GenerativeAI.Google) |\n| Vertex AI | [Authentication with Service Account](https://cloud.google.com/docs/authentication/provide-credentials-adc#service-account)                 | using [Mscc.GenerativeAI.Google](./src/Mscc.GenerativeAI.Google) |\n| Vertex AI | [Express Mode with an API key](https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview)                                                                                                            |                                                                  |\n\nThis applies mainly to the instantiation procedure.\n\n## Getting Started 🚀\n\nUse of Gemini API in either Google AI or Vertex AI is almost identical. The major difference is the way to instantiate the model handling your prompt.\n\n### Using Environment variables\n\nIn the cloud most settings are configured via environment variables (EnvVars). The ease of configuration, their widespread support and the simplicity of environment variables makes them a very interesting option.\n\n| Variable Name                  | Description                                                   |\n|--------------------------------|---------------------------------------------------------------|\n| GOOGLE_AI_MODEL                | The name of the model to use (default is *Model.Gemini15Pro*) |\n| GOOGLE_API_KEY                 | The API key generated in Google AI Studio                     |\n| GOOGLE_PROJECT_ID              | Project ID in Google Cloud to access the APIs                 |\n| GOOGLE_REGION                  | Region in Google Cloud (default is *us-central1*)             |\n| GOOGLE_ACCESS_TOKEN            | The access token required to use models running in Vertex AI  |\n| GOOGLE_APPLICATION_CREDENTIALS | Path to the application credentials file.                     |\n| GOOGLE_WEB_CREDENTIALS         | Path to a Web credentials file.                               |\n\nUsing any environment variable provides simplified access to a model.\n\n```csharp\nusing Mscc.GenerativeAI;\nvar model = new GenerativeModel();\n```\n\n### Choose an API and authentication mode\n\nGoogle AI with an API key\n\n```csharp\nusing Mscc.GenerativeAI;\n// Google AI with an API key\nvar googleAI = new GoogleAI(apiKey: \"your API key\");\nvar model = googleAI.GenerativeModel(model: Model.Gemini15Pro);\n```\n\nGoogle AI with OAuth. Use `gcloud auth application-default print-access-token` to get the access token.\n\n```csharp\nusing Mscc.GenerativeAI;\n// Google AI with OAuth. Use `gcloud auth application-default print-access-token` to get the access token.\nvar accessToken = \"your access token\";\nvar googleAI = new GoogleAI(accessToken: accessToken);\nvar model = googleAI.GenerativeModel(model: Model.Gemini15Pro);\n```\n\nVertex AI with OAuth. Use `gcloud auth application-default print-access-token` to get the access token.\n\n```csharp\nusing Mscc.GenerativeAI;\n// Vertex AI with OAuth. Use `gcloud auth application-default print-access-token` to get the access token.\nvar vertex = new VertexAI(projectId: projectId, region: region);\nvar model = vertex.GenerativeModel(model: Model.Gemini15Pro);\nmodel.AccessToken = accessToken;\n```\n\nVertex AI in express mode using an API key.\n\n```csharp\nusing Mscc.GenerativeAI;\n// Vertex AI in express mode with an API key.\nvar vertex = new VertexAI(apiKey: \"your API key\");\nvar model = vertex.GenerativeModel(model: Model.Gemini20FlashExperimental);\n```\n\nThe `ConfigurationFixture` type in the test project implements multiple options to retrieve sensitive information, i.e. API key or access token.\n\n### Using Google AI Gemini API\n\nWorking with Google AI in your application requires an API key. Get an API key from [Google AI Studio](https://aistudio.google.com/app/apikey).\n\n```csharp\nusing Mscc.GenerativeAI;\n\nvar apiKey = \"your_api_key\";\nvar prompt = \"Write a story about a magic backpack.\";\n\nvar googleAI = new GoogleAI(apiKey: apiKey);\nvar model = googleAI.GenerativeModel(model: Model.Gemini15Pro);\n\nvar response = await model.GenerateContent(prompt);\nConsole.WriteLine(response.Text);\n```\n\n### Using Vertex AI Gemini API\n\nUse of [Vertex AI](https://console.cloud.google.com/vertex-ai) requires an account on [Google Cloud](https://console.cloud.google.com/), a project with billing and Vertex AI API enabled.\n\n```csharp\nusing Mscc.GenerativeAI;\n\nvar projectId = \"your_google_project_id\"; // the ID of a project, not its name.\nvar region = \"us-central1\";     // see documentation for available regions.\nvar accessToken = \"your_access_token\";      // use `gcloud auth application-default print-access-token` to get it.\nvar prompt = \"Write a story about a magic backpack.\";\n\nvar vertex = new VertexAI(projectId: projectId, region: region);\nvar model = vertex.GenerativeModel(model: Model.Gemini15Pro);\nmodel.AccessToken = accessToken;\n\nvar response = await model.GenerateContent(prompt);\nConsole.WriteLine(response.Text);\n```\n\n### Using Vertex AI in express mode\n\n[Vertex AI in express mode](https://cloud.google.com/vertex-ai/generative-ai/docs/start/express-mode/overview) is the fastest way to start building generative AI applications on Google Cloud. Signing up in express mode is quick and easy, and it doesn't require entering any billing information. After you sign up, you can access and use Google Cloud APIs in just a few steps.\n\n```csharp\nusing Mscc.GenerativeAI;\n\nvar prompt = \"Explain bubble sort to me.\";\nvar vertex = new VertexAI(apiKey: \"your API key\");\nvar model = vertex.GenerativeModel(model: Model.Gemini20FlashExperimental);\n\nvar response = await model.GenerateContent(prompt);\nConsole.WriteLine(response.Text);\n```\n\n## More examples 🪄\n\nSupported models are accessible via the `Model` class. Since release 0.9.0 there is support for the previous PaLM 2 models and their functionalities.\n\n### Use system instruction\n\nThe model can be injected with a system instruction that applies to all further requests. \nFollowing is an example how to instruct the model to respond like a pirate.\n\n```csharp\nvar apiKey = \"your_api_key\";\nvar systemInstruction = new Content(\"You are a friendly pirate. Speak like one.\");\nvar prompt = \"Good morning! How are you?\";\nIGenerativeAI genAi = new GoogleAI(apiKey);\nvar model = genAi.GenerativeModel(Model.Gemini15ProLatest, systemInstruction: systemInstruction);\nvar request = new GenerateContentRequest(prompt);\n\nvar response = await model.GenerateContent(request);\nConsole.WriteLine(response.Text);\n```\n\nThe response might look similar to this:\n```text\nAhoy there, matey! I be doin' finer than a freshly swabbed poop deck on this fine mornin', how about yerself?  \nShimmer me timbers, it's good to see a friendly face!  \nWhat brings ye to these here waters?\n```\n\n### Generate structured output\n\nGemini generates unstructured text by default, but some applications require structured text. For these use cases, you can constrain Gemini to respond with JSON, a structured data format suitable for automated processing.\n\nYou can control the structure of the JSON response by suppling a schema. There are two ways to supply a schema to the model:\n\n- As text in the prompt\n- As a structured schema supplied through model configuration\n\n```csharp\nclass Recipe {\n    public string RecipeName { get; set; }\n}\n\n// generate structure JSON output\nvar apiKey = \"your_api_key\";\nvar prompt = \"List a few popular cookie recipes.\";\nvar googleAi = new GoogleAI(apiKey);\nvar model = googleAi.GenerativeModel(model: Model.Gemini15ProLatest);\nvar generationConfig = new GenerationConfig()\n{\n    ResponseMimeType = \"application/json\",\n    ResponseSchema = new List\u003cRecipe\u003e()\n};\n\nvar response = await model.GenerateContent(prompt, \n    generationConfig: generationConfig);\nConsole.WriteLine(response?.Text);\n}\n```\nThe output might look like this:\n```json\n[{\"recipeName\": \"Chocolate Chip Cookies\"}, {\"recipeName\": \"Peanut Butter Cookies\"}, {\"recipeName\": \"Snickerdoodles\"}, {\"recipeName\": \"Oatmeal Raisin Cookies\"}, {\"recipeName\": \"Sugar Cookies\"}]\n```\n### Use Google Search\n\nTo activate Google Search as a tool, set the boolean property `UseGoogleSearch` to true, like the following example.\n\n```csharp\nvar apiKey = \"your_api_key\";\nvar prompt = \"When is the next total solar eclipse in Mauritius?\";\nvar genAi = new GoogleAI(apiKey);\nvar model = genAi.GenerativeModel(Model.Gemini20FlashExperimental);\nmodel.UseGoogleSearch = true;\n\nvar response = await model.GenerateContent(prompt);\nConsole.WriteLine(string.Join(Environment.NewLine,\n    response.Candidates![0].Content!.Parts\n        .Select(x =\u003e x.Text)\n        .ToArray()));\n```\n\nMore details are described in the API documentation on [Search as a tool](https://ai.google.dev/gemini-api/docs/models/gemini-v2#search-tool).\n\n### Grounding with Google Search\n\nThe simplest version is to toggle the boolean property `UseGrounding`, like so.\n\n```csharp\nvar apiKey = \"your_api_key\";\nvar prompt = \"What is the current Google stock price?\";\nvar genAi = new GoogleAI(apiKey);\nvar model = genAi.GenerativeModel(Model.Gemini15Pro002);\nmodel.UseGrounding = true;\n\nvar response = await model.GenerateContent(prompt);\nConsole.WriteLine(response.Text);\n```\n\nIn case that you would like to have more control over the Google Search retrieval parameters, use the following approach.\n\n```csharp\nvar apiKey = \"your_api_key\";\nvar prompt = \"Who won Wimbledon this year?\";\nIGenerativeAI genAi = new GoogleAI(apiKey);\nvar model = genAi.GenerativeModel(Model.Gemini15Pro002,\n    tools: [new Tool { GoogleSearchRetrieval = \n        new(DynamicRetrievalConfigMode.ModeUnspecified, 0.06f) }]);\n\nvar response = await model.GenerateContent(prompt);\nConsole.WriteLine(response.Text);\n```\n\nIn either case, the returned `Candidates` item type has an additional property `GroundingMetadata` which provides the details of the Google Search based grounding\n\n### Text-and-image input\n\n```csharp\nusing Mscc.GenerativeAI;\n\nvar apiKey = \"your_api_key\";\nvar prompt = \"Parse the time and city from the airport board shown in this image into a list, in Markdown\";\nvar googleAI = new GoogleAI(apiKey: \"your API key\");\nvar model = googleAI.GenerativeModel(model: Model.GeminiVisionPro);\nvar request = new GenerateContentRequest(prompt);\nawait request.AddMedia(\"https://raw.githubusercontent.com/mscraftsman/generative-ai/refs/heads/main/tests/Mscc.GenerativeAI/payload/timetable.png\");\n\nvar response = await model.GenerateContent(request);\nConsole.WriteLine(response.Text);\n```\n\nThe part of `InlineData` is supported by both Google AI and Vertex AI. Whereas the part `FileData` is restricted to Vertex AI only.\n\n### Chat conversations\n\nGemini enables you to have freeform conversations across multiple turns. You can interact with Gemini Pro using a single-turn prompt and response or chat with it in a multi-turn, continuous conversation, even for code understanding and generation.\n\n```csharp\nusing Mscc.GenerativeAI;\n\nvar apiKey = \"your_api_key\";\nvar googleAI = new GoogleAI(apiKey);\nvar model = googleAI.GenerativeModel();    // using default model: gemini-1.5-pro\nvar chat = model.StartChat();   // optionally pass a previous history in the constructor.\n\n// Instead of discarding you could also use the response and access `response.Text`.\n_ = await chat.SendMessage(\"Hello, fancy brainstorming about IT?\");\n_ = await chat.SendMessage(\"In one sentence, explain how a computer works to a young child.\");\n_ = await chat.SendMessage(\"Okay, how about a more detailed explanation to a high schooler?\");\n_ = await chat.SendMessage(\"Lastly, give a thorough definition for a CS graduate.\");\n\n// A chat session keeps every response in its history.\nchat.History.ForEach(c =\u003e Console.WriteLine($\"{c.Role}: {c.Text}\"));\n\n// Last request/response pair can be removed from the history.\nvar latest = chat.Rewind();\nConsole.WriteLine($\"{latest.Sent} - {latest.Received}\");\n```\n\n### Use Gemini 1.5 with large files\n\nWith Gemini 1.5 you can create multimodal prompts supporting large files.\n\nThe following example uploads one or more files via File API and the created File URIs are used in the `GenerateContent` call to generate text.\n\n```csharp\nusing Mscc.GenerativeAI;\n\nvar apiKey = \"your_api_key\";\nvar prompt = \"Make a short story from the media resources. The media resources are:\";\nIGenerativeAI genAi = new GoogleAI(apiKey);\nvar model = genAi.GenerativeModel(Model.Gemini15Pro);\n\n// Upload your large image(s).\n// Instead of discarding you could also use the response and access `response.Text`.\nvar filePath = Path.Combine(Environment.CurrentDirectory, \"verylarge.png\");\nvar displayName = \"My very large image\";\n_ = await model.UploadMedia(filePath, displayName);\n\n// Create the prompt with references to File API resources.\nvar request = new GenerateContentRequest(prompt);\nvar files = await model.ListFiles();\nforeach (var file in files.Where(x =\u003e x.MimeType.StartsWith(\"image/\")))\n{\n    Console.WriteLine($\"File: {file.Name}\");\n    request.AddMedia(file);\n}\nvar response = await model.GenerateContent(request);\nConsole.WriteLine(response.Text);\n```\n\nRead more about [Gemini 1.5: Our next-generation model, now available for Private Preview in Google AI Studio](https://developers.googleblog.com/2024/02/gemini-15-available-for-private-preview-in-google-ai-studio.html).\n\n### Create a tuned model\n\nThe Gemini API lets you tune models on your own data. Since it's your data and your tuned models this needs stricter access controls than API-Keys can provide.\n\nBefore you can create a tuned model, you'll need to [set up OAuth for your project](https://ai.google.dev/palm_docs/oauth_quickstart).\n\n```csharp\nusing Mscc.GenerativeAI;\n\nvar projectId = \"your_google_project_id\"; // the ID of a project, not its name.\nvar accessToken = \"your_access_token\";      // use `gcloud auth application-default print-access-token` to get it.\nvar googleAI = new GoogleAI(accessToken: accessToken);\nvar model = googleAI.GenerativeModel(model: Model.Gemini10Pro001);\nmodel.ProjectId = projectId;\n\nvar parameters = new HyperParameters() { BatchSize = 2, LearningRate = 0.001f, EpochCount = 3 };\nvar dataset = new List\u003cTuningExample\u003e\n{    \n    new() { TextInput = \"1\", Output = \"2\" },\n    new() { TextInput = \"3\", Output = \"4\" },\n    new() { TextInput = \"-3\", Output = \"-2\" },\n    new() { TextInput = \"twenty two\", Output = \"twenty three\" },\n    new() { TextInput = \"two hundred\", Output = \"two hundred one\" },\n    new() { TextInput = \"ninety nine\", Output = \"one hundred\" },\n    new() { TextInput = \"8\", Output = \"9\" },\n    new() { TextInput = \"-98\", Output = \"-97\" },\n    new() { TextInput = \"1,000\", Output = \"1,001\" },\n    new() { TextInput = \"thirteen\", Output = \"fourteen\" },\n    new() { TextInput = \"seven\", Output = \"eight\" },\n};\nvar request = new CreateTunedModelRequest(Model.Gemini10Pro001, \n    \"Simply autogenerated Test model\",\n    dataset,\n    parameters);\n\nvar response = await model.CreateTunedModel(request);\nConsole.WriteLine($\"Name: {response.Name}\");\nConsole.WriteLine($\"Model: {response.Metadata.TunedModel} (Steps: {response.Metadata.TotalSteps})\");\n```\n(This is still work in progress but operational. Future release will provide types to simplify the create request.)\n\nTuned models appear in your Google AI Studio library.\n\n[![Tuned models are listed below My Library in Google AI Studio](./docs/GeminiTunedModels.png)](https://aistudio.google.com/app/library)\n\nRead more about [Tune Gemini Pro in Google AI Studio or with the Gemini API](https://developers.googleblog.com/2024/03/tune-gemini-pro-in-google-ai-studio-or-gemini-api.html).\n\n### More samples\n\nThe folders [samples](./samples) and [tests](./tests) contain more examples.\n\n- [Sample console application](./samples/Console.Minimal.Prompt)\n- [ASP.NET Core Minimal web application](./samples/Web.Minimal.Api)\n- [ASP.NET Core MVP web application](./samples/Web.Mvc) (work in progress!)\n\n## Troubleshooting ⚡\n\nSometimes you might have authentication warnings **HTTP 403** (Forbidden). Especially while working with OAuth-based authentication. You can fix it by re-authenticating through ADC.\n\n```bash\ngcloud config set project \"$PROJECT_ID\"\n\ngcloud auth application-default login\ngcloud auth application-default set-quota-project \"$PROJECT_ID\"\n```\n\nMake sure that the required API have been enabled.\n\n```bash\n# ENABLE APIs\ngcloud services enable aiplatform.googleapis.com\n```\n\nIn case of long-running streaming requests it can happen that you get a `HttpIOException`: The response ended prematurely while waiting for the next frame from the server. (ResponseEnded). \nThe root cause is the .NET runtime and the solution is to **upgrade to the latest version of the .NET runtime**. \nIn case that you cannot upgrade you might disable dynamic window sizing as a workaround:\nEither using the environment variable [`DOTNET_SYSTEM_NET_HTTP_SOCKETSHTTPHANDLER_HTTP2FLOWCONTROL_DISABLEDYNAMICWINDOWSIZING`](https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-environment-variables)\n```bash\nDOTNET_SYSTEM_NET_HTTP_SOCKETSHTTPHANDLER_HTTP2FLOWCONTROL_DISABLEDYNAMICWINDOWSIZING=true\n```\nor setting an `AppContext` switch:\n```csharp\nAppContext.SetSwitch(\"System.Net.SocketsHttpHandler.Http2FlowControl.DisableDynamicWindowSizing\", true);\n```\n\nSeveral issues regarding this problem have been reported on GitHub:\n- https://github.com/dotnet/runtime/pull/97881\n- https://github.com/grpc/grpc-dotnet/issues/2361\n- https://github.com/grpc/grpc-dotnet/issues/2358\n\n## Using the tests 🧩\n\nThe repository contains a number of test cases for Google AI and Vertex AI. You will find them in the [tests](./tests) folder. They are part of the [GenerativeAI solution].\nTo run the tests, either enter the relevant information into the [appsettings.json](./tests/Mscc.GenerativeAI/appsettings.json), create a new `appsettings.user.json` file with the same JSON structure in the `tests` folder, or define the following environment variables\n\n- GOOGLE_API_KEY\n- GOOGLE_PROJECT_ID\n- GOOGLE_REGION\n- GOOGLE_ACCESS_TOKEN (optional: if absent, `gcloud auth application-default print-access-token` is executed)\n\nThe test cases should provide more insights and use cases on how to use the [Mscc.GenerativeAI](https://github.com/mscraftsman/generative-ai) package in your .NET projects.\n\n## Try it out 🤩\n\nThe following link opens an instance of the code repository in Google Project IDX.\n\n\u003ca href=\"https://idx.google.com/import?url=https%3A%2F%2Fgithub.com%2Fmscraftsman%2Fgenerative-ai\"\u003e\n  \u003cpicture\u003e\n    \u003csource\n      media=\"(prefers-color-scheme: dark)\"\n      srcset=\"https://cdn.idx.dev/btn/try_dark_32.svg\"\u003e\n    \u003csource\n      media=\"(prefers-color-scheme: light)\"\n      srcset=\"https://cdn.idx.dev/btn/try_light_32.svg\"\u003e\n    \u003cimg\n      height=\"32\"\n      alt=\"Try in IDX\"\n      src=\"https://cdn.idx.dev/btn/try_purple_32.svg\"\u003e\n  \u003c/picture\u003e\n\u003c/a\u003e\n\nThis lets you work instantly with the code base without having to install anything.\n\n## Feedback ✨\n\nFor support and feedback kindly create issues at the \u003chttps://github.com/mscraftsman/generative-ai\u003e repository.\n\n## License 📜\n\nThis project is licensed under the [Apache-2.0 License](LICENSE) - see the [LICENSE](LICENSE) file for details.\n\n## Citation 📚\n\nIf you use [Mscc.GenerativeAI](https://github.com/mscraftsman/generative-ai) in your research project, kindly cite as follows\n\n```text\n@misc{Mscc.GenerativeAI,\n  author = {Kirstätter, J and MSCraftsman},\n  title = {Mscc.GenerativeAI - Gemini AI Client for .NET and ASP.NET Core},\n  year = {2024},\n  publisher = {GitHub},\n  journal = {GitHub repository},\n  note = {https://github.com/mscraftsman/generative-ai}\n}\n```\n\n--- \n\nCreated by [Jochen Kirstätter](https://jochen.kirstaetter.name/).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmscraftsman%2Fgenerative-ai","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmscraftsman%2Fgenerative-ai","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmscraftsman%2Fgenerative-ai/lists"}