Zonit.Extensions.Ai 1.0.11

There is a newer version of this package available.
See the version list below for details.
dotnet add package Zonit.Extensions.Ai --version 1.0.11
                    
NuGet\Install-Package Zonit.Extensions.Ai -Version 1.0.11
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Zonit.Extensions.Ai" Version="1.0.11" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Zonit.Extensions.Ai" Version="1.0.11" />
                    
Directory.Packages.props
<PackageReference Include="Zonit.Extensions.Ai" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Zonit.Extensions.Ai --version 1.0.11
                    
#r "nuget: Zonit.Extensions.Ai, 1.0.11"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#addin nuget:?package=Zonit.Extensions.Ai&version=1.0.11
                    
Install as a Cake Addin
#tool nuget:?package=Zonit.Extensions.Ai&version=1.0.11
                    
Install as a Cake Tool

Zonit.Extensions.Ai

A .NET library for integrating with AI models (OpenAI GPT) in applications, providing a simple and flexible architecture for text and image generation.

Main Features

  • OpenAI Model Support: GPT-4, GPT-4 Turbo, reasoning models (o1), DALL�E image generation
  • Flexible Architecture: Interface-driven, based on Clean Architecture
  • Type-safe Prompts: Strongly-typed prompts with automatic JSON Schema validation
  • AI Tools: Web search, file search with configuration
  • File Management: Built-in support for images and documents
  • Metadata Tracking: Automatic logging of cost, token counts, and execution time

Installation

Install-Package Zonit.Extensions.Ai

Configuration

1. Register Services

services.AddAi(options =>
{
    options.OpenAiKey = "your-openai-api-key";
});

2. appsettings.json

{
  "Ai": {
    "OpenAiKey": "your-openai-api-key"
  }
}

Basic Usage

Text Generation

public class TranslatePrompt : PromptBase<TranslateResponse>
{
    public string Content { get; set; }
    public string Language { get; set; }
    public string Culture { get; set; }

    public override string Prompt =>
        $"Translate the text '{Content}' into {Language} (culture: {Culture})";
}

public class TranslateResponse
{
    public string TranslatedText { get; set; }
    public string DetectedLanguage { get; set; }
}

// Usage:
var prompt = new TranslatePrompt
{
    Content = "Hello world!",
    Language = "pl",
    Culture = "pl-PL"
};

var result = await aiClient.GenerateAsync(prompt, new GPT4());
Console.WriteLine(result.Value.TranslatedText);

Image Generation

public class AnimalPrompt : PromptBase<byte[]>
{
    public string Animal { get; set; }

    public override string Prompt =>
        $"Generate an image depicting a {Animal}";
}

// Usage:
var prompt = new AnimalPrompt { Animal = "dog" };
var result = await aiClient.GenerateAsync(
    prompt,
    new GPTImage1
    {
        Quality = GPTImage1.QualityType.High,
        Size    = GPTImage1.SizeType.Square
    }
);

// Save the image:
await File.WriteAllBytesAsync("dog.png", result.Value.Data);

AI Models

Text Models

// Basic GPT-4
var gpt4 = new GPT4();

// GPT-4 Turbo with custom settings
var gpt4Turbo = new GPT4Turbo
{
    Temperature = 0.7,
    TopP        = 0.9,
    MaxTokens   = 2000
};

// Reasoning model (o1)
var reasoning = new GPT4Reasoning
{
    Reason        = OpenAiReasoningBase.ReasonType.High,
    ReasonSummary = OpenAiReasoningBase.ReasonSummaryType.Detailed
};

Image Models

var imageModel = new GPTImage1
{
    Quality = GPTImage1.QualityType.High,
    Size    = GPTImage1.SizeType.Landscape,
    Style   = GPTImage1.StyleType.Natural
};

AI Tools

public class SearchPrompt : PromptBase<SearchResponse>
{
    public string Query { get; set; }

    public override string Prompt => $"Search for information about: {Query}";

    public override IReadOnlyList<ITool> Tools =>
        new List<ITool>
        {
            new WebSearchTool
            {
                ContextSize = WebSearchTool.ContextSizeType.High
            }
        };

    public override ToolsType ToolChoice => ToolsType.WebSearch;
}
public override IReadOnlyList<ITool> Tools =>
    new List<ITool> { new FileSearchTool() };

public override ToolsType ToolChoice => ToolsType.FileSearch;

File Management

Create a File from Data

var fileData = await File.ReadAllBytesAsync("document.pdf");
var file = new FileModel("document.pdf", "application/pdf", fileData);

Create a File from Path

var file = await FileModel.CreateFromFilePathAsync("path/to/image.jpg");

Save a File

await file.SaveToFileAsync("output/saved-file.jpg");

Supported Formats

  • Images: JPG, PNG, GIF, BMP, WebP
  • Documents: PDF, DOC/DOCX, XLS/XLSX, PPT/PPTX
  • Text: TXT, JSON, CSV, XML

Metadata & Costs

var result = await aiClient.GenerateAsync(prompt, model);

// Cost information
Console.WriteLine($"Input cost: ${result.MetaData.PriceInput:F6}");
Console.WriteLine($"Output cost: ${result.MetaData.PriceOutput:F6}");
Console.WriteLine($"Total cost: ${result.MetaData.PriceTotal:F6}");

// Token counts
Console.WriteLine($"Input tokens: {result.MetaData.InputTokenCount}");
Console.WriteLine($"Output tokens: {result.MetaData.OutputTokenCount}");

// Execution time
Console.WriteLine($"Duration: {result.MetaData.Duration.TotalSeconds:F2}s");

Advanced Features

Logging Responses

var model = new GPT4
{
    StoreLogs = true
};

Custom JSON Schema

The library automatically generates JSON Schema from response classes. You can add descriptions with attributes:

[Description("Response containing the translated text")]
public class TranslateResponse
{
    [Description("The text translated into the target language")]
    public string TranslatedText { get; set; }

    [Description("The detected source language")]
    public string DetectedLanguage { get; set; }
}

Error Handling

try
{
    var result = await aiClient.GenerateAsync(prompt, model);
    // Use result.Value
}
catch (JsonException ex)
{
    // JSON parsing error
}
catch (InvalidOperationException ex)
{
    // API communication error
}

Architecture

The library follows Clean Architecture with layered separation:

  • Abstractions: Interfaces and contracts
  • Domain: Domain models and business logic
  • Application: Application services and configuration
  • Infrastructure: Repository implementations (OpenAI)
  • LLM: Language model definitions

Complete Application Example

public class AiService
{
    private readonly IAiClient _aiClient;

    public AiService(IAiClient aiClient)
    {
        _aiClient = aiClient;
    }

    public async Task<string> TranslateAsync(string text, string targetLanguage)
    {
        var prompt = new TranslatePrompt
        {
            Content = text,
            Language = targetLanguage,
            Culture  = $"{targetLanguage}-{targetLanguage.ToUpper()}"
        };

        var result = await _aiClient.GenerateAsync(prompt, new GPT4Turbo());
        return result.Value.TranslatedText;
    }

    public async Task<byte[]> GenerateImageAsync(string description)
    {
        var prompt = new ImagePrompt { Description = description };

        var result = await _aiClient.GenerateAsync(
            prompt,
            new GPTImage1
            {
                Quality = GPTImage1.QualityType.High,
                Size    = GPTImage1.SizeType.Square
            }
        );

        return result.Value.Data;
    }
}
Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.20 31 7/12/2025
1.0.19 73 7/11/2025
1.0.18 105 7/10/2025
1.0.17 101 7/10/2025
1.0.16 103 7/10/2025
1.0.15 103 7/10/2025
1.0.14 107 7/8/2025
1.0.13 109 7/8/2025
1.0.12 109 7/7/2025
1.0.11 65 7/4/2025
1.0.10 70 7/4/2025
1.0.9 80 7/4/2025
1.0.8 107 7/4/2025
1.0.7 110 7/4/2025
1.0.6 108 7/3/2025
1.0.5 110 7/3/2025
1.0.4 104 7/3/2025
1.0.3 107 7/3/2025
1.0.2 108 7/3/2025
1.0.1 112 7/3/2025
1.0.0 111 7/3/2025
0.0.9 121 6/3/2025
0.0.8 118 6/3/2025
0.0.7 120 5/20/2025
0.0.6 124 5/20/2025
0.0.5 122 5/20/2025
0.0.4 117 5/19/2025
0.0.3 118 5/19/2025
0.0.2 118 5/19/2025
0.0.1 114 5/2/2025