Skip to content

Commit 5d15119

Browse files
committed
Updated docs.
1 parent 2eac16b commit 5d15119

File tree

1 file changed

+6
-165
lines changed

1 file changed

+6
-165
lines changed

docfx/docs/openai.md

Lines changed: 6 additions & 165 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,16 @@
11
# OpenAI
22

3-
[![Banner](https://raw.githubusercontent.com/jscarle/LightResults/main/Banner.png)](https://github.com/jscarle/LightResults)
43

5-
The `LightResults.Extensions.OpenAI` package provides seamless integration between LightResults and OpenAI services, offering extension methods that return `Result<T>` instead of throwing exceptions.
4+
Provides a extension methods that wrap all OpenAI operations using LightResults.
65

7-
## Installation
8-
9-
```bash
10-
dotnet add package LightResults.Extensions.OpenAI
11-
```
12-
13-
## Overview
14-
15-
This extension wraps common OpenAI operations with the Result pattern, providing a more functional approach to error handling. Instead of dealing with exceptions, you get explicit success/failure results that you can pattern match on or chain with other operations.
16-
17-
## Features
18-
19-
- **Chat Completions**: Create chat completions with proper error handling
20-
- **Embeddings**: Generate text embeddings with Result pattern
21-
- **Image Generation**: Generate images using DALL-E with safe error handling
22-
- **Async Support**: Full async/await support for all operations
23-
- **Cancellation Support**: CancellationToken support for long-running operations
24-
25-
## Usage
26-
27-
### Basic Setup
6+
### Chat Completions example
287

298
```csharp
309
using OpenAI.Chat;
3110
using LightResults.Extensions.OpenAI;
3211

33-
var client = new ChatClient("gpt-4o", Environment.GetEnvironmentVariable("OPENAI_API_KEY"));
34-
```
35-
36-
### Chat Completions
12+
var client = new ChatClient("gpt-4.1", apiKey);
3713

38-
```csharp
3914
// Simple chat completion
4015
var result = client.TryCompleteChat("What is the meaning of life?");
4116
if (result.IsSuccess(out var completion))
@@ -71,39 +46,13 @@ if (chatResult.IsSuccess(out var chatCompletion))
7146
Console.WriteLine($"Response: {chatCompletion.Content[0].Text}");
7247
}
7348
```
74-
75-
### Embeddings
76-
77-
```csharp
78-
using OpenAI.Embeddings;
79-
using LightResults.Extensions.OpenAI;
80-
81-
var embeddingClient = new EmbeddingClient("text-embedding-3-small", apiKey);
82-
83-
// Generate single embedding
84-
var embeddingResult = await embeddingClient.TryGenerateEmbeddingAsync("Hello, world!");
85-
if (embeddingResult.IsSuccess(out var embedding))
86-
{
87-
var vector = embedding.ToFloats();
88-
Console.WriteLine($"Generated embedding with {vector.Length} dimensions");
89-
}
90-
91-
// Generate multiple embeddings
92-
var texts = new[] { "First text", "Second text", "Third text" };
93-
var embeddingsResult = await embeddingClient.TryGenerateEmbeddingsAsync(texts);
94-
if (embeddingsResult.IsSuccess(out var embeddings))
95-
{
96-
Console.WriteLine($"Generated {embeddings.Count} embeddings");
97-
}
98-
```
99-
100-
### Image Generation
49+
### Image Generation example
10150

10251
```csharp
10352
using OpenAI.Images;
10453
using LightResults.Extensions.OpenAI;
10554

106-
var imageClient = new ImageClient("dall-e-3", apiKey);
55+
var imageClient = new ImageClient("gpt-4.1-image", apiKey);
10756

10857
// Generate single image
10958
var imageResult = await imageClient.TryGenerateImageAsync(
@@ -116,7 +65,7 @@ if (imageResult.IsSuccess(out var image))
11665

11766
// Generate multiple images
11867
var imagesResult = await imageClient.TryGenerateImagesAsync(
119-
"A cute cat wearing a hat",
68+
"A cute cat wearing a hat",
12069
imageCount: 2);
12170

12271
if (imagesResult.IsSuccess(out var images))
@@ -127,111 +76,3 @@ if (imagesResult.IsSuccess(out var images))
12776
}
12877
}
12978
```
130-
131-
### Error Handling Patterns
132-
133-
```csharp
134-
// Pattern matching with method calls
135-
var result = await client.TryCompleteChatAsync("Hello!");
136-
if (result.IsSuccess(out var completion))
137-
{
138-
Console.WriteLine($"Success: {completion.Content[0].Text}");
139-
}
140-
else if (result.IsFailure(out var error))
141-
{
142-
Console.WriteLine($"Failed: {error.Message}");
143-
}
144-
145-
// Alternative pattern using separate checks
146-
var chatResult = await client.TryCompleteChatAsync("Generate a creative story");
147-
if (chatResult.IsSuccess())
148-
{
149-
// Get the value safely
150-
if (chatResult.IsSuccess(out var story))
151-
{
152-
Console.WriteLine($"Generated story: {story.Content[0].Text}");
153-
}
154-
}
155-
else
156-
{
157-
// Handle the error
158-
if (chatResult.IsFailure(out var error))
159-
{
160-
Console.WriteLine($"Story generation failed: {error.Message}");
161-
}
162-
}
163-
```
164-
165-
### Advanced Options
166-
167-
```csharp
168-
// Chat completion with options
169-
var options = new ChatCompletionOptions
170-
{
171-
Temperature = 0.7f,
172-
MaxTokens = 150,
173-
ResponseFormat = ChatResponseFormat.Text
174-
};
175-
176-
var result = await client.TryCompleteChatAsync("Be creative!", options);
177-
178-
// Embedding with custom dimensions
179-
var embeddingOptions = new EmbeddingGenerationOptions
180-
{
181-
Dimensions = 512
182-
};
183-
184-
var embeddingResult = await embeddingClient.TryGenerateEmbeddingAsync(
185-
"Sample text", embeddingOptions);
186-
187-
// Image generation with custom settings
188-
var imageOptions = new ImageGenerationOptions
189-
{
190-
Quality = GeneratedImageQuality.High,
191-
Size = GeneratedImageSize.W1024xH1024,
192-
Style = GeneratedImageStyle.Vivid
193-
};
194-
195-
var imageResult = await imageClient.TryGenerateImageAsync(
196-
"A futuristic cityscape", imageOptions);
197-
```
198-
199-
## Best Practices
200-
201-
1. **Always check results**: Use `IsSuccess()` and `IsFailure()` methods to verify operation outcomes
202-
2. **Use safe value access**: Use `IsSuccess(out var value)` to safely retrieve success values
203-
3. **Use safe error access**: Use `IsFailure(out var error)` to safely retrieve error information
204-
4. **Use async methods**: For better performance and responsiveness
205-
5. **Handle cancellation**: Pass CancellationTokens for long-running operations
206-
6. **Configure timeouts**: Set appropriate timeouts for your use case
207-
7. **Log errors**: Capture and log errors for debugging and monitoring
208-
209-
## Configuration
210-
211-
You can configure the OpenAI client with custom settings:
212-
213-
```csharp
214-
var client = new ChatClient(
215-
model: "gpt-4o",
216-
credential: new ApiKeyCredential(apiKey),
217-
options: new OpenAIClientOptions()
218-
{
219-
Endpoint = new Uri("https://your-custom-endpoint.com"),
220-
RetryPolicy = new RetryPolicy(maxRetries: 3)
221-
}
222-
);
223-
```
224-
225-
## Error Types
226-
227-
The extension captures various types of errors and wraps them in Result objects:
228-
229-
- **Authentication errors**: Invalid API key or permissions
230-
- **Rate limiting**: Too many requests
231-
- **Network errors**: Connection timeouts or failures
232-
- **API errors**: Invalid parameters or service errors
233-
- **Model errors**: Model not available or context length exceeded
234-
235-
## Thread Safety
236-
237-
All extension methods are thread-safe and can be used concurrently from multiple threads.

0 commit comments

Comments
 (0)