LightResults.Extensions.OpenAI 9.0.0-preview.1

Prefix Reserved
This is a prerelease version of LightResults.Extensions.OpenAI.
dotnet add package LightResults.Extensions.OpenAI --version 9.0.0-preview.1
                    
NuGet\Install-Package LightResults.Extensions.OpenAI -Version 9.0.0-preview.1
                    
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="LightResults.Extensions.OpenAI" Version="9.0.0-preview.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="LightResults.Extensions.OpenAI" Version="9.0.0-preview.1" />
                    
Directory.Packages.props
<PackageReference Include="LightResults.Extensions.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 LightResults.Extensions.OpenAI --version 9.0.0-preview.1
                    
#r "nuget: LightResults.Extensions.OpenAI, 9.0.0-preview.1"
                    
#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 LightResults.Extensions.OpenAI@9.0.0-preview.1
                    
#: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=LightResults.Extensions.OpenAI&version=9.0.0-preview.1&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=LightResults.Extensions.OpenAI&version=9.0.0-preview.1&prerelease
                    
Install as a Cake Tool

Banner

LightResults Extensions

Extensions for LightResults, an extremely light and modern Operation Result Pattern library for .NET.

main

OpenAI

Provides comprehensive OpenAI integration with the Result pattern, offering extension methods that return Result<T> instead of throwing exceptions.

nuget downloads

Documentation

Make sure to read the docs for the full API.

Try overloads

This package provides a Try extension method version of all public methods for all OpenAI clients, wrapping operations in a try { } catch { } block. If an exception occurs, a failed result will be returned and the Exception will be added to the result as metadata.

Supported Clients:

  • Chat Completions - ChatClient extensions for chat completions and streaming
  • Embeddings - EmbeddingClient extensions for text embeddings
  • Image Generation - ImageClient extensions for image generation and editing
  • Audio Processing - AudioClient extensions for speech-to-text and text-to-speech
  • Assistants - AssistantClient extensions for AI assistants and conversations
  • Vector Stores - VectorStoreClient extensions for vector storage and retrieval
  • File Operations - OpenAIFileClient extensions for file uploads and management
  • Batch Processing - BatchClient extensions for batch operations
  • Fine-tuning - FineTuningClient extensions for model fine-tuning
  • Evaluations - EvaluationClient extensions for model evaluations

Usage Examples

Chat Completions
using OpenAI.Chat;
using LightResults.Extensions.OpenAI;

var client = new ChatClient("gpt-4o", Environment.GetEnvironmentVariable("OPENAI_API_KEY"));

// Simple chat completion
var result = await client.TryCompleteChatAsync("What is the meaning of life?");
if (result.IsSuccess(out var completion))
{
    Console.WriteLine($"Response: {completion.Content[0].Text}");
}
else if (result.IsFailure(out var error))
{
    Console.WriteLine($"Error: {error.Message}");
}

// Chat with multiple messages
var messages = new List<ChatMessage>
{
    new SystemChatMessage("You are a helpful assistant."),
    new UserChatMessage("Explain quantum computing in simple terms.")
};

var chatResult = await client.TryCompleteChatAsync(messages);
if (chatResult.IsSuccess(out var chatCompletion))
{
    Console.WriteLine($"Response: {chatCompletion.Content[0].Text}");
}
Embeddings
using OpenAI.Embeddings;
using LightResults.Extensions.OpenAI;

var embeddingClient = new EmbeddingClient("text-embedding-3-small", apiKey);

// Generate single embedding
var embeddingResult = await embeddingClient.TryGenerateEmbeddingAsync("Hello, world!");
if (embeddingResult.IsSuccess(out var embedding))
{
    var vector = embedding.ToFloats();
    Console.WriteLine($"Generated embedding with {vector.Length} dimensions");
}

// Generate multiple embeddings
var texts = new[] { "First text", "Second text", "Third text" };
var embeddingsResult = await embeddingClient.TryGenerateEmbeddingsAsync(texts);
if (embeddingsResult.IsSuccess(out var embeddings))
{
    Console.WriteLine($"Generated {embeddings.Count} embeddings");
}
Image Generation
using OpenAI.Images;
using LightResults.Extensions.OpenAI;

var imageClient = new ImageClient("dall-e-3", apiKey);

// Generate image
var imageResult = await imageClient.TryGenerateImageAsync(
    "A serene landscape with mountains and a lake at sunset");

if (imageResult.IsSuccess(out var image))
{
    Console.WriteLine($"Generated image URL: {image.ImageUri}");
}

// Generate multiple images
var imagesResult = await imageClient.TryGenerateImagesAsync(
    "A cute cat wearing a hat", imageCount: 2);

if (imagesResult.IsSuccess(out var images))
{
    foreach (var generatedImage in images)
    {
        Console.WriteLine($"Image URL: {generatedImage.ImageUri}");
    }
}
Audio Processing
using OpenAI.Audio;
using LightResults.Extensions.OpenAI;

var audioClient = new AudioClient("whisper-1", apiKey);

// Transcribe audio
var audioData = File.ReadAllBytes("audio.mp3");
var transcriptionResult = await audioClient.TryTranscribeAudioAsync(audioData, "audio.mp3");
if (transcriptionResult.IsSuccess(out var transcription))
{
    Console.WriteLine($"Transcription: {transcription.Text}");
}

// Generate speech
var speechClient = new AudioClient("tts-1", apiKey);
var speechResult = await speechClient.TryGenerateSpeechAsync("Hello, world!", GeneratedSpeechVoice.Alloy);
if (speechResult.IsSuccess(out var speechData))
{
    await File.WriteAllBytesAsync("output.mp3", speechData.ToArray());
}
File Operations
using OpenAI.Files;
using LightResults.Extensions.OpenAI;

var fileClient = new OpenAIFileClient(apiKey);

// Upload file
var fileData = File.ReadAllBytes("document.txt");
var uploadResult = await fileClient.TryUploadFileAsync(fileData, "document.txt", FileUploadPurpose.Assistants);
if (uploadResult.IsSuccess(out var uploadedFile))
{
    Console.WriteLine($"Uploaded file ID: {uploadedFile.Id}");
}

// List files
var filesResult = await fileClient.TryGetFilesAsync();
if (filesResult.IsSuccess(out var files))
{
    foreach (var file in files)
    {
        Console.WriteLine($"File: {file.Filename} (ID: {file.Id})");
    }
}

Error Handling

All extension methods wrap operations in a try { } catch { } block and return Result<T> types for safe error handling:

var result = await client.TryCompleteChatAsync("Hello!");
if (result.IsFailure(out var error))
{
    var ex = error.Exception;
    
    // Handle specific exception types
    if (ex is ClientResultException clientException)
    {
        Console.WriteLine($"API Error: {clientException.Message}");
    }
    else if (ex is TaskCanceledException)
    {
        Console.WriteLine("Request was cancelled");
    }
    else
    {
        Console.WriteLine($"Unexpected error: {ex?.Message ?? error.Message}");
    }
}

Getting the Exception

var result = await client.TryCompleteChatAsync("Hello!");
if (result.IsFailure(out var error))
{
    var ex = error.Exception;
    // Do something with the base exception type or...
    
    if (ex is ClientResultException clientResultException)
    {
        // Handle OpenAI-specific errors
        Console.WriteLine($"OpenAI API Error: {clientResultException.Message}");
    }
}
Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  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 was computed.  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
9.0.0-preview.1 364 7/21/2025