The unofficial, full-featured .NET SDK for Google Gemini and Vertex AI.
Documentation · What's new in v4 · Migration guide · API reference · Samples
Google_GenerativeAI is a REST-based SDK that gives .NET developers idiomatic, strongly typed access to the
Gemini API (Google AI Studio) and Vertex AI, using one API surface for both platforms.
- Generation: text, chat and streaming, multimodal input (images, audio, video, PDF), JSON mode and thinking.
- Tools: function calling with source-generated tools, built-in tools (Google Search, code execution, URL context, File Search) and Model Context Protocol (MCP) servers.
- Newer Gemini APIs: the Interactions API, the Multimodal Live API with ephemeral tokens, Live Music, File Search, Batch, webhooks, model tuning and agent APIs.
- Media: native image generation, video generation (Veo on Vertex AI), speech generation, embeddings and context caching.
- Grounding: Vertex AI RAG Engine and Google Search grounding.
- Ecosystem:
Microsoft.Extensions.AI(IChatClient, embeddings, images), ASP.NET Core dependency injection, and NativeAOT and trimming support.
Supported frameworks: .NET 6, 7, 8, 9, 10 and 11, .NET Standard 2.0, and .NET Framework 4.6.2.
dotnet add package Google_GenerativeAIAdd the other packages as you need them, for example dotnet add package Google_GenerativeAI.Microsoft.
Get an API key from Google AI Studio.
using GenerativeAI;
var googleAi = new GoogleAi("YOUR_API_KEY"); // or set GOOGLE_API_KEY and use new GoogleAi()
var model = googleAi.CreateGenerativeModel(GoogleAIModels.Gemini38Flash);
var response = await model.GenerateContentAsync("Explain quantum computing in one paragraph.");
Console.WriteLine(response.Text());Vertex AI uses Application Default Credentials (gcloud auth application-default login) by default.
using GenerativeAI;
var vertexAi = new VertexAI(projectId: "your-project", region: "global");
var model = vertexAi.CreateGenerativeModel(VertexAIModels.Gemini.Gemini38Flash);
var response = await model.GenerateContentAsync("Hello from Vertex AI!");
Console.WriteLine(response.Text());The newest Gemini models are served from the
globallocation. Regional services such as the RAG Engine need a region likeus-central1. See Initialization, Authentication and Configuration & Error Handling for all options, including service accounts, OAuth, express mode and environment variables.
var chat = model.StartChat();
var reply = await chat.GenerateContentAsync("Hi! Remember that my name is Ada.");
Console.WriteLine(reply.Text());
await foreach (var chunk in chat.StreamContentAsync("What is my name?"))
Console.Write(chunk.Text());More: Chat Session · Streaming
var request = new GenerateContentRequest();
request.AddText("Compare the image with the PDF.");
request.AddInlineFile(@"C:\files\chart.png"); // local file, sent inline
request.AddRemoteFile("https://example.com/report.pdf", "application/pdf"); // remote file
var response = await model.GenerateContentAsync(request);More: Multimodal Features · Files Client
public class Recipe { public string? Name { get; set; } public List<string>? Ingredients { get; set; } }
var recipe = await model.GenerateObjectAsync<Recipe>("Give me a pancake recipe.");More: JSON Mode
Requires Google_GenerativeAI.Tools. Functions run automatically and their results go back to the model.
var weatherTool = new QuickTool(
([Description("City name")] string city) => $"It is 22°C and sunny in {city}.",
"GetWeather", "Gets the current weather for a city");
model.AddFunctionTool(weatherTool);
var answer = await model.GenerateContentAsync("What's the weather in Paris?");Source-generated tools ([FunctionTool] and [GenerateJsonSchema] interfaces) and built-in tools such as Google
Search and code execution are covered in
Function Calling.
Connect any MCP server (stdio, HTTP/SSE or a custom transport) and expose its tools to Gemini.
var transport = McpTransportFactory.CreateStdioTransport(
"everything", "npx", new[] { "-y", "@modelcontextprotocol/server-everything" });
using var mcpTool = await McpTool.CreateAsync(transport);
model.AddFunctionTool(mcpTool);More: MCP Integration · samples/McpIntegrationDemo
Requires Google_GenerativeAI.Microsoft.
IChatClient chatClient = new GenerativeAIChatClient("YOUR_API_KEY", GoogleAIModels.Gemini38Flash);
var result = await chatClient.GetResponseAsync("Write a haiku about .NET.");
Console.WriteLine(result.Text);More: Microsoft.Extensions.AI · ASP.NET Core / Web
Requires Google_GenerativeAI.Live. Real-time, bidirectional audio and video sessions over WebSockets.
using var live = new MultiModalLiveClient(new GoogleAIPlatformAdapter("YOUR_API_KEY"),
GoogleAIModels.Gemini38Live,
new GenerationConfig { ResponseModalities = new List<Modality> { Modality.AUDIO } });
live.AudioChunkReceived += (_, e) => PlayAudio(e.Buffer);
await live.ConnectAsync();
await live.SentTextAsync("Hello, Gemini!");Session resumption, transcription, manual activity detection, context updates, ephemeral tokens and Live Music: Multimodal Live API · samples/TwoWayAudioCommunicationWpf
Stateful model and agent interactions with streaming, background execution and automatic continuation.
var interactions = googleAi.CreateInteractionsClient();
var interaction = await interactions.CreateAsync(new CreateInteractionRequest
{
Model = InteractionModels.Gemini38Flash,
Input = "Summarize the history of the transistor.",
Background = true
});
var completed = await interactions.WaitForCompletionAsync(interaction.Id!, timeout: TimeSpan.FromMinutes(5));
Console.WriteLine(completed.OutputText);More: Interactions API
var stores = googleAi.CreateFileSearchStoresClient();
var store = await stores.CreateFileSearchStoreAsync("product-docs");
await stores.WaitForOperationAsync(await stores.UploadToFileSearchStoreAsync(store.Name!, "manual.pdf"));
model.UseFileSearch(store.Name!);
var grounded = await model.GenerateContentAsync("How do I reset the device?");More: File Search · Vertex RAG Engine
| Capability | Documentation |
|---|---|
| Embeddings (Gemini API and Vertex AI, task types, output dimensionality) | Embeddings |
| Context caching | Context Caching |
| Image generation (Gemini native image models) | Image Generation |
| Video generation (Veo on Vertex AI) | Video Generation |
| Speech generation (text-to-speech, single and multi-speaker) | Speech Generation |
| Batch processing (inline, file, GCS and BigQuery) | Batch API |
| Model tuning | Model Tuning |
| Webhooks | Webhooks |
| Agent APIs (decisions, voices, agents, environments, triggers, credentials) | Agent APIs |
| Vertex AI RAG Engine | Vertex RAG Engine |
| Model and file management | Model Client · Files Client |
| Supported models and replacements for retired models | Supported Models |
| NativeAOT and trimming | NativeAOT & Trimming |
- Latest Google APIs: the Interactions API, File Search, webhooks, ephemeral Live tokens, Live Music, model tuning, agent APIs, RAG Engine configuration and the newest Gemini models.
- Live API additions: manual activity signals, realtime text and video, context updates, session resumption and transcription settings.
- Platform: new
net10.0andnet11.0targets, updated dependencies (includingMicrosoft.Extensions.AIandModelContextProtocol2.x), and structured API error parsing. - Gemini 3.x compatibility: function results are sent with the
userrole automatically. - Retired models: constants for retired models are marked
[Obsolete]and name their replacements.
v4 contains breaking changes. Read the Migration Guide before upgrading, and the Release Notes for the full list.
The wiki has a page for every feature, with complete examples, platform availability notes (Gemini API or Vertex AI) and troubleshooting tips. The generated API reference documents every public type.
For AI coding agents: llms.txt is a documentation index, llms-full.txt contains
the whole wiki in one file, and skills/google-generativeai-dotnet is an installable Claude Code skill that
teaches agents the v4 APIs. Contributors' agents should read AGENTS.md.
| Sample | Shows |
|---|---|
| McpIntegrationDemo | MCP servers over stdio and HTTP |
| TwoWayAudioCommunicationWpf | Real-time voice conversation with the Live API |
| WebAppIntegration | ASP.NET Core dependency injection |
| VertexRAGSimpleQA | Question answering with the Vertex AI RAG Engine |
| JavascriptCodeExecutor | A custom code-execution function tool |
| SemanticRetrievalDemo | Legacy semantic retrieval (AQA) |
Issues and pull requests are welcome. Read CONTRIBUTING.md for the development setup, coding guidelines and test conventions, or open an issue to report a bug or discuss a feature.
Thanks to HavenDV for tryAGI/LangChain and CSharpToJsonSchema, which powers the source-generated function tools.
Licensed under the MIT License. This is an unofficial SDK and is not affiliated with or endorsed by Google.