Skip to content

Commit

Permalink
Refactor and rename types and properties for consistency and clarity (#…
Browse files Browse the repository at this point in the history
…225)

### Summary of Changes

This PR renames the following types and properties for consistency and clarity:

- **Types:**
  - `OpenAIFileInfo` → `OpenAIFile`
  - `OpenAIFileInfoCollection` → `OpenAIFileCollection`
  - `OpenAIModelInfo` → `OpenAIModel`
  - `OpenAIModelInfoCollection` → `OpenAIModelCollection`
  - `Embedding` → `OpenAIEmbedding`
  - `EmbeddingCollection` → `OpenAIEmbeddingCollection`

- **Properties and Methods:**
  - `ImageUrl` → `ImageUri` and method `FromImageUrl` → `FromImageUri` in `MessageContent`
  - `ParallelToolCallsEnabled` → `AllowParallelToolCalls` in `RunCreationOptions`, `ThreadRun`, and `ChatCompletionOptions`
  - `PromptTokens` → `InputTokenCount`, `CompletionTokens` → `OutputTokenCount`, and `TotalTokens` → `TotalTokenCount` in `RunTokenUsage`
  - `InputTokens` → `InputTokenCount` and `TotalTokens` → `TotalTokenCount` in `EmbeddingTokenUsage`

This PR also refactors the `ModerationResult` type to consolidate category-specific flags and scores into individual `ModerationCategory` properties, each containing `Flagged` and `Score` properties:

```csharp
public class ModerationResult {
    public bool Flagged { get; }
    public ModerationCategory Harassment { get; }
    public ModerationCategory HarassmentThreatening { get; }
    public ModerationCategory Hate { get; }
    public ModerationCategory HateThreatening { get; }
    public ModerationCategory SelfHarm { get; }
    public ModerationCategory SelfHarmInstructions { get; }
    public ModerationCategory SelfHarmIntent { get; }
    public ModerationCategory Sexual { get; }
    public ModerationCategory SexualMinors { get; }
    public ModerationCategory Violence { get; }
    public ModerationCategory ViolenceGraphic { get; }
}

public class ModerationCategory {
    public bool Flagged { get; }
    public float Score { get; }
}
```

Additionally, this PR includes smoke tests for the `ModerationResult` type.
  • Loading branch information
ShivangiReja authored Sep 25, 2024
1 parent 7a8bc8b commit 19ceae4
Show file tree
Hide file tree
Showing 101 changed files with 1,679 additions and 1,540 deletions.
19 changes: 19 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,24 @@
# Release History

## 2.0.0-beta.13 (Unreleased)

### Features Added

### Breaking Changes

- Refactored `ModerationResult` by merging `ModerationCategories` and `ModerationCategoryScores` into individual `ModerationCategory` properties, each with `Flagged` and `Score` properties. (commit_hash)
- Renamed type `OpenAIFileInfo` to `OpenAIFile` and `OpenAIFileInfoCollection` to `OpenAIFileCollection`. (commit_id)
- Renamed type `OpenAIModelInfo` to `OpenAIModel` and `OpenAIModelInfoCollection` to `OpenAIModelCollection`. (commit_id)
- Renamed type `Embedding` to `OpenAIEmbedding` and `EmbeddingCollection` to `OpenAIEmbeddingCollection`. (commit_id)
- Renamed property `ImageUrl` to `ImageUri` and method `FromImageUrl` to `FromImageUri` in `MessageContent`. (commit_id)
- Renamed property `ParallelToolCallsEnabled` to `AllowParallelToolCalls` in `RunCreationOptions`, `ThreadRun`, and `ChatCompletionOptions` types. (commit_id)
- Renamed property `PromptTokens` to `InputTokenCount`, `CompletionTokens` to `OutputTokenCount`, and `TotalTokens` to `TotalTokenCount` in `RunTokenUsage`. (commit_id)
- Renamed property `InputTokens` to `InputTokenCount` and `TotalTokens` to `TotalTokenCount` in `EmbeddingTokenUsage`. (commit_id)

### Bugs Fixed

### Other Changes

## 2.0.0-beta.12 (2024-09-20)

### Features Added
Expand Down
262 changes: 119 additions & 143 deletions api/OpenAI.netstandard2.0.cs

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions examples/Assistants/Example01_RetrievalAugmentedGeneration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public void Example01_RetrievalAugmentedGeneration()
}
""").ToStream();

OpenAIFileInfo salesFile = fileClient.UploadFile(
OpenAIFile salesFile = fileClient.UploadFile(
document,
"monthly_sales.json",
FileUploadPurpose.Assistants);
Expand Down Expand Up @@ -129,7 +129,7 @@ CollectionResult<ThreadMessage> messages
}
if (!string.IsNullOrEmpty(contentItem.ImageFileId))
{
OpenAIFileInfo imageInfo = fileClient.GetFile(contentItem.ImageFileId);
OpenAIFile imageInfo = fileClient.GetFile(contentItem.ImageFileId);
BinaryData imageBytes = fileClient.DownloadFile(contentItem.ImageFileId);
using FileStream stream = File.OpenWrite($"{imageInfo.Filename}.png");
imageBytes.ToStream().CopyTo(stream);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public async Task Example01_RetrievalAugmentedGenerationAsync()
}
""").ToStream();

OpenAIFileInfo salesFile = await fileClient.UploadFileAsync(
OpenAIFile salesFile = await fileClient.UploadFileAsync(
document,
"monthly_sales.json",
FileUploadPurpose.Assistants);
Expand Down Expand Up @@ -130,7 +130,7 @@ AsyncCollectionResult<ThreadMessage> messages
}
if (!string.IsNullOrEmpty(contentItem.ImageFileId))
{
OpenAIFileInfo imageInfo = await fileClient.GetFileAsync(contentItem.ImageFileId);
OpenAIFile imageInfo = await fileClient.GetFileAsync(contentItem.ImageFileId);
BinaryData imageBytes = await fileClient.DownloadFileAsync(contentItem.ImageFileId);
using FileStream stream = File.OpenWrite($"{imageInfo.Filename}.png");
imageBytes.ToStream().CopyTo(stream);
Expand Down
2 changes: 1 addition & 1 deletion examples/Assistants/Example04_AllTheTools.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ static string GetNameOfFamilyMember(string relation)

#region Upload a mock file for use with file search
FileClient fileClient = new(Environment.GetEnvironmentVariable("OPENAI_API_KEY"));
OpenAIFileInfo favoriteNumberFile = fileClient.UploadFile(
OpenAIFile favoriteNumberFile = fileClient.UploadFile(
BinaryData.FromString("""
This file contains the favorite numbers for individuals.
Expand Down
4 changes: 2 additions & 2 deletions examples/Assistants/Example05_AssistantsWithVision.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public void Example05_AssistantsWithVision()
FileClient fileClient = openAIClient.GetFileClient();
AssistantClient assistantClient = openAIClient.GetAssistantClient();

OpenAIFileInfo pictureOfAppleFile = fileClient.UploadFile(
OpenAIFile pictureOfAppleFile = fileClient.UploadFile(
"picture-of-apple.jpg",
FileUploadPurpose.Vision);
Uri linkToPictureOfOrange = new("https://platform.openai.com/fictitious-files/picture-of-orange.png");
Expand All @@ -38,7 +38,7 @@ public void Example05_AssistantsWithVision()
[
"Hello, assistant! Please compare these two images for me:",
MessageContent.FromImageFileId(pictureOfAppleFile.Id),
MessageContent.FromImageUrl(linkToPictureOfOrange),
MessageContent.FromImageUri(linkToPictureOfOrange),
]),
}
});
Expand Down
4 changes: 2 additions & 2 deletions examples/Assistants/Example05_AssistantsWithVisionAsync.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public async Task Example05_AssistantsWithVisionAsync()
FileClient fileClient = openAIClient.GetFileClient();
AssistantClient assistantClient = openAIClient.GetAssistantClient();

OpenAIFileInfo pictureOfAppleFile = await fileClient.UploadFileAsync(
OpenAIFile pictureOfAppleFile = await fileClient.UploadFileAsync(
"picture-of-apple.jpg",
FileUploadPurpose.Vision);
Uri linkToPictureOfOrange = new("https://platform.openai.com/fictitious-files/picture-of-orange.png");
Expand All @@ -39,7 +39,7 @@ public async Task Example05_AssistantsWithVisionAsync()
[
"Hello, assistant! Please compare these two images for me:",
MessageContent.FromImageFileId(pictureOfAppleFile.Id),
MessageContent.FromImageUrl(linkToPictureOfOrange),
MessageContent.FromImageUri(linkToPictureOfOrange),
]),
}
});
Expand Down
2 changes: 1 addition & 1 deletion examples/Embeddings/Example01_SimpleEmbedding.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public void Example01_SimpleEmbedding()
+ " and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist"
+ " attractions. We highly recommend this hotel.";

Embedding embedding = client.GenerateEmbedding(description);
OpenAIEmbedding embedding = client.GenerateEmbedding(description);
ReadOnlyMemory<float> vector = embedding.ToFloats();

Console.WriteLine($"Dimension: {vector.Length}");
Expand Down
2 changes: 1 addition & 1 deletion examples/Embeddings/Example01_SimpleEmbeddingAsync.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public async Task Example01_SimpleEmbeddingAsync()
+ " and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist"
+ " attractions. We highly recommend this hotel.";

Embedding embedding = await client.GenerateEmbeddingAsync(description);
OpenAIEmbedding embedding = await client.GenerateEmbeddingAsync(description);
ReadOnlyMemory<float> vector = embedding.ToFloats();

Console.WriteLine($"Dimension: {vector.Length}");
Expand Down
2 changes: 1 addition & 1 deletion examples/Embeddings/Example02_EmbeddingWithOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public void Example02_EmbeddingWithOptions()

EmbeddingGenerationOptions options = new() { Dimensions = 512 };

Embedding embedding = client.GenerateEmbedding(description, options);
OpenAIEmbedding embedding = client.GenerateEmbedding(description, options);
ReadOnlyMemory<float> vector = embedding.ToFloats();

Console.WriteLine($"Dimension: {vector.Length}");
Expand Down
2 changes: 1 addition & 1 deletion examples/Embeddings/Example02_EmbeddingWithOptionsAsync.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public async Task Example02_EmbeddingWithOptionsAsync()

EmbeddingGenerationOptions options = new() { Dimensions = 512 };

Embedding embedding = await client.GenerateEmbeddingAsync(description, options);
OpenAIEmbedding embedding = await client.GenerateEmbeddingAsync(description, options);
ReadOnlyMemory<float> vector = embedding.ToFloats();

Console.WriteLine($"Dimension: {vector.Length}");
Expand Down
4 changes: 2 additions & 2 deletions examples/Embeddings/Example03_MultipleEmbeddings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ public void Example03_MultipleEmbeddings()
+ " attractions. We highly recommend this hotel.";
List<string> inputs = [category, description];

EmbeddingCollection collection = client.GenerateEmbeddings(inputs);
OpenAIEmbeddingCollection collection = client.GenerateEmbeddings(inputs);

foreach (Embedding embedding in collection)
foreach (OpenAIEmbedding embedding in collection)
{
ReadOnlyMemory<float> vector = embedding.ToFloats();

Expand Down
4 changes: 2 additions & 2 deletions examples/Embeddings/Example03_MultipleEmbeddingsAsync.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ public async Task Example03_MultipleEmbeddingsAsync()
+ " attractions. We highly recommend this hotel.";
List<string> inputs = [category, description];

EmbeddingCollection collection = await client.GenerateEmbeddingsAsync(inputs);
OpenAIEmbeddingCollection collection = await client.GenerateEmbeddingsAsync(inputs);

foreach (Embedding embedding in collection)
foreach (OpenAIEmbedding embedding in collection)
{
ReadOnlyMemory<float> vector = embedding.ToFloats();

Expand Down
2 changes: 1 addition & 1 deletion src/Custom/Assistants/AssistantClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1267,7 +1267,7 @@ private static BinaryContent CreateThreadAndRunProtocolContent(
runOptions.MaxCompletionTokens,
runOptions.TruncationStrategy,
runOptions.ToolConstraint,
runOptions.ParallelToolCallsEnabled,
runOptions.AllowParallelToolCalls,
runOptions.ResponseFormat,
serializedAdditionalRawData: null);
return internalRequest.ToBinaryContent();
Expand Down
4 changes: 0 additions & 4 deletions src/Custom/Assistants/GeneratorStubs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,6 @@ public partial class MessageFailureDetails { }
[CodeGenModel("MessageObjectIncompleteDetailsReason")]
public readonly partial struct MessageFailureReason { }

[Experimental("OPENAI001")]
[CodeGenModel("RunCompletionUsage")]
public partial class RunTokenUsage { }

[Experimental("OPENAI001")]
[CodeGenModel("RunObjectLastError")]
public partial class RunError { }
Expand Down
4 changes: 2 additions & 2 deletions src/Custom/Assistants/MessageContent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public static MessageContent FromImageFileId(
/// <param name="imageUri"></param>
/// <param name="detail"></param>
/// <returns></returns>
public static MessageContent FromImageUrl(Uri imageUri, MessageImageDetail? detail = null)
public static MessageContent FromImageUri(Uri imageUri, MessageImageDetail? detail = null)
=> new InternalMessageImageUrlContent(imageUri, detail);

/// <summary>
Expand All @@ -38,7 +38,7 @@ public static MessageContent FromText(string text)
=> new InternalRequestMessageTextContent(text);

/// <inheritdoc cref="InternalMessageImageUrlContent.InternalUrl"/>
public Uri ImageUrl => AsInternalImageUrl?.InternalUrl;
public Uri ImageUri => AsInternalImageUrl?.InternalUrl;
/// <inheritdoc cref="InternalMessageImageFileContent.InternalFileId"/>
public string ImageFileId => AsInternalImageFile?.InternalFileId;
/// <inheritdoc cref="InternalMessageImageFileContent.InternalDetail"/>
Expand Down
2 changes: 1 addition & 1 deletion src/Custom/Assistants/RunCreationOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ private set
/// Assumed <c>true</c> if not otherwise specified.
/// </remarks>
[CodeGenMember("ParallelToolCalls")]
public bool? ParallelToolCallsEnabled { get; set; }
public bool? AllowParallelToolCalls { get; set; }

/// <summary>
/// A run-specific collection of tool definitions that will override the assistant-level defaults. If not provided,
Expand Down
23 changes: 23 additions & 0 deletions src/Custom/Assistants/RunTokenUsage.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;

namespace OpenAI.Assistants
{
[Experimental("OPENAI001")]
[CodeGenModel("RunCompletionUsage")]
public partial class RunTokenUsage
{
// CUSTOM: Renamed.
[CodeGenMember("CompletionTokens")]
public int OutputTokenCount { get; }

// CUSTOM: Renamed.
[CodeGenMember("PromptTokens")]
public int InputTokenCount { get; }

// CUSTOM: Renamed.
[CodeGenMember("TotalTokens")]
public int TotalTokenCount { get; }
}
}
6 changes: 3 additions & 3 deletions src/Custom/Assistants/ThreadRun.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public partial class ThreadRun
internal readonly InternalRunRequiredAction _internalRequiredAction;

// CUSTOM: Removed null check for `toolConstraint` and `responseFormat`.
internal ThreadRun(string id, DateTimeOffset createdAt, string threadId, string assistantId, RunStatus status, InternalRunRequiredAction internalRequiredAction, RunError lastError, DateTimeOffset? expiresAt, DateTimeOffset? startedAt, DateTimeOffset? cancelledAt, DateTimeOffset? failedAt, DateTimeOffset? completedAt, RunIncompleteDetails incompleteDetails, string model, string instructions, IEnumerable<ToolDefinition> tools, IReadOnlyDictionary<string, string> metadata, RunTokenUsage usage, int? maxPromptTokens, int? maxCompletionTokens, RunTruncationStrategy truncationStrategy, ToolConstraint toolConstraint, bool? parallelToolCallsEnabled, AssistantResponseFormat responseFormat)
internal ThreadRun(string id, DateTimeOffset createdAt, string threadId, string assistantId, RunStatus status, InternalRunRequiredAction internalRequiredAction, RunError lastError, DateTimeOffset? expiresAt, DateTimeOffset? startedAt, DateTimeOffset? cancelledAt, DateTimeOffset? failedAt, DateTimeOffset? completedAt, RunIncompleteDetails incompleteDetails, string model, string instructions, IEnumerable<ToolDefinition> tools, IReadOnlyDictionary<string, string> metadata, RunTokenUsage usage, int? maxPromptTokens, int? maxCompletionTokens, RunTruncationStrategy truncationStrategy, ToolConstraint toolConstraint, bool? allowParallelToolCalls, AssistantResponseFormat responseFormat)
{
Argument.AssertNotNull(id, nameof(id));
Argument.AssertNotNull(threadId, nameof(threadId));
Expand Down Expand Up @@ -54,7 +54,7 @@ internal ThreadRun(string id, DateTimeOffset createdAt, string threadId, string
MaxCompletionTokens = maxCompletionTokens;
TruncationStrategy = truncationStrategy;
ToolConstraint = toolConstraint;
ParallelToolCallsEnabled = parallelToolCallsEnabled;
AllowParallelToolCalls = allowParallelToolCalls;
ResponseFormat = responseFormat;
}

Expand Down Expand Up @@ -93,6 +93,6 @@ internal ThreadRun(string id, DateTimeOffset createdAt, string threadId, string
/// Assumed <c>true</c> if not otherwise specified.
/// </remarks>
[CodeGenMember("ParallelToolCalls")]
public bool? ParallelToolCallsEnabled { get; }
public bool? AllowParallelToolCalls { get; }

}
2 changes: 1 addition & 1 deletion src/Custom/Assistants/VectorStoreCreationHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public VectorStoreCreationHelper(IEnumerable<string> fileIds)
Metadata = new ChangeTrackingDictionary<string, string>();
}

public VectorStoreCreationHelper(IEnumerable<OpenAIFileInfo> files)
public VectorStoreCreationHelper(IEnumerable<OpenAIFile> files)
: this(files?.Select(file => file.Id) ?? [])
{ }
}
2 changes: 1 addition & 1 deletion src/Custom/Chat/ChatCompletionOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ public ChatCompletionOptions()
/// Assumed <c>true</c> if not otherwise specified.
/// </remarks>
[CodeGenMember("ParallelToolCalls")]
public bool? ParallelToolCallsEnabled { get; set; }
public bool? AllowParallelToolCalls { get; set; }

/// <summary>
/// An object specifying the format that the model must output.
Expand Down
Loading

0 comments on commit 19ceae4

Please sign in to comment.