RepletoryLib.Ai.OpenAi 1.0.0

dotnet add package RepletoryLib.Ai.OpenAi --version 1.0.0
                    
NuGet\Install-Package RepletoryLib.Ai.OpenAi -Version 1.0.0
                    
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="RepletoryLib.Ai.OpenAi" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="RepletoryLib.Ai.OpenAi" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="RepletoryLib.Ai.OpenAi" />
                    
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 RepletoryLib.Ai.OpenAi --version 1.0.0
                    
#r "nuget: RepletoryLib.Ai.OpenAi, 1.0.0"
                    
#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.
#:package RepletoryLib.Ai.OpenAi@1.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=RepletoryLib.Ai.OpenAi&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=RepletoryLib.Ai.OpenAi&version=1.0.0
                    
Install as a Cake Tool

RepletoryLib.Ai.OpenAi

OpenAI provider implementation for RepletoryLib AI services (GPT, DALL-E, Whisper, TTS, Moderation).

Part of the RepletoryLib ecosystem -- standalone, reusable .NET 10 libraries with zero business logic.

NuGet .NET 10 License: MIT


Overview

RepletoryLib.Ai.OpenAi implements all five AI service interfaces from RepletoryLib.Ai.Abstractions using direct HTTP calls to the OpenAI API. Each service uses a named HttpClient with Polly resilience policies (retry with Retry-After support, circuit breaker) and returns Result<T> for consistent error handling.

Key Features

  • Chat Completions -- GPT-4o, GPT-4, GPT-3.5 with streaming, tool calling, and structured output
  • Embeddings -- text-embedding-3-small/large with batch support and configurable dimensions
  • Image Generation -- DALL-E 3/2 with size, quality, and count options
  • Audio Transcription -- Whisper speech-to-text with language detection
  • Text-to-Speech -- TTS-1/TTS-1-HD with multiple voices and audio formats
  • Content Moderation -- omni-moderation-latest with category flag mapping
  • Polly Resilience -- Retry with Retry-After header support, circuit breaker per service
  • Result<T> Wrapping -- All responses wrapped in Result<T> with HTTP status code mapping

Installation

dotnet add package RepletoryLib.Ai.OpenAi

Dependencies

Package Type
RepletoryLib.Ai.Abstractions RepletoryLib
Microsoft.Extensions.Http.Polly NuGet
Microsoft.Extensions.Http NuGet
Microsoft.Extensions.Options.ConfigurationExtensions NuGet

Quick Start

using RepletoryLib.Ai.OpenAi;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRepletoryOpenAi(builder.Configuration);
{
  "Ai": {
    "OpenAi": {
      "ApiKey": "sk-...",
      "DefaultChatModel": "gpt-4o",
      "DefaultEmbeddingModel": "text-embedding-3-small",
      "TimeoutSeconds": 120,
      "RetryCount": 3
    }
  }
}

Configuration

OpenAiOptions

Property Type Default Description
ApiKey string "" OpenAI API key
BaseUrl string https://api.openai.com/v1 API base URL
DefaultChatModel string gpt-4o Default chat model
DefaultEmbeddingModel string text-embedding-3-small Default embedding model
DefaultImageModel string dall-e-3 Default image model
DefaultAudioModel string whisper-1 Default transcription model
DefaultTtsModel string tts-1 Default TTS model
DefaultModerationModel string omni-moderation-latest Default moderation model
MaxTokens int 4096 Default max output tokens
TimeoutSeconds int 120 Request timeout
RetryCount int 3 Retry attempts with exponential backoff
CircuitBreakerThreshold int 5 Failures before circuit opens
CircuitBreakerDurationSeconds int 30 Duration circuit stays open
Organization string? null Optional OpenAI organization ID

Usage Examples

Chat Completion

using RepletoryLib.Ai.Abstractions.Interfaces;
using RepletoryLib.Ai.Abstractions.Models.Chat;

public class ChatService
{
    private readonly IChatCompletionService _chat;

    public ChatService(IChatCompletionService chat) => _chat = chat;

    public async Task<string?> AskAsync(string question)
    {
        var request = new ChatRequest
        {
            Messages = [ChatMessage.User(question)]
        };

        var result = await _chat.CompleteAsync(request);
        return result.IsSuccess ? result.Data?.Content : null;
    }
}

Streaming

await foreach (var chunk in _chat.StreamAsync(request))
{
    if (chunk.ContentDelta is not null)
        Console.Write(chunk.ContentDelta);

    if (chunk.IsFinal)
        Console.WriteLine($"\nTokens: {chunk.FinalUsage?.TotalTokens}");
}

Embeddings

var result = await _embedding.EmbedSingleAsync("Hello, world!");
if (result.IsSuccess)
    Console.WriteLine($"Dimensions: {result.Data!.Length}");

Image Generation

var result = await _image.GenerateAsync(new ImageGenerationRequest
{
    Prompt = "A cat wearing a top hat",
    Size = ImageSize.Square1024,
    Quality = ImageQuality.Hd
});

Registered Services

Interface Implementation
IChatCompletionService OpenAiChatService
IEmbeddingService OpenAiEmbeddingService
IImageGenerationService OpenAiImageService
IAudioService OpenAiAudioService
IModerationService OpenAiModerationService
IAiService CompositeAiService

All services are registered with TryAddScoped, allowing them to be overridden by registering your own implementation first.


Integration with Other RepletoryLib Packages

Package Relationship
RepletoryLib.Ai.Abstractions Provider-agnostic interfaces and models
RepletoryLib.Common Result<T> for response wrapping
RepletoryLib.Tracing HTTP calls instrumented by OpenTelemetry
RepletoryLib.Caching.Abstractions Optional response caching

Troubleshooting

Issue Solution
401 Unauthorized Verify ApiKey is set correctly in configuration.
429 Rate Limited Retry policy handles this automatically. Increase RetryCount or add delays.
Timeout errors Increase TimeoutSeconds. Streaming requests may need longer timeouts.
Circuit breaker open Wait for CircuitBreakerDurationSeconds or restart the application.

License

This project is licensed under the MIT License.

Copyright (c) 2024-2026 Repletory.


For complete documentation, infrastructure setup, and configuration reference, see the RepletoryLib main repository.

Product Compatible and additional computed target framework versions.
.NET 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.0 127 3/2/2026