C# SDK for the Google Gemini API -- chat completions, embeddings, and vision
Repo tryAGI/Google_Generative_AI, read from GitHub 1 min ago. tryAGI has not joined Take My Repo.
tryAGI/Google_Generative_AI is a public repo on GitHub by tryAGI. C# SDK for the Google Gemini API -- chat completions, embeddings, and vision. It declares the MIT license on GitHub. It is written mainly in C#, has 10 stars and last changed on 2026-11-20. Nobody has reviewed it on Take My Repo yet, which says nothing about its quality. Read from GitHub on 2026-11-21.
In the maintainer's words. Shown from GitHub; Take My Repo does not keep a copy.
net10.0IChatClient, IEmbeddingGenerator and ISpeechToTextClient supportGeminiNextGenClientGeminiCloudLiveClientusing Google.Gemini; using var client = new GeminiClient(apiKey);
The SDK implements IChatClient and IEmbeddingGenerator:
using Google.Gemini; using Microsoft.Extensions.AI; #pragma warning disable MEAI001 // ISpeechToTextClient is evaluation API // IChatClient IChatClient chatClient = new GeminiClient(apiKey); var response = await chatClient.GetResponseAsync( [new ChatMessage(ChatRole.User, "Hello!")], new ChatOptions { ModelId = "gemini-2.0-flash" }); // IEmbeddingGenerator IEmbeddingGenerator<string, Embedding<float>> generator = new GeminiClient(apiKey); var embeddings = await generator.GenerateAsync( ["Hello, world!"], new EmbeddingGenerationOptions { ModelId = "gemini-embedding-001" }); // ISpeechToTextClient ISpeechToTextClient stt = new GeminiClient(apiKey); using var wav = File.OpenRead("speech.wav"); var transcription = await stt.GetTextAsync(wav);
SpeakAsync defaults to gemini-3.8-flash-lite-tts; choose
gemini-3.8-flash-tts for more expressive speech. Gemini 3.8 returns WAV by
default, which WriteWavFile saves without adding a second header:
using Google.Gemini; using var client = new GeminiClient(apiKey); var result = await client.SpeakAdvancedAsync( text: "Hello! This is Gemini.", voiceName: GeminiVoices.Puck, style: "cheerful and friendly"); Console.WriteLine($"{result.AudioData!.Length} bytes, {result.MimeType}"); result.WriteWavFile("speech.wav");
GeminiAudioTags exposes constants for the commonly supported inline audio tags
(emotion / style / delivery / pacing). GeminiVoices lists all 30 prebuilt voice
names, and client.ListTtsModelsAsync() discovers TTS-capable models at runtime.
SpeakAdvancedAsync also accepts a stored voice_... ID or stateless
voicekey_... and an explicit audio output format. Use the generated
SpeechConfig, SpeechMetadata, and MultiSpeakerVoiceConfig models for
multi-speaker turns.
The new Voices endpoint is exposed by a separate generated client:
using Google.Gemini.NextGen; using var nextGen = new GeminiNextGenClient(apiKey); var voices = await nextGen.Voices.ListAsync(type: ["prebuilt"]); var designed = await nextGen.Voices.CreateAsync(new CreateVoiceRequest { Store = true, Voice = new Voice { Type = VoiceType.Prompted, Prompted = new PromptedVoice { Input = "A warm, thoughtful narrator" }, }, }); // Use designed.Id as voiceName in SpeakAdvancedAsync.
GeminiNextGenClient also exposes the Interactions API used by Lyria 3.5,
Gemini Omni video operations, agent workflows, and newer platform endpoints.
See docs/guides/tts-and-stt.md and the
samples/AudioRoundTrip console for a complete walk-through.
For Google Cloud Live Avatar, see the recent Gemini API guide.
The SDK supports the Gemini Live API for real-time bidirectional voice and video interactions over WebSocket:
using Google.Gemini; using var client = new GeminiClient(apiKey); // Connect to the Live API await using var session = await client.ConnectLiveAsync(new LiveSetupConfig { Model = "models/gemini-3.1-flash-live-preview", GenerationConfig = new GenerationConfig { ResponseModalities = [GenerationConfigResponseModalitie.Audio], }, }); // Send text and receive audio responses await session.SendTextAsync("Hello, how are you?"); await foreach (var message in session.ReadEventsAsync()) { // Audio data in message.ServerContent.ModelTurn.Parts[].InlineData if (message.ServerContent?.TurnComplete == true) break; }
Voice selection and speech config:
await using var session = await client.ConnectLiveAsync(new LiveSetupConfig { Model = "models/gemini-3.1-flash-live-preview", GenerationConfig = new GenerationConfig { ResponseModalities = [GenerationConfigResponseModalitie.Audio], SpeechConfig = new SpeechConfig { VoiceConfig = new VoiceConfig { PrebuiltVoiceConfig = new PrebuiltVoiceConfig { VoiceName = "Kore", // Aoede, Charon, Fenrir, Kore, Puck, etc. }, }, }, }, });
Multi-turn conversation:
// First turn await session.SendTextAsync("My name is Alice"); await foreach (var msg in session.ReadEventsAsync()) { if (msg.ServerContent?.TurnComplete == true) break; } // Second turn — the model remembers context await session.SendTextAsync("What's my name?");
System instruction (customize model behavior):
await using var session = await client.ConnectLiveAsync(new LiveSetupConfig { Model = "models/gemini-3.1-flash-live-preview", GenerationConfig = new GenerationConfig { ResponseModalities = [GenerationConfigResponseModalitie.Audio], }, SystemInstruction = new Content { Parts = [new Part { Text = "You are a friendly pirate. Always respond in pirate speak." }], }, });
Tool calling:
var config = new LiveSetupConfig { Model = "models/gemini-3.1-flash-live-preview", GenerationConfig = new GenerationConfig { ResponseModalities = [GenerationConfigResponseModalitie.Audio], }, Tools = [new Tool { FunctionDeclarations = [myFunction] }], }; await using var session = await client.ConnectLiveAsync(config); await session.SendTextAsync("What's the weather in London?"); await foreach (var message in session.ReadEventsAsync()) { if (message.ToolCall is { } toolCall) { // Handle function call and send response await session.SendToolResponseAsync([new FunctionResponse { Name = toolCall.FunctionCalls![0].Name, Id = toolCall.FunctionCalls[0].Id, Response = new { temperature = "15C" }, }]); } // Tool calls cancelled due to user interruption if (message.ToolCallCancellation is { } cancellation) { Console.WriteLine($"Tool calls cancelled: {string.Join(", ", cancellation.Ids!)}"); } if (message.ServerContent?.TurnComplete == true) break; }
Use FunctionDeclaration.Parameters for simple tool schemas. If you need raw JSON Schema features such as additionalProperties: false, exact propertyOrdering, or you already have a JSON Schema document to reuse, prefer FunctionDeclaration.ParametersJsonSchema instead. The detailed Live API example is in the Live API guide.
Session resumption (reconnect without losing context):
var config = new LiveSetupConfig { Model = "models/gemini-3.1-flash-live-preview", GenerationConfig = new GenerationConfig { ResponseModalities = [GenerationConfigResponseModalitie.Audio], }, SessionResumption = new LiveSessionResumptionConfig(), }; await using var session1 = await client.ConnectLiveAsync(config); // ... interact ... var handle = session1.LastSessionResumptionHandle; // Later, reconnect with the handle var config2 = new LiveSetupConfig { // ... same config ... SessionResumption = new LiveSessionResumptionConfig { Handle = handle }, }; await using var session2 = await client.ConnectLiveAsync(config2);
Output transcription (get text alongside audio responses):
var config = new LiveSetupConfig { Model = "models/gemini-3.1-flash-live-preview", GenerationConfig = new GenerationConfig { ResponseModalities = [GenerationConfigResponseModalitie.Audio], }, OutputAudioTranscription = new LiveOutputAudioTranscription(), }; await using var session = await client.ConnectLiveAsync(config); await session.SendTextAsync("Tell me a joke"); await foreach (var message in session.ReadEventsAsync()) { // Text transcription of the audio response if (message.ServerContent?.OutputTranscription?.Text is { } text) Console.Write(text); if (message.ServerContent?.TurnComplete == true) break; }
Send audio/video:
// Send PCM audio (16-bit, 16kHz, little-endian, mono) await session.SendAudioAsync(pcmBytes); // Send audio with custom MIME type await session.SendAudioAsync(audioBytes, "audio/pcm;rate=24000"); // Send video frame await session.SendVideoAsync(jpegBytes, "image/jpeg"); // Stream video frames in a loop foreach (var frame in videoFrames) { await session.SendVideoAsync(frame, "image/jpeg"); await Task.Delay(100); // ~10 fps }
Auto-reconnect on GoAway (resilient sessions):
// ResilientLiveSession automatically reconnects when the server sends GoAway await using var session = await client.ConnectResilientLiveAsync(new LiveSetupConfig { Model = "models/gemini-3.1-flash-live-preview", GenerationConfig = new GenerationConfig { ResponseModalities = [GenerationConfigResponseModalitie.Audio], }, }); session.GoAwayReceived += (sender, goAway) => Console.WriteLine($"Server closing in {goAway.TimeLeft}, reconnecting..."); session.Reconnected += (sender, _) => Console.WriteLine("Reconnected successfully!"); await session.SendTextAsync("Hello!"); // Events keep flowing transparently across reconnections await foreach (var message in session.ReadEventsAsync()) { if (message.ServerContent?.TurnComplete == true) break; }
Input audio transcription (get text for audio you send):
var config = new LiveSetupConfig { Model = "models/gemini-3.1-flash-live-preview", GenerationConfig = new GenerationConfig { ResponseModalities = [GenerationConfigResponseModalitie.Audio], }, InputAudioTranscription = new LiveInputAudioTranscription(), }; await using var session = await client.ConnectLiveAsync(config); await session.SendAudioAsync(pcmBytes); await foreach (var message in session.ReadEventsAsync()) { // Text transcription of the audio you sent if (message.ServerContent?.InputTranscription?.Text is { } text) Console.Write($"[You said: {text}]"); if (message.ServerContent?.TurnComplete == true) break; }
Context window compression (for longer sessions):
var config = new LiveSetupConfig { Model = "models/gemini-3.1-flash-live-preview", GenerationConfig = new GenerationConfig { ResponseModalities = [GenerationConfigResponseModalitie.Audio], }, ContextWindowCompression = new LiveContextWindowCompression { SlidingWindow = new LiveSlidingWindow { TargetTokens = 1024, // tokens to retain after compression }, }, };
Interruption handling (user speaks during model response):
await foreach (var message in session.ReadEventsAsync()) { if (message.ServerContent?.Interrupted == true) { // Model response was cut short — user started speaking Console.WriteLine("Model interrupted by user input"); } if (message.ServerContent?.ModelTurn?.Parts is { } parts) { foreach (var part in parts) { // Process audio/text parts (may be partial if interrupted) if (part.InlineData?.Data is { } audioData) PlayAudio(audioData); } } if (message.ServerContent?.TurnComplete == true) break; }
Usage metadata (track token consumption):
await foreach (var message in session.ReadEventsAsync()) { if (message.UsageMetadata is { } usage) { Console.WriteLine($"Prompt tokens: {usage.PromptTokenCount}"); Console.WriteLine($"Response tokens: {usage.CandidatesTokenCount}"); Console.WriteLine($"Total tokens: {usage.TotalTokenCount}"); } if (message.ServerContent?.TurnComplete == true) break; }
GoAway handling (graceful session migration):
await foreach (var message in session.ReadEventsAsync()) { if (message.GoAway is { } goAway) { // Server is closing soon — reconnect using session resumption Console.WriteLine($"Server closing in {goAway.TimeLeft}, reconnecting..."); break; // dispose session and reconnect with resumption handle } if (message.ServerContent?.TurnComplete == true) break; }
Audio round-trip (send and receive audio):
var config = new LiveSetupConfig { Model = "models/gemini-3.1-flash-live-preview", GenerationConfig = new GenerationConfig { ResponseModalities = [GenerationConfigResponseModalitie.Audio], }, }; await using var session = await client.ConnectLiveAsync(config); // Send PCM audio (16-bit, 16kHz, little-endian, mono) await session.SendAudioAsync(pcmBytes); // Receive audio response await foreach (var message in session.ReadEventsAsync()) { if (message.ServerContent?.ModelTurn?.Parts is { } parts) { foreach (var part in parts) { if (part.InlineData?.Data is { } audioData) { // audioData is base64-decoded PCM audio (24kHz) PlayAudio(audioData); } } } if (message.ServerContent?.TurnComplete == true) break; }
The Gemini API Free Tier is model-specific. In practice, that means this SDK can be used for many free workflows, but whether a call is free depends on the model you choose, not on the SDK method name.
gemini-embedding-001 and gemini-embedding-2-preview.For the current Free Tier model categories, publicly documented quotas, and official links, see the Gemini API Free Tier guide in the docs and Google's docs for pricing, billing, rate limits, and available regions.
using var client = new GeminiClient(apiKey); var modelId = GetGenerateContentModelId(); try { IChatClient chatClient = client; var updates = chatClient.GetStreamingResponseAsync( messages: [ new ChatMessage(ChatRole.User, "Generate 5 random words.") ], options: new ChatOptions { ModelId = modelId, }); var deltas = new List<string>(); await foreach (var update in updates) { if (!string.IsNullOrWhiteSpace(update.Text)) { deltas.Add(update.Text); } } // In streaming mode, rate limiting may not throw ApiException but instead // return empty/truncated data. Treat empty results as inconclusive. if (deltas.Count == 0) { return; } } catch (ApiException ex) when (ex.StatusCode is System.Net.HttpStatusCode.TooManyRequests) { }
using var client = new GeminiClient(apiKey); var modelId = GetGenerateContentModelId(); try { IChatClient chatClient = client; var response = await chatClient.GetResponseAsync( messages: [ new ChatMessage(ChatRole.User, "Generate 5 random words.") ], options: new ChatOptions { ModelId = modelId, }); } catch (ApiException ex) when (ex.StatusCode is System.Net.HttpStatusCode.TooManyRequests) { }
using var client = CreateTestClient(); IChatClient chatClient = client; var metadata = chatClient.GetService<ChatClientMetadata>();
using var client = CreateTestClient(); IChatClient chatClient = client; var result = chatClient.GetService<ChatClientMetadata>(serviceKey: "unknown");
using var client = CreateTestClient(); IChatClient chatClient = client; var self = chatClient.GetService<GeminiClient>();
using var client = new GeminiClient(apiKey); var modelId = GetGenerateContentModelId(); try { var getWeatherTool = AIFunctionFactory.Create( (string location) => $"The weather in {location} is 72°F and sunny.", name: "get_weather", description: "Gets the current weather for a given location."); IChatClient chatClient = client; var messages = new List<ChatMessage> { new(ChatRole.User, "What is the weather in Paris?"), }; // First turn: model requests tool call var response = await chatClient.GetResponseAsync( messages, new ChatOptions { ModelId = modelId, Tools = [getWeatherTool], }); var functionCall = response.Messages .SelectMany(m => m.Contents) .OfType<FunctionCallContent>() .FirstOrDefault(); // Verify thought signature is preserved on function call content // (Gemini API requires it to be echoed back in subsequent turns) if (functionCall!.AdditionalProperties?.TryGetValue("gemini.thoughtSignature", out var sig) == true) { } // Add assistant message with function call and tool result messages.AddRange(response.Messages); var toolResult = await getWeatherTool.InvokeAsync( functionCall.Arguments is { } args ? new AIFunctionArguments(args) : null); messages.Add(new ChatMessage(ChatRole.Tool, [ new FunctionResultContent(functionCall.CallId, toolResult), ])); // Second turn: model should produce a final text response // (this verifies the thought signature round-trip works — the API // rejects requests with missing thought signatures) var finalResponse = await chatClient.GetResponseAsync( messages, new ChatOptions { ModelId = modelId, Tools = [getWeatherTool], }); } catch (ApiException ex) when (ex.StatusCode is System.Net.HttpStatusCode.TooManyRequests) { }
using var client = new GeminiClient(apiKey); var modelId = GetGenerateContentModelId(); try { var getWeatherTool = AIFunctionFactory.Create( (string location) => $"The weather in {location} is 72°F and sunny.", name: "get_weather", description: "Gets the current weather for a given location."); IChatClient chatClient = client; var response = await chatClient.GetResponseAsync( [ new ChatMessage(ChatRole.User, "What is the weather in Paris?") ], new ChatOptions { ModelId = modelId, Tools = [getWeatherTool], }); // The model should request a tool call var functionCall = response.Messages .SelectMany(m => m.Contents) .OfType<FunctionCallContent>() .FirstOrDefault(); } catch (ApiException ex) when (ex.StatusCode is System.Net.HttpStatusCode.TooManyRequests) { }
using var client = new GeminiClient(apiKey); var modelId = GetGenerateContentModelId(); try { var getWeatherTool = AIFunctionFactory.Create( (string location) => $"The weather in {location} is 72°F and sunny.", name: "get_weather", description: "Gets the current weather for a given location."); IChatClient chatClient = client; var updates = chatClient.GetStreamingResponseAsync( [ new ChatMessage(ChatRole.User, "What is the weather in Paris?") ], new ChatOptions { ModelId = modelId, Tools = [getWeatherTool], }); // Collect all streaming updates var functionCalls = new List<FunctionCallContent>(); await foreach (var update in updates) { functionCalls.AddRange(update.Contents.OfType<FunctionCallContent>()); } // In streaming mode, rate limiting may not throw ApiException but instead // return empty/truncated data. Treat empty results as inconclusive. if (functionCalls.Count == 0) { return; } } catch (ApiException ex) when (ex.StatusCode is System.Net.HttpStatusCode.TooManyRequests) { }
using var client = new GeminiClient(apiKey); var modelId = GetGenerateContentModelId(); try { var response = await client.ModelsCountTokensAsync( modelsId: modelId, contents: [ new Content { Role = "user", Parts = [new Part { Text = "What is the meaning of life?" }], }, new Content { Role = "model", Parts = [new Part { Text = "The meaning of life is a philosophical question." }], }, new Content { Role = "user", Parts = [new Part { Text = "Can you elaborate?" }], }, ]); } catch (ApiException ex) when (ex.StatusCode is System.Net.HttpStatusCode.TooManyRequests) { }
using var client = new GeminiClient(apiKey); var modelId = GetGenerateContentModelId(); try { var response = await client.ModelsCountTokensAsync( modelsId: modelId, contents: [ new Content { Parts = [new Part { Text = "Hello, world! This is a test of token counting." }], }, ]); } catch (ApiException ex) when (ex.StatusCode is System.Net.HttpStatusCode.TooManyRequests) { }
using var client = new GeminiClient(apiKey); try { // First generate an image to edit var original = await client.GenerateImageAsync( prompt: "A plain white background", imageSize: "1K"); var edited = await client.EditImageAsync( prompt: "Add a red circle in the center", imageData: original.ImageData!, mimeType: original.MimeType ?? "image/png", imageSize: "1K"); } catch (ApiException ex) when (ex.StatusCode is System.Net.HttpStatusCode.TooManyRequests) { }
using var client = new GeminiClient(apiKey); var modelId = GetEmbeddingModelId(); try { IEmbeddingGenerator<string, Embedding<float>> generator = client; var result = await generator.GenerateAsync( values: ["Hello, world!", "Goodbye, world!"], options: new EmbeddingGenerationOptions { ModelId = modelId, }); } catch (ApiException ex) when (ex.StatusCode is System.Net.HttpStatusCode.TooManyRequests) { }
using var client = CreateTestClient(); IEmbeddingGenerator<string, Embedding<float>> generator = client; var metadata = generator.GetService<EmbeddingGeneratorMetadata>();
using var client = CreateTestClient(); IEmbeddingGenerator<string, Embedding<float>> generator = client; var result = generator.GetService<EmbeddingGeneratorMetadata>(serviceKey: "unknown");
using var client = CreateTestClient(); IEmbeddingGenerator<string, Embedding<float>> generator = client; var self = generator.GetService<GeminiClient>();
using var client = new GeminiClient(apiKey); var modelId = GetEmbeddingModelId(); try { IEmbeddingGenerator<string, Embedding<float>> generator = client; var result = await generator.GenerateAsync( values: ["Hello, world!"], options: new EmbeddingGenerationOptions { ModelId = modelId, }); } catch (ApiException ex) when (ex.StatusCode is System.Net.HttpStatusCode.TooManyRequests) { }
using var client = new GeminiClient(apiKey); var modelId = GetEmbeddingModelId(); try { IEmbeddingGenerator<string, Embedding<float>> generator = client; // Use RETRIEVAL_QUERY task type for search queries var queryResult = await generator.GenerateAsync( values: ["How do I reset my password?"], options: new EmbeddingGenerationOptions { ModelId = modelId, AdditionalProperties = new AdditionalPropertiesDictionary { ["TaskType"] = "RETRIEVAL_QUERY", }, }); // Use RETRIEVAL_DOCUMENT task type with a Title for documents var docResult = await generator.GenerateAsync( values: ["To reset your password, go to Settings > Security > Change Password."], options: new EmbeddingGenerationOptions { ModelId = modelId, AdditionalProperties = new AdditionalPropertiesDictionary { ["TaskType"] = "RETRIEVAL_DOCUMENT", ["Title"] = "Password Reset Guide", }, }); } catch (ApiException ex) when (ex.StatusCode is System.Net.HttpStatusCode.TooManyRequests) { }
using var client = new GeminiClient(apiKey); var response = await client.FilesListAsync(); // Should return a valid response even if no files exist
using var client = new GeminiClient(apiKey); var modelId = GetGenerateContentModelId(); try { Console.WriteLine($"Using model: {modelId}"); GenerateContentResponse response = await client.ModelsGenerateContentAsync( modelsId: modelId, contents: [ new Content { Parts = [ new Part { Text = "Generate 5 random words", }, ], Role = "user", }, ], generationConfig: new GenerationConfig(), safetySettings: new List<SafetySetting>()); Console.WriteLine(response.Candidates?[0].Content?.Parts?[0].Text); } catch (ApiException ex) when (ex.StatusCode is System.Net.HttpStatusCode.TooManyRequests) { }
using var client = new GeminiClient(apiKey); try { var result = await client.GenerateImageAsync( prompt: "A simple red circle on a white background", imageSize: "1K"); } catch (ApiException ex) when (ex.StatusCode is System.Net.HttpStatusCode.TooManyRequests) { }
using var client = new GeminiClient(apiKey); try { var result = await client.GenerateImageAsync( prompt: "A landscape with mountains", imageSize: "1K", aspectRatio: "16:9"); } catch (ApiException ex) when (ex.StatusCode is System.Net.HttpStatusCode.TooManyRequests) { }
using var client = new GeminiClient(apiKey); try { // First generate a reference image var reference = await client.GenerateImageAsync( prompt: "A simple red square", imageSize: "1K"); var result = await client.GenerateImageWithReferencesAsync( prompt: "Create a similar shape but in blue", referenceImages: [(reference.ImageData!, reference.MimeType ?? "image/png")], imageSize: "1K"); } catch (ApiException ex) when (ex.StatusCode is System.Net.HttpStatusCode.TooManyRequests) { }
using var client = new GeminiClient(apiKey); try { var result = await client.GenerateVideoAsync( prompt: "A serene beach at sunset with gentle waves"); } catch (ApiException ex) when (ex.StatusCode is System.Net.HttpStatusCode.TooManyRequests) { } catch (ApiException ex) when (ex.StatusCode is System.Net.HttpStatusCode.BadRequest) { // VIDEO modality may not be supported in generateContent endpoint yet }
using var client = new GeminiClient(apiKey); try { var image = await client.GenerateImageAsync( prompt: "A still landscape with mountains and a lake", imageSize: "1K"); var result = await client.GenerateVideoFromImageAsync( prompt: "Animate the clouds moving slowly across the sky", imageData: image.ImageData!, mimeType: image.MimeType ?? "image/png"); } catch (ApiException ex) when (ex.StatusCode is System.Net.HttpStatusCode.TooManyRequests) { } catch (ApiException ex) when (ex.StatusCode is System.Net.HttpStatusCode.BadRequest) { }
using var client = new GeminiClient(apiKey); try { var startFrame = await client.GenerateImageAsync( prompt: "A red circle on a white background", imageSize: "1K"); var endFrame = await client.GenerateImageAsync( prompt: "A blue square on a white background", imageSize: "1K"); var result = await client.InterpolateFramesAsync( startFrame: startFrame.ImageData!, endFrame: endFrame.ImageData!, prompt: "Smoothly transition between the two shapes"); } catch (ApiException ex) when (ex.StatusCode is System.Net.HttpStatusCode.TooManyRequests) { } catch (ApiException ex) when (ex.StatusCode is System.Net.HttpStatusCode.BadRequest) { }
using var client = new GeminiClient(apiKey); ListModelsResponse response = await client.ModelsListAsync(); foreach (var model in response.Models ?? []) { Console.WriteLine(model.Name); }
using var client = new GeminiClient(apiKey); try { var result = await client.SpeakAsync( text: "Say calmly: Testing with a different voice. This should sound professional.", voiceName: "Kore"); } catch (ApiException ex) when (ex.StatusCode is System.Net.HttpStatusCode.TooManyRequests) { } catch (ApiException ex) when (ex.StatusCode is System.Net.HttpStatusCode.BadRequest && ex.Message.Contains("only be used for TTS")) { }
using var client = new GeminiClient(apiKey); try { var result = await client.SpeakAsync( text: "Say cheerfully: Hello, this is a test of text to speech. Have a wonderful day!", voiceName: "Puck"); } catch (ApiException ex) when (ex.StatusCode is System.Net.HttpStatusCode.TooManyRequests) { } catch (ApiException ex) when (ex.StatusCode is System.Net.HttpStatusCode.BadRequest && ex.Message.Contains("only be used for TTS")) { }
using var client = new GeminiClient(apiKey); try { // First generate audio to transcribe var audio = await client.SpeakAsync( text: "Read aloud: The quick brown fox jumps over the lazy dog."); var transcription = await client.TranscribeAsync( audioData: audio.AudioData!, mimeType: audio.MimeType ?? "audio/wav"); } catch (ApiException ex) when (ex.StatusCode is System.Net.HttpStatusCode.TooManyRequests) { } catch (ApiException ex) when (ex.StatusCode is System.Net.HttpStatusCode.BadRequest && ex.Message.Contains("only be used for TTS")) { }
using var client = new GeminiClient(apiKey); try { // Generate a short music clip from a text prompt using the Lyria 3 Clip model. var result = await client.GenerateMusicAsync( prompt: "A cheerful acoustic guitar melody with a light percussion beat, major key, 120 BPM"); } catch (ApiException ex) when (ex.StatusCode is System.Net.HttpStatusCode.TooManyRequests) { } catch (ApiException ex) when (ex.StatusCode is System.Net.HttpStatusCode.BadRequest) { }
tryAGI/Google_Generative_AI is a public repo on GitHub by tryAGI. C# SDK for the Google Gemini API -- chat completions, embeddings, and vision.
It declares the MIT license on GitHub.
Its maker has not tagged a system, so it is unknown here. Its README says what it needs.
Open "Take it" on its page: Take My Repo writes an install plan for your machine and hands it to your AI agent (Claude Code, Codex or Cursor), which asks you before each step. Take My Repo has not tested it on any machine.
Its last change on GitHub was on 2026-11-20. Take My Repo does not judge from that whether it is maintained.
Nobody has reviewed it on Take My Repo yet, which says nothing about its quality.
Your lightweight open-source personal agent.

The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond.

High-performance .NET BPE tokenizer — up to 618 MiB/s, competitive with Rust. Zero-allocation counting, multilingual cache, o200k/cl100k/r50k/p50k encodings + HuggingFace tokenizer.json support.

C# SDK for the Hugging Face API -- inference, embeddings, and model hub

C# SDK for the Anthropic API -- Claude chat completions, tool calling, and vision


This page is also available as structured data, with the same sources and dates.
/api/v1/resources/gh/tryAGI/Google_Generative_AITake My Repo has not tested this on your machine. Requirements come from the project's own documentation.