Mscc.GenerativeAI .NET Client

repository·main·Indexed 42 days ago

https://github.com/mscraftsman/generative-ai

A comprehensive Gemini API client for .NET and ASP.NET Core providing access to Google AI Studio and Vertex AI models. Supports content generation, multi-turn chat, model tuning, embeddings, and advanced features such as Google Search grounding, structured JSON output with schemas, and multimodal input. Includes specialized packages for web applications and compatibility with Microsoft.Extensions.AI and Semantic Kernel.

Tokens
16K
Snippets
54
Records
66
Agent score
52%

What's inside Mscc.GenerativeAI

  1. Capabilities of the Gemini SDK for .NET

    main

    The Mscc.GenerativeAI library provides a comprehensive suite of tools for interacting with Gemini models, including:

    • Content Generation: GenerateContent for text responses and GenerateContentStream for real-time streaming responses.
    • Conversational AI: StartChat to initiate multi-turn chat sessions.
    • Model Management: List available models and retrieve specific model information.
    • Data & Embeddings: GenerateEmbeddings to convert text to numerical vectors and CountTokens to estimate token usage.
    • Advanced Features:
      • Grounded Answers: Generate answers based on provided context.
      • Tuned Models: Create custom models (supports text-bison-001 and gemini-2.0-flash-001).
      • File API: Upload and use large files with Gemini 2.0 and later models.
  2. Features of the Gemini API Client

    main

    The Mscc.GenerativeAI library provides a comprehensive set of features for interacting with Gemini models:

    • Model Management: List available models and retrieve detailed information about specific models.
    • Content Generation: Generate text content, stream responses for real-time applications, and generate grounded answers using provided context.
    • Embeddings & Tokens: Generate embeddings for text and count tokens to estimate usage costs.
    • Conversational AI: Start and manage chat sessions for multi-turn conversations.
    • Model Tuning: Create tuned models (currently supports text-bison-001 and gemini-2.0-flash-001).
    • File API: Upload and manage large files for use with Gemini 2.0 and later models.
  3. Best practices for using response schemas

    main

    When using ResponseSchema to guide model output, follow these best practices:

    • Token Limits: Remember that the size of your response schema counts towards your input token limit.
    • Required vs. Optional Fields: By default, fields are optional. The model may skip them if context is insufficient. To force the model to provide a value, set fields as required.
    • Prompt Context: If the model is not producing the expected structure, add more context to your input prompt or revise the schema. A good debugging step is to review the model's response without structured output first to see how it naturally responds, then adjust the schema to match that behavior.
  4. Ground responses with Google Search

    main

    Grounding allows the model to use Google Search to verify facts.

    1. Simple Toggle: Set model.UseGrounding = true.
    2. Advanced Control: Use the tools parameter in GenerativeModel to pass a Tool containing GoogleSearchRetrieval with a DynamicRetrievalConfigMode and a threshold (float).

    Responses include GroundingMetadata in the Candidates item to provide details about the search-based grounding.

    // Advanced approach with retrieval parameters
    IGenerativeAI genAi = new GoogleAI(apiKey);
    var model = genAi.GenerativeModel(Model.Gemini25Flash, 
        tools: [new Tool { GoogleSearchRetrieval = 
            new(DynamicRetrievalConfigMode.ModeUnspecified, 0.06f) }]);
    
    var response = await model.GenerateContent(prompt);
  5. How the URL context tool works

    main

    The UrlContext tool employs a two-step retrieval process:

    1. Internal Index Cache: The tool first attempts to fetch content from an optimized internal cache.
    2. Live Fetch Fallback: If the URL is not found in the index (e.g., a very new page), the tool automatically performs a live fetch to retrieve the content in real-time.

    This mechanism balances speed and cost with the ability to access fresh data.

  6. Manage GenerativeModel lifecycle with IDisposable

    main

    GenerativeModel implements IDisposable to manage underlying resources. It is recommended to dispose of instances when they are no longer needed to prevent resource leaks. Use a using statement or call Dispose() manually in a finally block.

    // Using statement (Recommended)
    using (var model = new GenerativeModel(...))
    {
        // use model
    }
    
    // Manual disposal
    var model = new GenerativeModel(...);
    try
    {
        // use model
    }
    finally
    {
        model.Dispose();
    }
  7. Manage multi-turn conversations with Chat

    main

    Use model.StartChat() to create a chat session. This session automatically manages conversation history, allowing you to send sequential messages using SendMessage or SendMessageStream. You can access the full history via the chat.History property.

    using Mscc.GenerativeAI;
    
    var googleAi = new GoogleAI();
    var model = googleAi.GenerativeModel(model: Model.Gemini25Flash);
    var chat = model.StartChat();
    
    var prompt = "Hello, let's talk a bit about nature.";
    var response = await chat.SendMessage(prompt);
    Console.WriteLine(response.Text);
    
    // Access history
    chat.History.ForEach(c =>
    {
        Console.WriteLine($"{c.Role}: {c.Text}");
    });
  8. Quickstart: Make your first Gemini API request in .NET

    main

    To get started with the Gemini SDK for .NET, initialize a GoogleAI instance with your API key, select a model using GenerativeModel, and call GenerateContent to receive a response. This example uses the Model.Gemini25Flash model to generate text from a prompt.

    using Mscc.GenerativeAI;
    
    var googleAI = new GoogleAI(apiKey: "your API key");
    var model = googleAI.GenerativeModel(model: Model.Gemini25Flash);
    
    var response = await model.GenerateContent("Explain how AI works in a few words");
    Console.WriteLine(response.Text);
  9. Install Mscc.GenerativeAI.Web

    main

    To integrate Gemini API into your ASP.NET Core project, install the Mscc.GenerativeAI.Web package. You can use the .NET CLI, NuGet Package Manager Console, or manually edit your .csproj file.

    # Using .NET CLI
    dotnet add package Mscc.GenerativeAI.Web
    
    # Using NuGet Package Manager Console
    Install-Package Mscc.GenerativeAI.Web

    Or add directly to your .csproj:

    <ItemGroup>
      <PackageReference Include="Mscc.GenerativeAI.Web" Version="3.1.0" />
    </ItemGroup>
  10. Stream responses for fluid interactions

    main

    Instead of waiting for the full response, use GenerateContentStream to receive GenerateContentResponse instances incrementally. This is ideal for real-time UI updates.

    using Mscc.GenerativeAI;
    
    var prompt = "How are you doing today?";
    var googleAi = new GoogleAI();
    var model = googleAi.GenerativeModel(model: Model.Gemini25Flash);
    
    var responseStream = model.GenerateContentStream(prompt);
    
    await foreach (var response in responseStream)
    {
        Console.WriteLine($"{response.Text}");
    }
  11. Configure thinking budget for Gemini 2.5 models

    main

    Gemini 2.5 Flash and Pro models have "thinking" enabled by default to improve response quality. To disable this feature (which can reduce latency and token usage), set the ThinkingBudget to 0 within a ThinkingConfig object passed to the GenerationConfig.

    using Mscc.GenerativeAI;
    
    var googleAI = new GoogleAI(apiKey: "your API key");
    var model = googleAI.GenerativeModel(model: Model.Gemini25Flash);
    var generationConfig = new GenerationConfig()
    {
        ThinkingConfig = new ThinkingConfig()
        {
            ThinkingBudget = 0  // Disables thinking
        }
    };
    
    var response = await model.GenerateContent("Explain how AI works in a few words", 
        generationConfig: generationConfig);
    Console.WriteLine(response.Text);