Google GenerativeAI SDK for .NET

repository·main·Indexed 41 days ago

https://github.com/gunpal5/google_generativeai

An unofficial C# .NET SDK for interacting with Google's Generative AI models, including Gemini and Vertex AI. It provides simplified APIs for text generation, multimodal tasks, function calling, and RAG. Features include LangChain.net support, NativeAOT/Trimming compatibility since v2.4.0, and integration with the Model Context Protocol (MCP). The SDK is modularized into packages for tools, authentication, Microsoft AI ecosystem integration via IChatClient, web applications, and the Multimodal Live API.

Tokens
14.4K
Snippets
37
Records
50
Agent score
65%

What's inside Google GenerativeAI SDK

  1. Overview of Google Gemini Code Generation Demonstration

    main

    This sample demonstrates how to use Google Gemini for code generation and function calling. It showcases the capabilities of the Google_GenerativeAI SDK to integrate AI-powered features into applications.

    This specific demonstration leverages the JINT JavaScript interpreter to execute code, allowing the AI to generate and run JavaScript logic within a controlled environment.

  2. Overview of Google GenerativeAI SDK

    main

    The Google_GenerativeAI SDK is an unofficial C# .NET library for accessing Google Generative AI models (like Gemini and Imagen) and services (like Vertex AI). It is built on REST APIs and designed for high performance and flexibility.

    Key features include:

    • LangChain.net Support: Integration with LangChain workflows.
    • Function Calling: Simplified via source generators for argument classes.
    • Multimodal Support: Easy handling of text, images, and audio.
    • Vertex AI Support: Support for OAuth, Service Accounts, and Application Default Credentials (ADC).
    • NativeAOT/Trimming Compatibility: Fully compatible since v2.4.0.
  3. Compare Reflection-Based vs Code Generator-Based approaches

    main

    Choose your approach based on your project's scale and deployment target:

    AspectReflection-BasedCode Generator-Based
    Setup ComplexityLow (quick prototyping)Moderate (attributes, interfaces, codegen)
    SerializationManual (JsonSerializerContext required for NativeAOT)Automatic via generated code
    NativeAOT / TrimmingRequires extra steps to preserve reflection dataDesigned for AOT; minimal extra configuration
    GroupingPossible, but less structuredInterface-based approach naturally groups methods
    Best Use CaseSmall/short-lived projects, PoCsEnterprise solutions, complex/maintainable projects
  4. Use Google AQA for Semantic Search Retrieval (RAG)

    main
    The library supports Google's Attributed Question Answering (AQA) model to enhance RAG through semantic search. Unlike keyword matching, AQA uses deep semantic understanding to capture query intent and provides an "Answerable Probability" score to indicate confidence in the retrieved answer. This is useful for building systems that require high-precision retrieval and attribution.
  5. How MultiModalLiveClient works

    main

    The MultiModalLiveClient is the central component for real-time interaction with the Gemini Multimodal Live API via WebSockets. It manages the connection, handles message serialization, and uses an event-driven architecture to notify your application of incoming data.

    Key capabilities include:

    • Real-time communication: Streaming text and audio data.
    • Asynchronous operations: Non-blocking network I/O.
    • Event-driven updates: Subscribing to connection status, message reception, and audio/text chunks.
    • Tool integration: Support for function tools to extend model capabilities.
    • Audio processing: Handling audio in chunks with support for varying sample rates.
  6. Key Features of the Google_GenerativeAI SDK

    main

    The Google_GenerativeAI SDK is designed for efficient AI integration with the following core capabilities:

    • Effortless Code Integration: Provides developer-friendly APIs that minimize boilerplate, allowing for rapid integration of AI features into both small-scale and complex workflows.
    • Function Call Capabilities: Supports built-in dynamic function invocation. This allows developers to trigger backend logic or custom operations directly from the AI, reducing the need for manual wiring and validation code.
  7. Set up Two-Way Realtime Audio Communication with Gemini AI (WPF)

    main

    To implement two-way audio interaction between a .NET WPF application and Google Gemini AI, you must use the Google_GenerativeAI.Live package from the Google_GenerativeAI SDK. This allows for streaming microphone audio to the model and playing back received AI audio responses.

    Prerequisites

    Configuration

    Provide authentication via the GOOGLE_API_KEY environment variable:

    export GOOGLE_API_KEY="YOUR_API_KEY"
  8. Start a multi-turn chat session

    main

    To implement conversational AI, use the StartChat() method on a GenerativeModel instance. This creates a chat session that preserves context from previous messages, allowing for multi-turn reasoning. You can initialize the model using either GoogleAi or VertexAI providers.

    Workflow:

    1. Initialize the provider (GoogleAi or VertexAI).
    2. Create a GenerativeModel using a model name (e.g., models/gemini-1.5-flash).
    3. Call StartChat() to get a chat session object.
    4. Use GenerateContentAsync(...) on the chat session to exchange messages.
    // Using Google AI
    var googleAI = new GoogleAi("YOUR_GOOGLE_API_KEY");
    var generativeModel = googleAI.CreateGenerativeModel("models/gemini-1.5-flash");
    var chatSession = generativeModel.StartChat();
    var response = await chatSession.GenerateContentAsync("Hello!");
    
    // Using Vertex AI
    var vertexAI = new VertexAI(); 
    var generativeModel = vertexAI.CreateGenerativeModel("models/gemini-1.5-flash");
    var chatSession = generativeModel.StartChat();
    var response = await chatSession.GenerateContentAsync("Hello!");
  9. Use multimodal capabilities with local and remote files

    main

    Gemini models support multimodal inputs including images, audio, and video. You can provide these files in three ways:

    1. Local Files: Pass the absolute file path directly to GenerateContentAsync.
    2. Remote Files: Pass the file URI and the corresponding MIME type to GenerateContentAsync.
    3. GenerateContentRequest: For complex prompts, create a GenerateContentRequest object and use AddInlineFile(path) for local files or AddRemoteFile(uri, mimeType) for remote files.
    // 1. Local File
    var response = await geminiModel.GenerateContentAsync("Describe this image", @"C:\path\to\image.jpg");
    
    // 2. Remote File
    var response = await geminiModel.GenerateContentAsync("Summarize this PDF", "https://example.com/sample.pdf", "application/pdf");
    
    // 3. Using GenerateContentRequest for multiple files
    var request = new GenerateContentRequest();
    request.AddText("Describe these files");
    request.AddInlineFile(@"C:\files\example.png");
    request.AddRemoteFile("https://example.com/path/to/sample.pdf", "application/pdf");
    var response = await geminiModel.GenerateContentAsync(request);
  10. Handle JSON responses automatically

    main

    The SDK provides several ways to work with structured JSON data from Gemini:

    Automatic Deserialization

    • GenerateObjectAsync<T>(request): Directly returns a deserialized object of type T.
    • GenerateContentAsync<T>(request): Returns a response that can be converted using .ToObject<T>().
    • UseJsonMode<T>(): An extension method for GenerateContentRequest that instructs the model to return a JSON response matching type T.

    Manual JSON Parsing

    If you need more control, you can manually configure the GenerationConfig with ResponseMimeType = "application/json" and a ResponseSchema. To extract data from a standard response, use response.ExtractJsonBlocks() to retrieve raw JSON blocks, then call .ToObject<T>() on each block.

    // Option 1: Direct deserialization
    var myObject = await model.GenerateObjectAsync<SampleJsonClass>(request);
    
    // Option 2: Using JSON mode in request
    var request = new GenerateContentRequest();
    request.UseJsonMode<SampleJsonClass>();
    request.AddText("Give me a response.");
    var response = await model.GenerateContentAsync(request);
    var myObject = response.ToObject<SampleJsonClass>();
    
    // Option 3: Manual extraction from blocks
    var response = await model.GenerateContentAsync(request);
    var jsonBlocks = response.ExtractJsonBlocks();
    var myObjects = jsonBlocks.Select(block => block.ToObject<SampleJsonClass>());
  11. Implement Retrieval-Augmented Generation (RAG) with Vertex RAG Engine

    main

    You can implement RAG by integrating the Vertex RAG Engine, which allows Gemini to access external corpora and vector databases (like Pinecone or Weaviate) for grounded responses.

    To use this feature:

    1. Initialize VertexAI with your platform configuration.
    2. Use CreateRagManager() to get a manager for corpus operations.
    3. Create a corpus using CreateCorpusAsync.
    4. Import data into the corpus using ImportFilesAsync with a source (e.g., GcsSource).
    5. Create a generative model using CreateGenerativeModel, passing the corpus.Name to the corpusIdForRag parameter to link the model to your knowledge base.
    6. Call GenerateContentAsync to query the model using the retrieved context.
    // Initialize VertexAI with your platform configuration.
    var vertexAi = new VertexAI(GetTestVertexAIPlatform());
    
    // Create an instance of the RAG manager for corpus operations.
    var ragManager = vertexAi.CreateRagManager();
    
    // Create a new corpus for your knowledge base.
    var corpus = await ragManager.CreateCorpusAsync("My New Corpus", "My description");
    
    // Import data into the corpus from a specified source.
    var fileSource = new GcsSource() { /* Configure your GcsSource here */ };
    await ragManager.ImportFilesAsync(corpus.Name, fileSource);
    
    // Create a Gemini generative model configured to use the created corpus for RAG.
    var model = vertexAi.CreateGenerativeModel(VertexAIModels.Gemini.Gemini2Flash, corpusIdForRag: corpus.Name);
    
    // Generate content by querying the model.
    var result = await model.GenerateContentAsync("query related to the corpus");