From 9ab4487a4c362e75b28032ae0626c93a3bd4b77f Mon Sep 17 00:00:00 2001 From: Tolga Kayhan Date: Thu, 13 Jun 2024 16:01:43 +0100 Subject: [PATCH 1/3] code cleanup --- .../ExtensionsAndHelpers/ConsoleExtensions.cs | 3 +- OpenAI.Playground/Program.cs | 4 +- .../AssistantHelpers/AssistantTestHelper.cs | 7 +- .../AssistantHelpers/AssistantTestHelper3.cs | 42 +++++----- .../AssistantHelpers/RunTestHelper.cs | 18 ++--- .../AssistantHelpers/RunTestHelper2.cs | 39 +++++----- .../AssistantHelpers/VectorTestHelper.cs | 4 +- .../TestHelpers/AudioTestHelper.cs | 19 +++-- .../TestHelpers/BatchTestHelper.cs | 11 ++- .../TestHelpers/ChatCompletionTestHelper.cs | 78 +++++++++---------- .../TestHelpers/CompletionTestHelper.cs | 21 +++-- .../TestHelpers/EditTestHelper.cs | 5 +- .../TestHelpers/EmbeddingTestHelper.cs | 7 +- .../TestHelpers/FineTuningJobTestHelper.cs | 10 +-- .../TestHelpers/FineTuningTestHelper.cs | 5 +- .../TestHelpers/ImageTestHelper.cs | 13 ++-- .../TestHelpers/ModerationTestHelper.cs | 3 +- .../TestHelpers/ThreadTestHelper.cs | 4 +- .../Builders/FunctionDefinitionBuilder.cs | 9 +-- .../AzureOpenAiEndpointProvider.cs | 14 ++-- .../IOpenAiEndpointProvider.cs | 4 +- .../OpenAiEndpointProvider.cs | 5 +- OpenAI.SDK/Extensions/HttpclientExtensions.cs | 10 +-- OpenAI.SDK/Extensions/ModelExtension.cs | 2 +- .../Extensions/StreamHandleExtension.cs | 5 +- OpenAI.SDK/Interfaces/IAssistantService.cs | 7 +- OpenAI.SDK/Interfaces/IAudioService.cs | 4 +- OpenAI.SDK/Interfaces/IBatchService.cs | 1 - .../Interfaces/IChatCompletionService.cs | 7 +- .../Interfaces/IFineTuningJobService.cs | 7 +- OpenAI.SDK/Interfaces/IImageService.cs | 2 +- OpenAI.SDK/Interfaces/IModelService.cs | 4 +- OpenAI.SDK/Interfaces/IModerationService.cs | 2 +- OpenAI.SDK/Interfaces/IOpenAIService.cs | 9 ++- OpenAI.SDK/Interfaces/IRunService.cs | 30 +++---- OpenAI.SDK/Interfaces/IVectorStoreFiles.cs | 26 +++++-- OpenAI.SDK/Interfaces/IVectorStores.cs | 13 ++-- OpenAI.SDK/Managers/OpenAIAudioService.cs | 16 +--- OpenAI.SDK/Managers/OpenAIBatchService.cs | 6 +- OpenAI.SDK/Managers/OpenAIChatCompletions.cs | 7 +- OpenAI.SDK/Managers/OpenAIFile.cs | 18 ++--- OpenAI.SDK/Managers/OpenAIFineTuningJob.cs | 49 ++++++------ OpenAI.SDK/Managers/OpenAIMessageService.cs | 6 +- OpenAI.SDK/Managers/OpenAIRunService.cs | 25 +++--- OpenAI.SDK/Managers/OpenAIRunStepService.cs | 2 +- OpenAI.SDK/Managers/OpenAIService.cs | 10 +-- OpenAI.SDK/Managers/OpenAIThreadService.cs | 2 +- .../Managers/OpenAIVectorStoreService.cs | 26 ++++--- OpenAI.SDK/ObjectModels/Converters.cs | 4 +- OpenAI.SDK/ObjectModels/Models.cs | 65 +++++++++------- .../RequestModels/AssistantCreateRequest.cs | 2 +- .../RequestModels/AssistantModifyRequest.cs | 38 ++++----- .../RequestModels/AudioCreateSpeechRequest.cs | 14 ++-- .../ChatCompletionCreateRequest.cs | 38 +++++---- .../ObjectModels/RequestModels/ChatMessage.cs | 10 +-- .../RequestModels/CompletionCreateRequest.cs | 7 +- .../RequestModels/CreateModerationRequest.cs | 2 +- .../CreateThreadAndRunRequest.cs | 64 ++++++++------- .../CreateVectorStoreFileBatchRequest.cs | 3 +- .../CreateVectorStoreFileRequest.cs | 3 +- .../RequestModels/CreateVectorStoreRequest.cs | 11 ++- .../RequestModels/EditCreateRequest.cs | 3 +- .../RequestModels/EmbeddingCreateRequest.cs | 23 +++--- .../RequestModels/FineTuneCancelRequest.cs | 3 +- .../FineTuningJobListEventsRequest.cs | 47 ++++++----- .../RequestModels/ImageCreateRequest.cs | 16 ++-- .../RequestModels/MessageContent.cs | 38 ++++----- .../RequestModels/MessageCreateRequest.cs | 20 +++-- .../RequestModels/ModifyMessageRequest.cs | 4 +- .../RequestModels/RunModifyRequest.cs | 2 +- .../RequestModels/StreamOptions.cs | 7 +- .../SubmitToolOutputsToRunRequest.cs | 3 +- .../RequestModels/ToolChoiceFunction.cs | 32 ++++---- .../RequestModels/ToolDefinition.cs | 43 ++++++---- .../RequestModels/UpdateVectorStoreRequest.cs | 8 +- .../RequestModels/VisionImageUrl.cs | 35 +++++---- .../AudioCreateTranscriptionResponse.cs | 59 +++++++++----- .../ResponseModels/BaseResponse.cs | 37 ++++++--- .../BatchResponseModel/BatchResponse.cs | 3 +- .../ChatCompletionCreateResponse.cs | 19 +++-- .../CompletionCreateResponse.cs | 15 ++-- .../CreateModerationResponse.cs | 74 ++++++++++++------ .../ResponseModels/EditCreateResponse.cs | 12 ++- .../ResponseModels/EmbeddingCreateResponse.cs | 15 ++-- .../FileResponseModels/FileDeleteResponse.cs | 7 +- .../FileResponseModels/FileListResponse.cs | 3 +- .../FileResponseModels/FileUploadResponse.cs | 15 ++-- .../FineTuneListEventsResponse.cs | 3 +- .../FineTuneListResponse.cs | 3 +- .../FineTuneResponse.cs | 37 ++++++--- .../FineTuningJobListEventsResponse.cs | 9 +-- .../FineTuningJobListResponse.cs | 3 +- .../FineTuningJobResponse.cs | 2 +- .../ImageResponseModel/ImageCreateResponse.cs | 17 ++-- .../ResponseModels/MessageListResponse.cs | 5 +- .../ModelDeleteResponse.cs | 6 +- .../ModelResponseModels/ModelListResponse.cs | 3 +- .../ModelRetrieveResponse.cs | 46 +++++++---- .../ResponseModels/UsageResponse.cs | 6 +- .../VectorStoreResponseModels/ExpiresAfter.cs | 4 +- .../VectorStoreResponseModels/FileCounts.cs | 10 +-- .../VectorStoreFileBatchObject.cs | 12 +-- .../VectorStoreFileObject.cs | 16 ++-- .../VectorStoreFileResponse.cs | 4 - .../VectorStoreObjectResponse.cs | 25 +++--- .../SharedModels/AssistantResponse.cs | 14 ++-- .../SharedModels/ChatChoiceResponse.cs | 33 +++++--- .../SharedModels/ChoiceResponse.cs | 12 ++- .../SharedModels/EventResponse.cs | 20 +++-- .../ObjectModels/SharedModels/FileResponse.cs | 24 ++++-- .../SharedModels/FunctionParameters.cs | 16 ++-- .../SharedModels/HyperParametersResponse.cs | 3 +- .../SharedModels/IOpenAiModels.cs | 5 +- .../SharedModels/LogProbsResponse.cs | 21 +++-- .../SharedModels/MessageImageFile.cs | 4 - .../SharedModels/MessageResponse.cs | 23 +++--- .../ObjectModels/SharedModels/RunResponse.cs | 16 ++-- .../SharedImageRequestBaseModel.cs | 8 +- OpenAI.SDK/ObjectModels/StaticValueHelper.cs | 11 +-- OpenAI.SDK/ObjectModels/UploadFilePurposes.cs | 7 +- OpenAI.SDK/OpenAiOptions.cs | 11 +-- OpenAI.SDK/Tokenizer/GPT3/GPT3Settings.cs | 6 +- OpenAI.SDK/Tokenizer/GPT3/TokenizerGpt3.cs | 15 ++-- .../FunctionCallingHelperTests.cs | 25 ++---- .../OpenAI.Utilities.Tests.csproj | 50 ++++++------ OpenAI.Utilities/Embedding/EmbeddingTools.cs | 41 +++++----- .../Extensions/StringExtensions.cs | 2 +- .../FunctionCalling/FunctionCallingHelper.cs | 43 ++++------ .../FunctionDescriptionAttribute.cs | 2 +- .../InvalidFunctionCallException.cs | 2 +- .../ParameterDescriptionAttribute.cs | 2 +- OpenAI.UtilitiesPlayground/Program.cs | 3 +- .../TestHelpers/EmbeddingTestHelpers.cs | 28 +++---- .../TestHelpers/FunctionCallingTestHelpers.cs | 2 +- 134 files changed, 1122 insertions(+), 963 deletions(-) delete mode 100644 OpenAI.SDK/ObjectModels/ResponseModels/VectorStoreResponseModels/VectorStoreFileResponse.cs delete mode 100644 OpenAI.SDK/ObjectModels/SharedModels/MessageImageFile.cs diff --git a/OpenAI.Playground/ExtensionsAndHelpers/ConsoleExtensions.cs b/OpenAI.Playground/ExtensionsAndHelpers/ConsoleExtensions.cs index 7fd296b0..46a866aa 100644 --- a/OpenAI.Playground/ExtensionsAndHelpers/ConsoleExtensions.cs +++ b/OpenAI.Playground/ExtensionsAndHelpers/ConsoleExtensions.cs @@ -16,8 +16,9 @@ public static void WriteError(Error? error) { if (error == null) { - throw new Exception("Unknown Error"); + throw new("Unknown Error"); } + WriteLine($"{error.Code}: {error.Message}", ConsoleColor.Red); } } \ No newline at end of file diff --git a/OpenAI.Playground/Program.cs b/OpenAI.Playground/Program.cs index b705009c..2a9d0448 100644 --- a/OpenAI.Playground/Program.cs +++ b/OpenAI.Playground/Program.cs @@ -4,10 +4,8 @@ using OpenAI.Extensions; using OpenAI.Interfaces; using OpenAI.Playground.TestHelpers; -using OpenAI.Playground.TestHelpers.AssistantHelpers; -var builder = new ConfigurationBuilder().AddJsonFile("ApiSettings.json") - .AddUserSecrets(); +var builder = new ConfigurationBuilder().AddJsonFile("ApiSettings.json").AddUserSecrets(); IConfiguration configuration = builder.Build(); var serviceCollection = new ServiceCollection(); diff --git a/OpenAI.Playground/TestHelpers/AssistantHelpers/AssistantTestHelper.cs b/OpenAI.Playground/TestHelpers/AssistantHelpers/AssistantTestHelper.cs index 143fa864..8ebabe1b 100644 --- a/OpenAI.Playground/TestHelpers/AssistantHelpers/AssistantTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/AssistantHelpers/AssistantTestHelper.cs @@ -5,7 +5,8 @@ using OpenAI.Playground.ExtensionsAndHelpers; namespace OpenAI.Playground.TestHelpers.AssistantHelpers; -internal static partial class AssistantTestHelper + +internal static partial class AssistantTestHelper { internal static class BasicsTestHelper { @@ -128,9 +129,7 @@ public static async Task ModifyAssistantTask(IOpenAIService openAI) if (result.Successful) { - if (result is { Name: newName, Instructions: newInstructions } && result.Tools.First() - .Type == ToolDefinition.DefineFileSearch() - .Type) + if (result is { Name: newName, Instructions: newInstructions } && result.Tools.First().Type == ToolDefinition.DefineFileSearch().Type) { ConsoleExtensions.WriteLine("Modify Assistant Test is successful.", ConsoleColor.Green); } diff --git a/OpenAI.Playground/TestHelpers/AssistantHelpers/AssistantTestHelper3.cs b/OpenAI.Playground/TestHelpers/AssistantHelpers/AssistantTestHelper3.cs index 57d7c8d8..4e35e744 100644 --- a/OpenAI.Playground/TestHelpers/AssistantHelpers/AssistantTestHelper3.cs +++ b/OpenAI.Playground/TestHelpers/AssistantHelpers/AssistantTestHelper3.cs @@ -27,16 +27,14 @@ public static async Task RunAssistantApiTest(IOpenAIService sdk) #region Create assistant - var func = new FunctionDefinitionBuilder("get_corp_location", "get location of corp").AddParameter("name", PropertyDefinition.DefineString("company name, e.g. Betterway")) - .Validate() - .Build(); + var func = new FunctionDefinitionBuilder("get_corp_location", "get location of corp").AddParameter("name", PropertyDefinition.DefineString("company name, e.g. Betterway")).Validate().Build(); ConsoleExtensions.WriteLine("Assistant Create Test:", ConsoleColor.DarkCyan); - var assistantResult = await sdk.Beta.Assistants.AssistantCreate(new AssistantCreateRequest + var assistantResult = await sdk.Beta.Assistants.AssistantCreate(new() { Instructions = "You are a professional assistant who provides company information. Company-related data comes from uploaded questions and does not provide vague answers, only clear answers.", Name = "Qicha", - Tools = new List() { ToolDefinition.DefineCodeInterpreter(), ToolDefinition.DefineFileSearch(), ToolDefinition.DefineFunction(func) }, + Tools = new() { ToolDefinition.DefineCodeInterpreter(), ToolDefinition.DefineFileSearch(), ToolDefinition.DefineFunction(func) }, Model = Models.Gpt_3_5_Turbo_1106 }); if (assistantResult.Successful) @@ -75,7 +73,7 @@ public static async Task RunAssistantApiTest(IOpenAIService sdk) #region // Assistant modify ConsoleExtensions.WriteLine("Assistant modify:", ConsoleColor.DarkCyan); - var asstResult = await sdk.Beta.Assistants.AssistantModify(assistantId, new AssistantModifyRequest() + var asstResult = await sdk.Beta.Assistants.AssistantModify(assistantId, new() { Name = "Qicha rename" }); @@ -161,17 +159,15 @@ public static async Task RunHowAssistantsWorkTest(IOpenAIService sdk) #region //create assistants - var func = new FunctionDefinitionBuilder("get_corp_location", "get location of corp").AddParameter("name", PropertyDefinition.DefineString("company name, e.g. Betterway")) - .Validate() - .Build(); + var func = new FunctionDefinitionBuilder("get_corp_location", "get location of corp").AddParameter("name", PropertyDefinition.DefineString("company name, e.g. Betterway")).Validate().Build(); ConsoleExtensions.WriteLine("Assistant Create Test:", ConsoleColor.DarkCyan); - var assistantResult = await sdk.Beta.Assistants.AssistantCreate(new AssistantCreateRequest + var assistantResult = await sdk.Beta.Assistants.AssistantCreate(new() { Instructions = "You are a professional assistant who provides company information. Company-related data comes from uploaded questions and does not provide vague answers, only clear answers.", Name = "Qicha", Model = Models.Gpt_3_5_Turbo_1106, - Tools = new List() { ToolDefinition.DefineCodeInterpreter(), ToolDefinition.DefineFileSearch(), ToolDefinition.DefineFunction(func) }, + Tools = [ToolDefinition.DefineCodeInterpreter(), ToolDefinition.DefineFileSearch(), ToolDefinition.DefineFunction(func)] }); if (assistantResult.Successful) @@ -211,16 +207,19 @@ public static async Task RunHowAssistantsWorkTest(IOpenAIService sdk) #region //create thread message ConsoleExtensions.WriteLine("Message Create Test:", ConsoleColor.DarkCyan); - var messageResult = await sdk.Beta.Messages.CreateMessage(threadId, new MessageCreateRequest + var messageResult = await sdk.Beta.Messages.CreateMessage(threadId, new() { Role = StaticValues.AssistantsStatics.MessageStatics.Roles.User, - Content =new("Where is Zhejiang Jiacheng Supply Chain Co., LTD."), + Content = new("Where is Zhejiang Jiacheng Supply Chain Co., LTD."), // Tools must be specified for Attachments - Attachments = [new() - { - FileId = uploadFileId, - Tools = [ ToolDefinition.DefineFileSearch() ] - }] + Attachments = + [ + new() + { + FileId = uploadFileId, + Tools = [ToolDefinition.DefineFileSearch()] + } + ] }); if (messageResult.Successful) @@ -240,7 +239,7 @@ public static async Task RunHowAssistantsWorkTest(IOpenAIService sdk) #region //create run ConsoleExtensions.WriteLine("Run Create Test:", ConsoleColor.DarkCyan); - var runResult = await sdk.Beta.Runs.RunCreate(threadId, new RunCreateRequest() + var runResult = await sdk.Beta.Runs.RunCreate(threadId, new() { AssistantId = assistantId }); @@ -305,7 +304,7 @@ public static async Task RunHowAssistantsWorkTest(IOpenAIService sdk) //All outputs must be submitted in a single request. if (toolOutputs.Any()) { - await sdk.Beta.Runs.RunSubmitToolOutputs(threadId, runId, new SubmitToolOutputsToRunRequest() + await sdk.Beta.Runs.RunSubmitToolOutputs(threadId, runId, new() { ToolOutputs = toolOutputs }); @@ -332,8 +331,7 @@ public static async Task RunHowAssistantsWorkTest(IOpenAIService sdk) { var msgRespList = messageListResult.Data; var ask = msgRespList?.FirstOrDefault(msg => msg.Role == StaticValues.AssistantsStatics.MessageStatics.Roles.User); - var replys = msgRespList?.Where(msg => msg.CreatedAt > ask?.CreatedAt && msg.Role == StaticValues.AssistantsStatics.MessageStatics.Roles.Assistant) - .ToList() ?? new List(); + var replys = msgRespList?.Where(msg => msg.CreatedAt > ask?.CreatedAt && msg.Role == StaticValues.AssistantsStatics.MessageStatics.Roles.Assistant).ToList() ?? new List(); ConsoleExtensions.WriteLine(replys.ToJson()); } else diff --git a/OpenAI.Playground/TestHelpers/AssistantHelpers/RunTestHelper.cs b/OpenAI.Playground/TestHelpers/AssistantHelpers/RunTestHelper.cs index 8be27539..1e6ec2ed 100644 --- a/OpenAI.Playground/TestHelpers/AssistantHelpers/RunTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/AssistantHelpers/RunTestHelper.cs @@ -78,7 +78,7 @@ public static async Task RunThreadAndRunTests(IOpenAIService openAI) ConsoleExtensions.WriteLine("Run Thread and Run Testing is starting:", ConsoleColor.Blue); await CreateThreadAndRun(openAI); } - + public static async Task CreateRunTest(IOpenAIService openAI) { @@ -185,7 +185,6 @@ public static async Task CreateRunAsStreamTest(IOpenAIService openAI) ConsoleExtensions.WriteError(run.Error); } } - } public static async Task CreateToolRunTest(IOpenAIService openAI) @@ -404,8 +403,7 @@ public static async Task SubmitToolOutputsToRunTest(IOpenAIService openAI) [ new() { - ToolCallId = retrieveResult.RequiredAction!.SubmitToolOutputs.ToolCalls.First() - .Id, + ToolCallId = retrieveResult.RequiredAction!.SubmitToolOutputs.ToolCalls.First().Id, Output = "70 degrees and sunny." } ] @@ -442,8 +440,7 @@ public static async Task SubmitToolOutputsAsStreamToRunTest(IOpenAIService openA [ new() { - ToolCallId = retrieveResult.RequiredAction!.SubmitToolOutputs.ToolCalls.First() - .Id, + ToolCallId = retrieveResult.RequiredAction!.SubmitToolOutputs.ToolCalls.First().Id, Output = "70 degrees and sunny." } ] @@ -485,6 +482,7 @@ public static async Task CancelRunTest(IOpenAIService openAI) { CreatedAssistantId = assistantResult.Id; } + var createRunResult = await openAI.Beta.Runs.RunCreate(createThreadResult.Id, new() { AssistantId = assistantResult.Id }); var result = await openAI.Beta.Runs.RunCancel(createThreadResult.Id, createRunResult.Id); @@ -565,8 +563,7 @@ public static async Task RetrieveRunStepTest(IOpenAIService openAI) } var resultStepsList = await openAI.Beta.RunSteps.RunStepsList(CreatedThreadId, CreatedRunId); - var result = await openAI.Beta.RunSteps.RunStepRetrieve(CreatedThreadId, CreatedRunId, resultStepsList.Data!.First() - .Id); + var result = await openAI.Beta.RunSteps.RunStepRetrieve(CreatedThreadId, CreatedRunId, resultStepsList.Data!.First().Id); if (result.Successful) { ConsoleExtensions.WriteLine("Retrieve Run Step Test is successful.", ConsoleColor.Green); @@ -640,7 +637,7 @@ public static async Task CreateThreadAndRunAsStream(IOpenAIService sdk) ] } }); - + await foreach (var run in runResult) { if (run.Successful) @@ -659,9 +656,8 @@ public static async Task CreateThreadAndRunAsStream(IOpenAIService sdk) ConsoleExtensions.WriteError(run.Error); } } - ConsoleExtensions.WriteLine("Create Thread and Run As Stream Test is successful.", ConsoleColor.Green); - + ConsoleExtensions.WriteLine("Create Thread and Run As Stream Test is successful.", ConsoleColor.Green); } public static async Task Cleanup(IOpenAIService sdk) diff --git a/OpenAI.Playground/TestHelpers/AssistantHelpers/RunTestHelper2.cs b/OpenAI.Playground/TestHelpers/AssistantHelpers/RunTestHelper2.cs index 495c8ccf..3090fbcf 100644 --- a/OpenAI.Playground/TestHelpers/AssistantHelpers/RunTestHelper2.cs +++ b/OpenAI.Playground/TestHelpers/AssistantHelpers/RunTestHelper2.cs @@ -19,19 +19,17 @@ public static async Task RunRunCreateTest(IOpenAIService sdk) ConsoleExtensions.WriteLine("Run Create Test:", ConsoleColor.DarkCyan); var threadResult = await sdk.Beta.Threads.ThreadCreate(); var threadId = threadResult.Id; - var func = new FunctionDefinitionBuilder("get_corp_location", "get location of corp").AddParameter("name", PropertyDefinition.DefineString("company name, e.g. Betterway")) - .Validate() - .Build(); - var assistantResult = await sdk.Beta.Assistants.AssistantCreate(new AssistantCreateRequest + var func = new FunctionDefinitionBuilder("get_corp_location", "get location of corp").AddParameter("name", PropertyDefinition.DefineString("company name, e.g. Betterway")).Validate().Build(); + var assistantResult = await sdk.Beta.Assistants.AssistantCreate(new() { Instructions = "You are a professional assistant who provides company information. Company-related data comes from uploaded questions and does not provide vague answers, only clear answers.", Name = "Qicha", - Tools = new List() { ToolDefinition.DefineCodeInterpreter(), ToolDefinition.DefineFileSearch(), ToolDefinition.DefineFunction(func) }, + Tools = new() { ToolDefinition.DefineCodeInterpreter(), ToolDefinition.DefineFileSearch(), ToolDefinition.DefineFunction(func) }, Model = Models.Gpt_3_5_Turbo_1106 }); - var runResult = await sdk.Beta.Runs.RunCreate(threadId, new RunCreateRequest() + var runResult = await sdk.Beta.Runs.RunCreate(threadId, new() { - AssistantId = assistantResult.Id, + AssistantId = assistantResult.Id }); if (runResult.Successful) { @@ -41,7 +39,7 @@ public static async Task RunRunCreateTest(IOpenAIService sdk) { if (runResult.Error == null) { - throw new Exception("Unknown Error"); + throw new("Unknown Error"); } ConsoleExtensions.WriteLine($"{runResult.Error.Code}: {runResult.Error.Message}"); @@ -87,7 +85,7 @@ public static async Task RunRunCreateTest(IOpenAIService sdk) attemptCount++; if (attemptCount >= maxAttempts) { - throw new Exception("The maximum number of attempts has been reached."); + throw new("The maximum number of attempts has been reached."); } } while (!doneStatusList.Contains(runStatus)); } @@ -104,18 +102,17 @@ public static async Task RunRunCancelTest(IOpenAIService sdk) ConsoleExtensions.WriteLine("Run cancel Testing is starting:", ConsoleColor.Cyan); var threadResult = await sdk.Beta.Threads.ThreadCreate(); var threadId = threadResult.Id; - var func = new FunctionDefinitionBuilder("get_corp_location", "get location of corp").AddParameter("name", PropertyDefinition.DefineString("company name, e.g. Betterway")) - .Validate() - .Build(); var assistantResult = await sdk.Beta.Assistants.AssistantCreate(new AssistantCreateRequest - { - Instructions = "You are a professional assistant who provides company information. Company-related data comes from uploaded questions and does not provide vague answers, only clear answers.", - Name = "Qicha", - Tools = new List() { ToolDefinition.DefineCodeInterpreter(), ToolDefinition.DefineFileSearch(), ToolDefinition.DefineFunction(func) }, - Model = Models.Gpt_3_5_Turbo_1106 - }); - var runCreateResult = await sdk.Beta.Runs.RunCreate(threadId, new RunCreateRequest() + var func = new FunctionDefinitionBuilder("get_corp_location", "get location of corp").AddParameter("name", PropertyDefinition.DefineString("company name, e.g. Betterway")).Validate().Build(); + var assistantResult = await sdk.Beta.Assistants.AssistantCreate(new() + { + Instructions = "You are a professional assistant who provides company information. Company-related data comes from uploaded questions and does not provide vague answers, only clear answers.", + Name = "Qicha", + Tools = new() { ToolDefinition.DefineCodeInterpreter(), ToolDefinition.DefineFileSearch(), ToolDefinition.DefineFunction(func) }, + Model = Models.Gpt_3_5_Turbo_1106 + }); + var runCreateResult = await sdk.Beta.Runs.RunCreate(threadId, new() { - AssistantId = assistantResult.Id, + AssistantId = assistantResult.Id }); ConsoleExtensions.WriteLine("Run Cancel Test:", ConsoleColor.DarkCyan); @@ -128,7 +125,7 @@ public static async Task RunRunCancelTest(IOpenAIService sdk) { if (runResult.Error == null) { - throw new Exception("Unknown Error"); + throw new("Unknown Error"); } ConsoleExtensions.WriteLine($"{runResult.Error.Code}: {runResult.Error.Message}"); diff --git a/OpenAI.Playground/TestHelpers/AssistantHelpers/VectorTestHelper.cs b/OpenAI.Playground/TestHelpers/AssistantHelpers/VectorTestHelper.cs index 3b313612..0448b171 100644 --- a/OpenAI.Playground/TestHelpers/AssistantHelpers/VectorTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/AssistantHelpers/VectorTestHelper.cs @@ -219,7 +219,7 @@ public static async Task CreateVectorFile(IOpenAIService openAI) CreatedFileId1 = uploadFilesResponse.Id; var result = await openAI.Beta.VectorStoreFiles.CreateVectorStoreFile(CreatedVectorId, new() { - FileId = CreatedFileId1, + FileId = CreatedFileId1 }); if (result.Successful) @@ -523,4 +523,4 @@ private static async Task Cleanup(IOpenAIService sdk) } } } -} +} \ No newline at end of file diff --git a/OpenAI.Playground/TestHelpers/AudioTestHelper.cs b/OpenAI.Playground/TestHelpers/AudioTestHelper.cs index 1c69d8a3..1609f0a3 100644 --- a/OpenAI.Playground/TestHelpers/AudioTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/AudioTestHelper.cs @@ -1,6 +1,5 @@ using OpenAI.Interfaces; using OpenAI.ObjectModels; -using OpenAI.ObjectModels.RequestModels; using OpenAI.Playground.ExtensionsAndHelpers; namespace OpenAI.Playground.TestHelpers; @@ -19,7 +18,7 @@ public static async Task RunSimpleAudioCreateTranscriptionTest(IOpenAIService sd var sampleFile = await FileExtensions.ReadAllBytesAsync($"SampleData/{fileName}"); ConsoleExtensions.WriteLine($"Uploading file {fileName}", ConsoleColor.DarkCyan); - var audioResult = await sdk.Audio.CreateTranscription(new AudioCreateTranscriptionRequest + var audioResult = await sdk.Audio.CreateTranscription(new() { FileName = fileName, File = sampleFile, @@ -43,7 +42,7 @@ public static async Task RunSimpleAudioCreateTranscriptionTest(IOpenAIService sd { if (audioResult.Error == null) { - throw new Exception("Unknown Error"); + throw new("Unknown Error"); } Console.WriteLine($"{audioResult.Error.Code}: {audioResult.Error.Message}"); @@ -68,7 +67,7 @@ public static async Task RunSimpleAudioCreateTranslationTest(IOpenAIService sdk) var sampleFile = await FileExtensions.ReadAllBytesAsync($"SampleData/{fileName}"); ConsoleExtensions.WriteLine($"Uploading file {fileName}", ConsoleColor.DarkCyan); - var audioResult = await sdk.Audio.CreateTranslation(new AudioCreateTranscriptionRequest + var audioResult = await sdk.Audio.CreateTranslation(new() { FileName = fileName, File = sampleFile, @@ -84,7 +83,7 @@ public static async Task RunSimpleAudioCreateTranslationTest(IOpenAIService sdk) { if (audioResult.Error == null) { - throw new Exception("Unknown Error"); + throw new("Unknown Error"); } Console.WriteLine($"{audioResult.Error.Code}: {audioResult.Error.Message}"); @@ -97,14 +96,14 @@ public static async Task RunSimpleAudioCreateTranslationTest(IOpenAIService sdk) } } - public static async Task RunSimpleAudioCreateSpeechTest(IOpenAIService sdk) + public static async Task RunSimpleAudioCreateSpeechTest(IOpenAIService sdk) { ConsoleExtensions.WriteLine("Create Speech Testing is starting:", ConsoleColor.Cyan); try { ConsoleExtensions.WriteLine("Audio Create Speech Test:", ConsoleColor.DarkCyan); - var audioResult = await sdk.Audio.CreateSpeech(new AudioCreateSpeechRequest + var audioResult = await sdk.Audio.CreateSpeech(new() { Model = Models.Tts_1, Input = "The sixth sick sheikh's sixth sheep's sick", @@ -116,7 +115,7 @@ public static async Task RunSimpleAudioCreateSpeechTest(IOpenAIService sdk) if (audioResult.Successful) { #if NET6_0_OR_GREATER - var audio =audioResult.Data!; + var audio = audioResult.Data!; // save stream data as mp3 file await using var fileStream = File.Create("SampleData/speech.mp3"); await audio.CopyToAsync(fileStream); @@ -128,7 +127,7 @@ public static async Task RunSimpleAudioCreateSpeechTest(IOpenAIService sdk) { if (audioResult.Error == null) { - throw new Exception("Unknown Error"); + throw new("Unknown Error"); } Console.WriteLine($"{audioResult.Error.Code}: {audioResult.Error.Message}"); @@ -140,4 +139,4 @@ public static async Task RunSimpleAudioCreateSpeechTest(IOpenAIService sdk) throw; } } -} +} \ No newline at end of file diff --git a/OpenAI.Playground/TestHelpers/BatchTestHelper.cs b/OpenAI.Playground/TestHelpers/BatchTestHelper.cs index eb96b97e..a0708481 100644 --- a/OpenAI.Playground/TestHelpers/BatchTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/BatchTestHelper.cs @@ -1,5 +1,4 @@ using OpenAI.Interfaces; -using OpenAI.ObjectModels.RequestModels; using OpenAI.Playground.ExtensionsAndHelpers; namespace OpenAI.Playground.TestHelpers; @@ -22,10 +21,10 @@ public static async Task RunBatchOperationsTest(IOpenAIService sdk) if (!fileUploadResult.Successful) { - throw new Exception("File upload failed"); + throw new("File upload failed"); } - var batchCreateResult = await sdk.Batch.BatchCreate(new BatchCreateRequest + var batchCreateResult = await sdk.Batch.BatchCreate(new() { InputFileId = fileUploadResult.Id, Endpoint = "/v1/chat/completions", @@ -34,7 +33,7 @@ public static async Task RunBatchOperationsTest(IOpenAIService sdk) if (!batchCreateResult.Successful) { - throw new Exception("Batch creation failed"); + throw new("Batch creation failed"); } ConsoleExtensions.WriteLine($"Batch ID: {batchCreateResult.Id}", ConsoleColor.Green); @@ -46,7 +45,7 @@ public static async Task RunBatchOperationsTest(IOpenAIService sdk) if (!batchRetrieveResult.Successful) { - throw new Exception("Batch retrieval failed"); + throw new("Batch retrieval failed"); } ConsoleExtensions.WriteLine($"Batch ID: {batchRetrieveResult.Id}", ConsoleColor.Green); @@ -62,7 +61,7 @@ public static async Task RunBatchOperationsTest(IOpenAIService sdk) if (!batchCancelResult.Successful) { - throw new Exception("Batch cancellation failed"); + throw new("Batch cancellation failed"); } ConsoleExtensions.WriteLine($"Batch ID: {batchCancelResult.Id}", ConsoleColor.Green); diff --git a/OpenAI.Playground/TestHelpers/ChatCompletionTestHelper.cs b/OpenAI.Playground/TestHelpers/ChatCompletionTestHelper.cs index 835a8bc9..74d8a18a 100644 --- a/OpenAI.Playground/TestHelpers/ChatCompletionTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/ChatCompletionTestHelper.cs @@ -16,7 +16,7 @@ public static async Task RunSimpleChatCompletionTest(IOpenAIService sdk) try { ConsoleExtensions.WriteLine("Chat Completion Test:", ConsoleColor.DarkCyan); - var completionResult = await sdk.ChatCompletion.CreateCompletion(new ChatCompletionCreateRequest + var completionResult = await sdk.ChatCompletion.CreateCompletion(new() { Messages = new List { @@ -37,7 +37,7 @@ public static async Task RunSimpleChatCompletionTest(IOpenAIService sdk) { if (completionResult.Error == null) { - throw new Exception("Unknown Error"); + throw new("Unknown Error"); } Console.WriteLine($"{completionResult.Error.Code}: {completionResult.Error.Message}"); @@ -56,7 +56,7 @@ public static async Task RunSimpleCompletionStreamTest(IOpenAIService sdk) try { ConsoleExtensions.WriteLine("Chat Completion Stream Test:", ConsoleColor.DarkCyan); - var completionResult = sdk.ChatCompletion.CreateCompletionAsStream(new ChatCompletionCreateRequest + var completionResult = sdk.ChatCompletion.CreateCompletionAsStream(new() { Messages = new List { @@ -79,7 +79,7 @@ public static async Task RunSimpleCompletionStreamTest(IOpenAIService sdk) { if (completion.Error == null) { - throw new Exception("Unknown Error"); + throw new("Unknown Error"); } Console.WriteLine($"{completion.Error.Code}: {completion.Error.Message}"); @@ -102,7 +102,7 @@ public static async Task RunSimpleCompletionStreamWithUsageTest(IOpenAIService s try { ConsoleExtensions.WriteLine("Chat Completion Stream Test:", ConsoleColor.DarkCyan); - var completionResult = sdk.ChatCompletion.CreateCompletionAsStream(new ChatCompletionCreateRequest + var completionResult = sdk.ChatCompletion.CreateCompletionAsStream(new() { Messages = new List { @@ -111,9 +111,9 @@ public static async Task RunSimpleCompletionStreamWithUsageTest(IOpenAIService s new(StaticValues.ChatMessageRoles.System, "The Los Angeles Dodgers won the World Series in 2020."), new(StaticValues.ChatMessageRoles.User, "Tell me a story about The Los Angeles Dodgers") }, - StreamOptions = new StreamOptions + StreamOptions = new() { - IncludeUsage = true, + IncludeUsage = true }, MaxTokens = 150, Model = Models.Gpt_3_5_Turbo @@ -138,7 +138,7 @@ public static async Task RunSimpleCompletionStreamWithUsageTest(IOpenAIService s { if (completion.Error == null) { - throw new Exception("Unknown Error"); + throw new("Unknown Error"); } Console.WriteLine($"{completion.Error.Code}: {completion.Error.Message}"); @@ -162,20 +162,17 @@ public static async Task RunChatFunctionCallTest(IOpenAIService sdk) // example taken from: // https://github.com/openai/openai-cookbook/blob/main/examples/How_to_call_functions_with_chat_models.ipynb - var fn1 = new FunctionDefinitionBuilder("get_current_weather", "Get the current weather") - .AddParameter("location", PropertyDefinition.DefineString("The city and state, e.g. San Francisco, CA")) - .AddParameter("format", PropertyDefinition.DefineEnum(new List {"celsius", "fahrenheit"}, "The temperature unit to use. Infer this from the users location.")) + var fn1 = new FunctionDefinitionBuilder("get_current_weather", "Get the current weather").AddParameter("location", PropertyDefinition.DefineString("The city and state, e.g. San Francisco, CA")) + .AddParameter("format", PropertyDefinition.DefineEnum(new() { "celsius", "fahrenheit" }, "The temperature unit to use. Infer this from the users location.")) .Validate() .Build(); - var fn2 = new FunctionDefinitionBuilder("get_n_day_weather_forecast", "Get an N-day weather forecast") - .AddParameter("location", new PropertyDefinition {Type = "string", Description = "The city and state, e.g. San Francisco, CA"}) - .AddParameter("format", PropertyDefinition.DefineEnum(new List {"celsius", "fahrenheit"}, "The temperature unit to use. Infer this from the users location.")) + var fn2 = new FunctionDefinitionBuilder("get_n_day_weather_forecast", "Get an N-day weather forecast").AddParameter("location", new() { Type = "string", Description = "The city and state, e.g. San Francisco, CA" }) + .AddParameter("format", PropertyDefinition.DefineEnum(new() { "celsius", "fahrenheit" }, "The temperature unit to use. Infer this from the users location.")) .AddParameter("num_days", PropertyDefinition.DefineInteger("The number of days to forecast")) .Validate() .Build(); - var fn3 = new FunctionDefinitionBuilder("get_current_datetime", "Get the current date and time, e.g. 'Saturday, June 24, 2023 6:14:14 PM'") - .Build(); + var fn3 = new FunctionDefinitionBuilder("get_current_datetime", "Get the current date and time, e.g. 'Saturday, June 24, 2023 6:14:14 PM'").Build(); var fn4 = new FunctionDefinitionBuilder("identify_number_sequence", "Get a sequence of numbers present in the user message") .AddParameter("values", PropertyDefinition.DefineArray(PropertyDefinition.DefineNumber("Sequence of numbers specified by the user"))) @@ -203,7 +200,7 @@ public static async Task RunChatFunctionCallTest(IOpenAIService sdk) var completionResult = await sdk.ChatCompletion.CreateCompletion(request); /* expected output along the lines of: - + Message: Function call: get_n_day_weather_forecast location: Chicago, USA @@ -248,14 +245,14 @@ public static async Task RunChatFunctionCallTest(IOpenAIService sdk) { if (completionResult.Error == null) { - throw new Exception("Unknown Error"); + throw new("Unknown Error"); } Console.WriteLine($"{completionResult.Error.Code}: {completionResult.Error.Message}"); } - var completionResultAfterTool = await sdk.ChatCompletion.CreateCompletion(request); - + var completionResultAfterTool = await sdk.ChatCompletion.CreateCompletion(request); + if (completionResultAfterTool.Successful) { Console.WriteLine(completionResultAfterTool.Choices.First().Message.Content); @@ -264,7 +261,7 @@ public static async Task RunChatFunctionCallTest(IOpenAIService sdk) { if (completionResultAfterTool.Error == null) { - throw new Exception("Unknown Error"); + throw new("Unknown Error"); } Console.WriteLine($"{completionResultAfterTool.Error.Code}: {completionResultAfterTool.Error.Message}"); @@ -284,31 +281,24 @@ public static async Task RunChatFunctionCallTestAsStream(IOpenAIService sdk) // example taken from: // https://github.com/openai/openai-cookbook/blob/main/examples/How_to_call_functions_with_chat_models.ipynb - var fn1 = new FunctionDefinitionBuilder("get_current_weather", "Get the current weather") - .AddParameter("location", PropertyDefinition.DefineString("The city and state, e.g. San Francisco, CA")) - .AddParameter("format", PropertyDefinition.DefineEnum(new List {"celsius", "fahrenheit"}, "The temperature unit to use. Infer this from the users location.")) + var fn1 = new FunctionDefinitionBuilder("get_current_weather", "Get the current weather").AddParameter("location", PropertyDefinition.DefineString("The city and state, e.g. San Francisco, CA")) + .AddParameter("format", PropertyDefinition.DefineEnum(new() { "celsius", "fahrenheit" }, "The temperature unit to use. Infer this from the users location.")) .Validate() .Build(); - var fn2 = new FunctionDefinitionBuilder("get_n_day_weather_forecast", "Get an N-day weather forecast") - .AddParameter("location", new PropertyDefinition {Type = "string", Description = "The city and state, e.g. San Francisco, CA"}) - .AddParameter("format", PropertyDefinition.DefineEnum(new List {"celsius", "fahrenheit"}, "The temperature unit to use. Infer this from the users location.")) + var fn2 = new FunctionDefinitionBuilder("get_n_day_weather_forecast", "Get an N-day weather forecast").AddParameter("location", new() { Type = "string", Description = "The city and state, e.g. San Francisco, CA" }) + .AddParameter("format", PropertyDefinition.DefineEnum(new() { "celsius", "fahrenheit" }, "The temperature unit to use. Infer this from the users location.")) .AddParameter("num_days", PropertyDefinition.DefineInteger("The number of days to forecast")) .Validate() .Build(); - var fn3 = new FunctionDefinitionBuilder("get_current_datetime", "Get the current date and time, e.g. 'Saturday, June 24, 2023 6:14:14 PM'") - .Build(); + var fn3 = new FunctionDefinitionBuilder("get_current_datetime", "Get the current date and time, e.g. 'Saturday, June 24, 2023 6:14:14 PM'").Build(); var fn4 = new FunctionDefinitionBuilder("identify_number_sequence", "Get a sequence of numbers present in the user message") .AddParameter("values", PropertyDefinition.DefineArray(PropertyDefinition.DefineNumber("Sequence of numbers specified by the user"))) - .Build(); - var fn5 = new FunctionDefinitionBuilder("google_search", "Gets a result from Google Search") - .AddParameter("search_term", PropertyDefinition.DefineArray(PropertyDefinition.DefineNumber("Search Term"))) - .Build(); - var fn6 = new FunctionDefinitionBuilder("getURL", "Downloads the content of given website") - .AddParameter("URL", PropertyDefinition.DefineArray(PropertyDefinition.DefineNumber("Search Term"))) .Build(); + var fn5 = new FunctionDefinitionBuilder("google_search", "Gets a result from Google Search").AddParameter("search_term", PropertyDefinition.DefineArray(PropertyDefinition.DefineNumber("Search Term"))).Build(); + var fn6 = new FunctionDefinitionBuilder("getURL", "Downloads the content of given website").AddParameter("URL", PropertyDefinition.DefineArray(PropertyDefinition.DefineNumber("Search Term"))).Build(); try { @@ -320,12 +310,13 @@ public static async Task RunChatFunctionCallTestAsStream(IOpenAIService sdk) { ChatMessage.FromSystem("You are a bot that performs internet searches and also downloads content from websites."), // to test weather forecast functions: - ChatMessage.FromUser("I need you to first search Google for \"Cat\" and, at the same time, download the contents from https://www.wired.com."), + ChatMessage.FromUser("I need you to first search Google for \"Cat\" and, at the same time, download the contents from https://www.wired.com.") //ChatMessage.FromUser("Give me a weather report for Chicago, USA, for the next 5 days and also current weather.") // or to test array functions, use this instead: // ChatMessage.FromUser("And also The combination is: One. Two. Three. Four. Five."), }, - Tools = new List { ToolDefinition.DefineFunction(fn1), ToolDefinition.DefineFunction(fn2), ToolDefinition.DefineFunction(fn3), ToolDefinition.DefineFunction(fn4), ToolDefinition.DefineFunction(fn5), ToolDefinition.DefineFunction(fn6) }, + Tools = new List + { ToolDefinition.DefineFunction(fn1), ToolDefinition.DefineFunction(fn2), ToolDefinition.DefineFunction(fn3), ToolDefinition.DefineFunction(fn4), ToolDefinition.DefineFunction(fn5), ToolDefinition.DefineFunction(fn6) }, // optionally, to force a specific function: //ToolChoice = ToolChoice.FunctionChoice("get_current_weather"), // or auto tool choice: @@ -337,7 +328,7 @@ public static async Task RunChatFunctionCallTestAsStream(IOpenAIService sdk) var completionResults = sdk.ChatCompletion.CreateCompletionAsStream(request); /* when testing weather forecasts, expected output should be along the lines of: - + Message: Function call: get_n_day_weather_forecast location: Chicago, USA @@ -346,7 +337,7 @@ public static async Task RunChatFunctionCallTestAsStream(IOpenAIService sdk) */ /* when testing array functions, expected output should be along the lines of: - + Message: Function call: identify_number_sequence values: [1, 2, 3, 4, 5] @@ -365,7 +356,7 @@ public static async Task RunChatFunctionCallTestAsStream(IOpenAIService sdk) request.Messages.Add(choice.Message); Console.WriteLine($"Tools: {tools.Count}"); - for (int i = 0; i < tools.Count; i++) + for (var i = 0; i < tools.Count; i++) { var toolCall = tools[i]; Console.WriteLine($" {toolCall.Id}: {toolCall.FunctionCall}"); @@ -377,7 +368,7 @@ public static async Task RunChatFunctionCallTestAsStream(IOpenAIService sdk) { Console.WriteLine($" Function call: {fn.Name}"); } - + if (!string.IsNullOrEmpty(fn.Arguments)) { if (functionArguments.TryGetValue(i, out var currentArguments)) @@ -388,6 +379,7 @@ public static async Task RunChatFunctionCallTestAsStream(IOpenAIService sdk) { currentArguments = fn.Arguments; } + functionArguments[i] = currentArguments; fn.Arguments = currentArguments; @@ -421,7 +413,7 @@ public static async Task RunChatFunctionCallTestAsStream(IOpenAIService sdk) { if (completionResult.Error == null) { - throw new Exception("Unknown Error"); + throw new("Unknown Error"); } Console.WriteLine($"{completionResult.Error.Code}: {completionResult.Error.Message}"); @@ -440,7 +432,7 @@ public static async Task RunChatFunctionCallTestAsStream(IOpenAIService sdk) { if (completion.Error == null) { - throw new Exception("Unknown Error"); + throw new("Unknown Error"); } Console.WriteLine($"{completion.Error.Code}: {completion.Error.Message}"); diff --git a/OpenAI.Playground/TestHelpers/CompletionTestHelper.cs b/OpenAI.Playground/TestHelpers/CompletionTestHelper.cs index 0837e21b..a85b8b3d 100644 --- a/OpenAI.Playground/TestHelpers/CompletionTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/CompletionTestHelper.cs @@ -1,6 +1,5 @@ using OpenAI.Interfaces; using OpenAI.ObjectModels; -using OpenAI.ObjectModels.RequestModels; using OpenAI.Playground.ExtensionsAndHelpers; namespace OpenAI.Playground.TestHelpers; @@ -14,7 +13,7 @@ public static async Task RunSimpleCompletionTest(IOpenAIService sdk, Cancellatio try { ConsoleExtensions.WriteLine("Completion Test:", ConsoleColor.DarkCyan); - var completionResult = await sdk.Completions.CreateCompletion(new CompletionCreateRequest + var completionResult = await sdk.Completions.CreateCompletion(new() { Prompt = "Once upon a time", // PromptAsList = new []{"Once upon a time"}, @@ -30,7 +29,7 @@ public static async Task RunSimpleCompletionTest(IOpenAIService sdk, Cancellatio { if (completionResult.Error == null) { - throw new Exception("Unknown Error"); + throw new("Unknown Error"); } Console.WriteLine($"{completionResult.Error.Code}: {completionResult.Error.Message}"); @@ -65,7 +64,7 @@ public static async Task RunSimpleCompletionTest2(IOpenAIService sdk) try { ConsoleExtensions.WriteLine("Completion Test:", ConsoleColor.DarkCyan); - var completionResult = await sdk.Completions.CreateCompletion(new CompletionCreateRequest + var completionResult = await sdk.Completions.CreateCompletion(new() { Prompt = "Once upon a time", // PromptAsList = new []{"Once upon a time"}, @@ -82,7 +81,7 @@ public static async Task RunSimpleCompletionTest2(IOpenAIService sdk) { if (completionResult.Error == null) { - throw new Exception("Unknown Error"); + throw new("Unknown Error"); } Console.WriteLine($"{completionResult.Error.Code}: {completionResult.Error.Message}"); @@ -105,7 +104,7 @@ public static async Task RunSimpleCompletionTest3(IOpenAIService sdk) { ConsoleExtensions.WriteLine("Completion Test:", ConsoleColor.DarkCyan); //Parameter Model should override the Model in the ObjectModel - var completionResult = await sdk.Completions.CreateCompletion(new CompletionCreateRequest + var completionResult = await sdk.Completions.CreateCompletion(new() { Prompt = "Once upon a time", // PromptAsList = new []{"Once upon a time"}, @@ -122,7 +121,7 @@ public static async Task RunSimpleCompletionTest3(IOpenAIService sdk) { if (completionResult.Error == null) { - throw new Exception("Unknown Error"); + throw new("Unknown Error"); } Console.WriteLine($"{completionResult.Error.Code}: {completionResult.Error.Message}"); @@ -143,7 +142,7 @@ public static async Task RunSimpleCompletionStreamTest(IOpenAIService sdk) try { ConsoleExtensions.WriteLine("Completion Stream Test:", ConsoleColor.DarkCyan); - var completionResult = sdk.Completions.CreateCompletionAsStream(new CompletionCreateRequest + var completionResult = sdk.Completions.CreateCompletionAsStream(new() { Prompt = "Once upon a time", MaxTokens = 500 @@ -159,7 +158,7 @@ public static async Task RunSimpleCompletionStreamTest(IOpenAIService sdk) { if (completion.Error == null) { - throw new Exception("Unknown Error"); + throw new("Unknown Error"); } Console.WriteLine($"{completion.Error.Code}: {completion.Error.Message}"); @@ -185,7 +184,7 @@ public static async Task RunSimpleCompletionStreamTestWithCancellationToken(IOpe try { ConsoleExtensions.WriteLine("Completion Stream Test:", ConsoleColor.DarkCyan); - var completionResult = sdk.Completions.CreateCompletionAsStream(new CompletionCreateRequest + var completionResult = sdk.Completions.CreateCompletionAsStream(new() { Prompt = "Once upon a time", MaxTokens = 100 @@ -203,7 +202,7 @@ public static async Task RunSimpleCompletionStreamTestWithCancellationToken(IOpe { if (completion.Error == null) { - throw new Exception("Unknown Error"); + throw new("Unknown Error"); } Console.WriteLine($"{completion.Error.Code}: {completion.Error.Message}"); diff --git a/OpenAI.Playground/TestHelpers/EditTestHelper.cs b/OpenAI.Playground/TestHelpers/EditTestHelper.cs index 7ec0fec1..99ec12f8 100644 --- a/OpenAI.Playground/TestHelpers/EditTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/EditTestHelper.cs @@ -1,6 +1,5 @@ using OpenAI.Interfaces; using OpenAI.ObjectModels; -using OpenAI.ObjectModels.RequestModels; using OpenAI.Playground.ExtensionsAndHelpers; namespace OpenAI.Playground.TestHelpers; @@ -14,7 +13,7 @@ public static async Task RunSimpleEditCreateTest(IOpenAIService sdk) try { ConsoleExtensions.WriteLine("Edit Create Test:", ConsoleColor.DarkCyan); - var completionResult = await sdk.Edit.CreateEdit(new EditCreateRequest + var completionResult = await sdk.Edit.CreateEdit(new() { Input = "What day of the wek is it?", Instruction = "Fix the spelling mistakes" @@ -28,7 +27,7 @@ public static async Task RunSimpleEditCreateTest(IOpenAIService sdk) { if (completionResult.Error == null) { - throw new Exception("Unknown Error"); + throw new("Unknown Error"); } Console.WriteLine($"{completionResult.Error.Code}: {completionResult.Error.Message}"); diff --git a/OpenAI.Playground/TestHelpers/EmbeddingTestHelper.cs b/OpenAI.Playground/TestHelpers/EmbeddingTestHelper.cs index 66068d42..ebbf8c46 100644 --- a/OpenAI.Playground/TestHelpers/EmbeddingTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/EmbeddingTestHelper.cs @@ -1,6 +1,5 @@ using OpenAI.Interfaces; using OpenAI.ObjectModels; -using OpenAI.ObjectModels.RequestModels; using OpenAI.Playground.ExtensionsAndHelpers; namespace OpenAI.Playground.TestHelpers; @@ -14,9 +13,9 @@ public static async Task RunSimpleEmbeddingTest(IOpenAIService sdk) try { ConsoleExtensions.WriteLine("Embedding Test:", ConsoleColor.DarkCyan); - var embeddingResult = await sdk.Embeddings.CreateEmbedding(new EmbeddingCreateRequest + var embeddingResult = await sdk.Embeddings.CreateEmbedding(new() { - InputAsList = new List {"The quick brown fox jumped over the lazy dog."}, + InputAsList = new() { "The quick brown fox jumped over the lazy dog." }, Model = Models.TextEmbeddingAdaV2 }); @@ -28,7 +27,7 @@ public static async Task RunSimpleEmbeddingTest(IOpenAIService sdk) { if (embeddingResult.Error == null) { - throw new Exception("Unknown Error"); + throw new("Unknown Error"); } Console.WriteLine($"{embeddingResult.Error.Code}: {embeddingResult.Error.Message}"); diff --git a/OpenAI.Playground/TestHelpers/FineTuningJobTestHelper.cs b/OpenAI.Playground/TestHelpers/FineTuningJobTestHelper.cs index 93ef4dd9..eca493ae 100644 --- a/OpenAI.Playground/TestHelpers/FineTuningJobTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/FineTuningJobTestHelper.cs @@ -17,7 +17,7 @@ public static async Task RunCaseStudyIsTheModelMakingUntrueStatements(IOpenAISer foreach (var job in jobs.Data) { Console.WriteLine(job.FineTunedModel); - } + } try { @@ -38,13 +38,13 @@ public static async Task RunCaseStudyIsTheModelMakingUntrueStatements(IOpenAISer ConsoleExtensions.WriteLine($"Wait 5 seconds for the file to be ready", ConsoleColor.DarkYellow); await Task.Delay(5_000); - var createFineTuningJobResponse = await sdk.FineTuningJob.CreateFineTuningJob(new FineTuningJobCreateRequest + var createFineTuningJobResponse = await sdk.FineTuningJob.CreateFineTuningJob(new() { TrainingFile = uploadFilesResponse.Id, Model = Models.Gpt_3_5_Turbo }); - var listFineTuningJobEventsStream = await sdk.FineTuningJob.ListFineTuningJobEvents(new FineTuningJobListEventsRequest + var listFineTuningJobEventsStream = await sdk.FineTuningJob.ListFineTuningJobEvents(new() { FineTuningJobId = createFineTuningJobResponse.Id }, true); @@ -71,12 +71,12 @@ public static async Task RunCaseStudyIsTheModelMakingUntrueStatements(IOpenAISer do { - var completionResult = await sdk.ChatCompletion.CreateCompletion(new ChatCompletionCreateRequest + var completionResult = await sdk.ChatCompletion.CreateCompletion(new() { Messages = new List { ChatMessage.FromSystem("You are Marv, a chatbot that reluctantly answers questions with sarcastic responses."), - ChatMessage.FromUser("How many pounds are in a kilogram?"), + ChatMessage.FromUser("How many pounds are in a kilogram?") }, MaxTokens = 50, Model = retrieveFineTuningJobResponse.FineTunedModel diff --git a/OpenAI.Playground/TestHelpers/FineTuningTestHelper.cs b/OpenAI.Playground/TestHelpers/FineTuningTestHelper.cs index 78e5858f..6ea4e4c5 100644 --- a/OpenAI.Playground/TestHelpers/FineTuningTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/FineTuningTestHelper.cs @@ -1,6 +1,5 @@ using OpenAI.Interfaces; using OpenAI.ObjectModels; -using OpenAI.ObjectModels.RequestModels; using OpenAI.ObjectModels.ResponseModels.FineTuneResponseModels; using OpenAI.Playground.ExtensionsAndHelpers; @@ -28,7 +27,7 @@ public static async Task RunCaseStudyIsTheModelMakingUntrueStatements(IOpenAISer ConsoleExtensions.WriteLine($"{fileName} failed", ConsoleColor.DarkRed); } - var createFineTuneResponse = await sdk.FineTunes.CreateFineTune(new FineTuneCreateRequest + var createFineTuneResponse = await sdk.FineTunes.CreateFineTune(new() { TrainingFile = uploadFilesResponse.Id, Model = Models.Ada @@ -57,7 +56,7 @@ public static async Task RunCaseStudyIsTheModelMakingUntrueStatements(IOpenAISer do { - var completionResult = await sdk.Completions.CreateCompletion(new CompletionCreateRequest + var completionResult = await sdk.Completions.CreateCompletion(new() { MaxTokens = 1, Prompt = @"https://t.co/f93xEd2 Excited to share my latest blog post! ->", diff --git a/OpenAI.Playground/TestHelpers/ImageTestHelper.cs b/OpenAI.Playground/TestHelpers/ImageTestHelper.cs index bc41e739..3b4063d9 100644 --- a/OpenAI.Playground/TestHelpers/ImageTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/ImageTestHelper.cs @@ -1,6 +1,5 @@ using OpenAI.Interfaces; using OpenAI.ObjectModels; -using OpenAI.ObjectModels.RequestModels; using OpenAI.Playground.ExtensionsAndHelpers; namespace OpenAI.Playground.TestHelpers; @@ -14,7 +13,7 @@ public static async Task RunSimpleCreateImageTest(IOpenAIService sdk) try { ConsoleExtensions.WriteLine("Image Create Test:", ConsoleColor.DarkCyan); - var imageResult = await sdk.Image.CreateImage(new ImageCreateRequest + var imageResult = await sdk.Image.CreateImage(new() { Prompt = "Laser cat eyes", N = 1, @@ -32,7 +31,7 @@ public static async Task RunSimpleCreateImageTest(IOpenAIService sdk) { if (imageResult.Error == null) { - throw new Exception("Unknown Error"); + throw new("Unknown Error"); } Console.WriteLine($"{imageResult.Error.Code}: {imageResult.Error.Message}"); @@ -59,7 +58,7 @@ public static async Task RunSimpleCreateImageEditTest(IOpenAIService sdk) try { ConsoleExtensions.WriteLine("Image Edit Create Test:", ConsoleColor.DarkCyan); - var imageResult = await sdk.Image.CreateImageEdit(new ImageEditCreateRequest + var imageResult = await sdk.Image.CreateImageEdit(new() { Image = originalFile, ImageName = originalFileName, @@ -81,7 +80,7 @@ public static async Task RunSimpleCreateImageEditTest(IOpenAIService sdk) { if (imageResult.Error == null) { - throw new Exception("Unknown Error"); + throw new("Unknown Error"); } Console.WriteLine($"{imageResult.Error.Code}: {imageResult.Error.Message}"); @@ -104,7 +103,7 @@ public static async Task RunSimpleCreateImageVariationTest(IOpenAIService sdk) try { ConsoleExtensions.WriteLine("Image Variation Create Test:", ConsoleColor.DarkCyan); - var imageResult = await sdk.Image.CreateImageVariation(new ImageVariationCreateRequest + var imageResult = await sdk.Image.CreateImageVariation(new() { Image = originalFile, ImageName = originalFileName, @@ -123,7 +122,7 @@ public static async Task RunSimpleCreateImageVariationTest(IOpenAIService sdk) { if (imageResult.Error == null) { - throw new Exception("Unknown Error"); + throw new("Unknown Error"); } Console.WriteLine($"{imageResult.Error.Code}: {imageResult.Error.Message}"); diff --git a/OpenAI.Playground/TestHelpers/ModerationTestHelper.cs b/OpenAI.Playground/TestHelpers/ModerationTestHelper.cs index 1c47f049..9c62346b 100644 --- a/OpenAI.Playground/TestHelpers/ModerationTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/ModerationTestHelper.cs @@ -1,5 +1,4 @@ using OpenAI.Interfaces; -using OpenAI.ObjectModels.RequestModels; using OpenAI.Playground.ExtensionsAndHelpers; namespace OpenAI.Playground.TestHelpers; @@ -13,7 +12,7 @@ public static async Task CreateModerationTest(IOpenAIService sdk) try { ConsoleExtensions.WriteLine("Create Moderation test", ConsoleColor.DarkCyan); - var moderationResponse = await sdk.Moderation.CreateModeration(new CreateModerationRequest + var moderationResponse = await sdk.Moderation.CreateModeration(new() { Input = "I want to kill them." }); diff --git a/OpenAI.Playground/TestHelpers/ThreadTestHelper.cs b/OpenAI.Playground/TestHelpers/ThreadTestHelper.cs index 993a0f9f..c621217c 100644 --- a/OpenAI.Playground/TestHelpers/ThreadTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/ThreadTestHelper.cs @@ -23,7 +23,7 @@ public static async Task RunThreadCreateTest(IOpenAIService sdk) { if (threadResult.Error == null) { - throw new Exception("Unknown Error"); + throw new("Unknown Error"); } ConsoleExtensions.WriteLine($"{threadResult.Error.Code}: {threadResult.Error.Message}"); @@ -55,7 +55,7 @@ public static async Task RunThreadRetrieveTest(IOpenAIService sdk) { if (threadResult.Error == null) { - throw new Exception("Unknown Error"); + throw new("Unknown Error"); } ConsoleExtensions.WriteLine($"{threadResult.Error.Code}: {threadResult.Error.Message}"); diff --git a/OpenAI.SDK/Builders/FunctionDefinitionBuilder.cs b/OpenAI.SDK/Builders/FunctionDefinitionBuilder.cs index d413d21d..482ca978 100644 --- a/OpenAI.SDK/Builders/FunctionDefinitionBuilder.cs +++ b/OpenAI.SDK/Builders/FunctionDefinitionBuilder.cs @@ -11,10 +11,7 @@ public class FunctionDefinitionBuilder /// /// String constant for validation of function name. /// - private const string ValidNameChars = - "abcdefghijklmnopqrstuvwxyz" + - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + - "0123456789-_"; + private const string ValidNameChars = "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789-_"; private readonly FunctionDefinition _definition; @@ -25,11 +22,11 @@ public class FunctionDefinitionBuilder /// The optional description of the function public FunctionDefinitionBuilder(string name, string? description = null) { - _definition = new FunctionDefinition + _definition = new() { Name = name, Description = description, - Parameters = new PropertyDefinition + Parameters = new() { Properties = new Dictionary() } diff --git a/OpenAI.SDK/EndpointProviders/AzureOpenAiEndpointProvider.cs b/OpenAI.SDK/EndpointProviders/AzureOpenAiEndpointProvider.cs index c13fa58b..100e665b 100644 --- a/OpenAI.SDK/EndpointProviders/AzureOpenAiEndpointProvider.cs +++ b/OpenAI.SDK/EndpointProviders/AzureOpenAiEndpointProvider.cs @@ -20,6 +20,7 @@ public AzureOpenAiEndpointProvider(string apiVersion, string deploymentId) private string Prefix => $"{ApiPrefix}/{DeploymentsPrefix}/{WebUtility.UrlEncode(_deploymentId)}"; private string AzureVersionQueryString => $"?api-version={_apiVersion}"; private string AssistantPrefix => $"{ApiPrefix}/"; + public string ModelRetrieve(string model) { return $"{Prefix}/models/{model}{AzureVersionQueryString}"; @@ -291,6 +292,7 @@ public string MessageList(string threadId, PaginationRequest? messageListRequest return url; } + public string MessageDelete(string threadId, string messageId) { return $"{AssistantPrefix}/threads/{threadId}/messages/{messageId}{AzureVersionQueryString}"; @@ -447,11 +449,6 @@ public string VectorStoreFileBatchList(string vectorStoreId, string batchId, Pag return url; } - public string FineTuningJobList() - { - return $"{Prefix}/fine_tuning/jobs{AzureVersionQueryString}"; - } - public string BatchCreate() { return $"{Prefix}/batches{AzureVersionQueryString}"; @@ -467,10 +464,13 @@ public string BatchCancel(string batchId) return $"{Prefix}/batches/{batchId}/cancel{AzureVersionQueryString}"; } + public string FineTuningJobList() + { + return $"{Prefix}/fine_tuning/jobs{AzureVersionQueryString}"; + } + private string Files() { return $"{Prefix}/files{AzureVersionQueryString}"; } - - } \ No newline at end of file diff --git a/OpenAI.SDK/EndpointProviders/IOpenAiEndpointProvider.cs b/OpenAI.SDK/EndpointProviders/IOpenAiEndpointProvider.cs index 66c25818..59668b55 100644 --- a/OpenAI.SDK/EndpointProviders/IOpenAiEndpointProvider.cs +++ b/OpenAI.SDK/EndpointProviders/IOpenAiEndpointProvider.cs @@ -52,7 +52,7 @@ internal interface IOpenAiEndpointProvider string ThreadModify(string threadId); string ThreadDelete(string threadId); string MessageCreate(string threadId); - string MessageRetrieve(string threadId,string messageId); + string MessageRetrieve(string threadId, string messageId); string MessageModify(string threadId, string messageId); string MessageList(string threadId, PaginationRequest? messageListRequest); string RunCreate(string threadId); @@ -62,7 +62,7 @@ internal interface IOpenAiEndpointProvider string RunSubmitToolOutputs(string threadId, string runId); string RunCancel(string threadId, string runId); string ThreadAndRunCreate(); - string RunStepRetrieve(string threadId, string runId,string stepId); + string RunStepRetrieve(string threadId, string runId, string stepId); string RunStepList(string threadId, string runId, PaginationRequest? runStepListRequest); string VectorStoreCreate(); string VectorStoreList(PaginationRequest baseListRequest); diff --git a/OpenAI.SDK/EndpointProviders/OpenAiEndpointProvider.cs b/OpenAI.SDK/EndpointProviders/OpenAiEndpointProvider.cs index 08f44592..027d00f3 100644 --- a/OpenAI.SDK/EndpointProviders/OpenAiEndpointProvider.cs +++ b/OpenAI.SDK/EndpointProviders/OpenAiEndpointProvider.cs @@ -1,5 +1,4 @@ using System.Net; -using System.Threading; using OpenAI.ObjectModels.RequestModels; namespace OpenAI.EndpointProviders; @@ -299,10 +298,12 @@ public string MessageList(string threadId, PaginationRequest? messageListRequest return url; } + public string MessageDelete(string threadId, string messageId) { return $"{_apiVersion}/threads/{threadId}/messages/{messageId}"; } + public string RunCreate(string threadId) { return $"{_apiVersion}/threads/{threadId}/runs"; @@ -452,6 +453,4 @@ public string VectorStoreFileBatchList(string vectorStoreId, string batchId, Pag return url; } - - } \ No newline at end of file diff --git a/OpenAI.SDK/Extensions/HttpclientExtensions.cs b/OpenAI.SDK/Extensions/HttpclientExtensions.cs index 93075a1c..31c2c543 100644 --- a/OpenAI.SDK/Extensions/HttpclientExtensions.cs +++ b/OpenAI.SDK/Extensions/HttpclientExtensions.cs @@ -111,7 +111,8 @@ private static HttpRequestMessage CreatePostEventStreamRequest(string uri, HttpC return await HandleResponseContent(response, cancellationToken); } - public static async Task<(string? stringResponse, TResponse baseResponse)> PostFileAndReadAsStringAsync(this HttpClient client, string uri, HttpContent content, CancellationToken cancellationToken = default) where TResponse : BaseResponse, new() + public static async Task<(string? stringResponse, TResponse baseResponse)> PostFileAndReadAsStringAsync(this HttpClient client, string uri, HttpContent content, CancellationToken cancellationToken = default) + where TResponse : BaseResponse, new() { var response = await client.PostAsync(uri, content, cancellationToken); if (response.IsSuccessStatusCode) @@ -121,7 +122,7 @@ private static HttpRequestMessage CreatePostEventStreamRequest(string uri, HttpC HttpStatusCode = response.StatusCode, HeaderValues = response.ParseHeaders() }; - return (await response.Content.ReadAsStringAsync(cancellationToken),tResponse ); + return (await response.Content.ReadAsStringAsync(cancellationToken), tResponse); } else { @@ -151,8 +152,7 @@ private static HttpRequestMessage CreatePostEventStreamRequest(string uri, HttpC } else { - result = await response.Content.ReadFromJsonAsync(cancellationToken: cancellationToken) ?? - throw new InvalidOperationException(); + result = await response.Content.ReadFromJsonAsync(cancellationToken: cancellationToken) ?? throw new InvalidOperationException(); } result.HttpStatusCode = response.StatusCode; @@ -163,7 +163,7 @@ private static HttpRequestMessage CreatePostEventStreamRequest(string uri, HttpC public static ResponseHeaderValues ParseHeaders(this HttpResponseMessage response) { - return new ResponseHeaderValues() + return new() { Date = response.Headers.Date, Connection = response.Headers.Connection?.ToString(), diff --git a/OpenAI.SDK/Extensions/ModelExtension.cs b/OpenAI.SDK/Extensions/ModelExtension.cs index e2df1048..4dcfe4ff 100644 --- a/OpenAI.SDK/Extensions/ModelExtension.cs +++ b/OpenAI.SDK/Extensions/ModelExtension.cs @@ -4,7 +4,7 @@ namespace OpenAI.Extensions; public static class ModelExtension { - public static void ProcessModelId(this IOpenAiModels.IModel modelFromObject, string? modelFromParameter, string? defaultModelId,bool allowNull =false) + public static void ProcessModelId(this IOpenAiModels.IModel modelFromObject, string? modelFromParameter, string? defaultModelId, bool allowNull = false) { if (allowNull) { diff --git a/OpenAI.SDK/Extensions/StreamHandleExtension.cs b/OpenAI.SDK/Extensions/StreamHandleExtension.cs index bc6a9c30..60c68a5c 100644 --- a/OpenAI.SDK/Extensions/StreamHandleExtension.cs +++ b/OpenAI.SDK/Extensions/StreamHandleExtension.cs @@ -8,11 +8,12 @@ namespace OpenAI.Extensions; public static class StreamHandleExtension { - public static async IAsyncEnumerable AsStream(this HttpResponseMessage response, bool justDataMode = true, [EnumeratorCancellation] CancellationToken cancellationToken = default) where TResponse : BaseResponse, new() + public static async IAsyncEnumerable AsStream(this HttpResponseMessage response, bool justDataMode = true, [EnumeratorCancellation] CancellationToken cancellationToken = default) + where TResponse : BaseResponse, new() { // Helper data in case we need to reassemble a multi-packet response ReassemblyContext ctx = new(); - + // Ensure that we parse headers only once to improve performance a little bit. var httpStatusCode = response.StatusCode; var headerValues = response.ParseHeaders(); diff --git a/OpenAI.SDK/Interfaces/IAssistantService.cs b/OpenAI.SDK/Interfaces/IAssistantService.cs index 72cf1176..48843585 100644 --- a/OpenAI.SDK/Interfaces/IAssistantService.cs +++ b/OpenAI.SDK/Interfaces/IAssistantService.cs @@ -10,11 +10,14 @@ public interface IAssistantService /// Create an assistant with a model and instructions. /// /// - /// ID of the model to use. You can use the List models API to see all of your available models, or see our Model overview for descriptions of them. + /// + /// ID of the model to use. You can use the List models API to see all of your available models, or + /// see our Model overview for descriptions of them. + /// /// /// Task AssistantCreate(AssistantCreateRequest request, string? modelId = null, CancellationToken cancellationToken = default); - + /// /// Returns a list of assistants. /// diff --git a/OpenAI.SDK/Interfaces/IAudioService.cs b/OpenAI.SDK/Interfaces/IAudioService.cs index fdfee32c..5ef6c2cd 100644 --- a/OpenAI.SDK/Interfaces/IAudioService.cs +++ b/OpenAI.SDK/Interfaces/IAudioService.cs @@ -32,6 +32,4 @@ public interface IAudioService /// Propagates notification that operations should be canceled. /// Task> CreateSpeech(AudioCreateSpeechRequest audioCreateSpeechRequest, CancellationToken cancellationToken = default); - - -} +} \ No newline at end of file diff --git a/OpenAI.SDK/Interfaces/IBatchService.cs b/OpenAI.SDK/Interfaces/IBatchService.cs index 230d1aaf..2de1feb2 100644 --- a/OpenAI.SDK/Interfaces/IBatchService.cs +++ b/OpenAI.SDK/Interfaces/IBatchService.cs @@ -28,5 +28,4 @@ public interface IBatchService /// /// The Batch object matching the specified ID. Task BatchCancel(string batchId, CancellationToken cancellationToken = default); - } \ No newline at end of file diff --git a/OpenAI.SDK/Interfaces/IChatCompletionService.cs b/OpenAI.SDK/Interfaces/IChatCompletionService.cs index 6ff0dc58..e051eefc 100644 --- a/OpenAI.SDK/Interfaces/IChatCompletionService.cs +++ b/OpenAI.SDK/Interfaces/IChatCompletionService.cs @@ -23,10 +23,13 @@ public interface IChatCompletionService /// /// The ID of the model to use for this request /// - /// Ignore stream lines if they don’t start with "data:". If you don't know what it means, probably you shouldn't change this. + /// + /// Ignore stream lines if they don’t start with "data:". If you don't know what it means, + /// probably you shouldn't change this. + /// /// Propagates notification that operations should be canceled. /// - IAsyncEnumerable CreateCompletionAsStream(ChatCompletionCreateRequest chatCompletionCreate, string? modelId = null, bool justDataMode = true,CancellationToken cancellationToken = default); + IAsyncEnumerable CreateCompletionAsStream(ChatCompletionCreateRequest chatCompletionCreate, string? modelId = null, bool justDataMode = true, CancellationToken cancellationToken = default); } public static class IChatCompletionServiceExtension diff --git a/OpenAI.SDK/Interfaces/IFineTuningJobService.cs b/OpenAI.SDK/Interfaces/IFineTuningJobService.cs index 457a0cf2..8990a8ea 100644 --- a/OpenAI.SDK/Interfaces/IFineTuningJobService.cs +++ b/OpenAI.SDK/Interfaces/IFineTuningJobService.cs @@ -25,7 +25,7 @@ public interface IFineTuningJobService /// /// Propagates notification that operations should be canceled. /// - Task ListFineTuningJobs(FineTuningJobListRequest? fineTuningJobListRequest =null,CancellationToken cancellationToken = default); + Task ListFineTuningJobs(FineTuningJobListRequest? fineTuningJobListRequest = null, CancellationToken cancellationToken = default); /// /// Gets info about the fine-tuning job. @@ -48,7 +48,8 @@ public interface IFineTuningJobService /// /// /// - /// Whether to stream events for the fine-tuning job. If set to true, events will be sent as data-only server-sent events + /// Whether to stream events for the fine-tuning job. If set to true, events will be sent as data-only server-sent + /// events /// as they become available. The stream will terminate with a data: [DONE] message when the job is finished /// (succeeded, cancelled, or failed). /// If set to false, only events generated so far will be returned. @@ -56,4 +57,4 @@ public interface IFineTuningJobService /// Propagates notification that operations should be canceled. /// Task ListFineTuningJobEvents(FineTuningJobListEventsRequest model, bool? stream = null, CancellationToken cancellationToken = default); -} +} \ No newline at end of file diff --git a/OpenAI.SDK/Interfaces/IImageService.cs b/OpenAI.SDK/Interfaces/IImageService.cs index 79940be4..e2bf6346 100644 --- a/OpenAI.SDK/Interfaces/IImageService.cs +++ b/OpenAI.SDK/Interfaces/IImageService.cs @@ -45,6 +45,6 @@ public static class IImageServiceExtension /// public static Task CreateImage(this IImageService service, string prompt, CancellationToken cancellationToken = default) { - return service.CreateImage(new ImageCreateRequest(prompt), cancellationToken); + return service.CreateImage(new(prompt), cancellationToken); } } \ No newline at end of file diff --git a/OpenAI.SDK/Interfaces/IModelService.cs b/OpenAI.SDK/Interfaces/IModelService.cs index d2c4c6b3..bbb56450 100644 --- a/OpenAI.SDK/Interfaces/IModelService.cs +++ b/OpenAI.SDK/Interfaces/IModelService.cs @@ -25,9 +25,9 @@ public interface IModelService /// Propagates notification that operations should be canceled. /// Task RetrieveModel(string model, CancellationToken cancellationToken = default); - + /// - /// Delete a fine-tuned model. You must have the Owner role in your organization to delete a model. + /// Delete a fine-tuned model. You must have the Owner role in your organization to delete a model. /// /// The model to delete /// diff --git a/OpenAI.SDK/Interfaces/IModerationService.cs b/OpenAI.SDK/Interfaces/IModerationService.cs index 9872718e..74686f21 100644 --- a/OpenAI.SDK/Interfaces/IModerationService.cs +++ b/OpenAI.SDK/Interfaces/IModerationService.cs @@ -35,7 +35,7 @@ public static class IModerationServiceExtension /// public static Task CreateModeration(this IModerationService service, string input, string? model = null, CancellationToken cancellationToken = default) { - return service.CreateModeration(new CreateModerationRequest + return service.CreateModeration(new() { Input = input, Model = model diff --git a/OpenAI.SDK/Interfaces/IOpenAIService.cs b/OpenAI.SDK/Interfaces/IOpenAIService.cs index 051e48db..318d44d9 100644 --- a/OpenAI.SDK/Interfaces/IOpenAIService.cs +++ b/OpenAI.SDK/Interfaces/IOpenAIService.cs @@ -29,7 +29,7 @@ public interface IOpenAIService public IFineTuneService FineTunes { get; } /// - /// Manage fine-tuning jobs to tailor a model to your specific training data. + /// Manage fine-tuning jobs to tailor a model to your specific training data. /// public IFineTuningJobService FineTuningJob { get; } @@ -54,13 +54,14 @@ public interface IOpenAIService /// Given an audio file, the model will return a transcription of the audio. /// public IAudioService Audio { get; } + /// - /// Create large batches of API requests to run asynchronously. + /// Create large batches of API requests to run asynchronously. /// - public IBatchService Batch{ get; } + public IBatchService Batch { get; } /// - /// Beta + /// Beta /// public IBetaService Beta { get; } diff --git a/OpenAI.SDK/Interfaces/IRunService.cs b/OpenAI.SDK/Interfaces/IRunService.cs index fa6dfc16..85c5c5dd 100644 --- a/OpenAI.SDK/Interfaces/IRunService.cs +++ b/OpenAI.SDK/Interfaces/IRunService.cs @@ -17,7 +17,7 @@ public interface IRunService Task RunCreate(string threadId, RunCreateRequest request, string? modelId = null, CancellationToken cancellationToken = default); /// - /// Create a run and stream the results. + /// Create a run and stream the results. /// /// /// @@ -61,7 +61,7 @@ public interface IRunService Task RunSubmitToolOutputs(string threadId, string runId, SubmitToolOutputsToRunRequest request, CancellationToken cancellationToken = default); /// - /// Submit tool outputs to run + /// Submit tool outputs to run /// /// When a run has the status: "requires_action" and required_action.type is submit_tool_outputs, /// this endpoint can be used to submit the outputs from the tool calls once they're all completed. @@ -75,26 +75,28 @@ public interface IRunService /// IAsyncEnumerable RunSubmitToolOutputsAsStream(string threadId, string runId, SubmitToolOutputsToRunRequest request, [EnumeratorCancellation] CancellationToken cancellationToken = default); - /// - /// Modifies a run. - /// - /// The ID of the [thread](/docs/api-reference/threads) that was run. - /// The ID of the run to modify. - /// - /// - /// - Task RunModify(string threadId, string runId, RunModifyRequest request, CancellationToken cancellationToken = default); + /// + /// Modifies a run. + /// + /// The ID of the [thread](/docs/api-reference/threads) that was run. + /// The ID of the run to modify. + /// + /// + /// + Task RunModify(string threadId, string runId, RunModifyRequest request, CancellationToken cancellationToken = default); /// - /// Create a thread and run it in one request. + /// Create a thread and run it in one request. /// Task CreateThreadAndRun(CreateThreadAndRunRequest requestBody, CancellationToken cancellationToken = default); + /// - /// Create a thread and run it in one request as Stream. + /// Create a thread and run it in one request as Stream. /// IAsyncEnumerable CreateThreadAndRunAsStream(CreateThreadAndRunRequest createThreadAndRunRequest, string? modelId = null, bool justDataMode = true, [EnumeratorCancellation] CancellationToken cancellationToken = default); + /// - /// Returns a list of runs belonging to a thread. + /// Returns a list of runs belonging to a thread. /// Task ListRuns(string threadId, PaginationRequest runListRequest, CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/OpenAI.SDK/Interfaces/IVectorStoreFiles.cs b/OpenAI.SDK/Interfaces/IVectorStoreFiles.cs index 4fbc03c8..020f6495 100644 --- a/OpenAI.SDK/Interfaces/IVectorStoreFiles.cs +++ b/OpenAI.SDK/Interfaces/IVectorStoreFiles.cs @@ -7,35 +7,45 @@ namespace OpenAI.Interfaces; public interface IVectorStoreFiles { /// - /// Returns a list of vector store files. + /// Returns a list of vector store files. /// Task ListVectorStoreFiles(string vectorStoreId, VectorStoreFileListRequest baseListRequest, CancellationToken cancellationToken = default); + /// - /// Create a vector store file by attaching a [File](/docs/api-reference/files) to a [vector store](/docs/api-reference/vector-stores/object). + /// Create a vector store file by attaching a [File](/docs/api-reference/files) to a [vector + /// store](/docs/api-reference/vector-stores/object). /// Task CreateVectorStoreFile(string vectorStoreId, CreateVectorStoreFileRequest requestBody, CancellationToken cancellationToken = default); + /// - /// Retrieves a vector store file. + /// Retrieves a vector store file. /// Task GetVectorStoreFile(string vectorStoreId, string fileId, CancellationToken cancellationToken = default); + /// - /// Delete a vector store file. This will remove the file from the vector store but the file itself will not be deleted. To delete the file, use the [delete file](/docs/api-reference/files/delete) endpoint. + /// Delete a vector store file. This will remove the file from the vector store but the file itself will not be + /// deleted. To delete the file, use the [delete file](/docs/api-reference/files/delete) endpoint. /// Task DeleteVectorStoreFile(string vectorStoreId, string fileId, CancellationToken cancellationToken = default); + /// - /// Create a vector store file batch. + /// Create a vector store file batch. /// Task CreateVectorStoreFileBatch(string vectorStoreId, CreateVectorStoreFileBatchRequest requestBody, CancellationToken cancellationToken = default); + /// - /// Retrieves a vector store file batch. + /// Retrieves a vector store file batch. /// Task GetVectorStoreFileBatch(string vectorStoreId, string batchId, CancellationToken cancellationToken = default); + /// - /// Cancel a vector store file batch. This attempts to cancel the processing of files in this batch as soon as possible. + /// Cancel a vector store file batch. This attempts to cancel the processing of files in this batch as soon as + /// possible. /// Task CancelVectorStoreFileBatch(string vectorStoreId, string batchId, CancellationToken cancellationToken = default); + /// - /// Returns a list of vector store files in a batch. + /// Returns a list of vector store files in a batch. /// Task ListFilesInVectorStoreBatch(string vectorStoreId, string batchId, PaginationRequest baseListRequest, CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/OpenAI.SDK/Interfaces/IVectorStores.cs b/OpenAI.SDK/Interfaces/IVectorStores.cs index 6259e8ee..31db1a52 100644 --- a/OpenAI.SDK/Interfaces/IVectorStores.cs +++ b/OpenAI.SDK/Interfaces/IVectorStores.cs @@ -7,24 +7,27 @@ namespace OpenAI.Interfaces; public interface IVectorStores { /// - /// Returns a list of vector stores. + /// Returns a list of vector stores. /// Task ListVectorStores(PaginationRequest request, CancellationToken cancellationToken = default); + /// - /// Create a vector store. + /// Create a vector store. /// Task CreateVectorStore(CreateVectorStoreRequest requestBody, CancellationToken cancellationToken = default); /// - /// Retrieves a vector store. + /// Retrieves a vector store. /// Task RetrieveVectorStore(string vectorStoreId, CancellationToken cancellationToken = default); + /// - /// Modifies a vector store. + /// Modifies a vector store. /// Task ModifyVectorStore(string vectorStoreId, UpdateVectorStoreRequest requestBody, CancellationToken cancellationToken = default); + /// - /// Delete a vector store. + /// Delete a vector store. /// Task DeleteVectorStore(string vectorStoreId, CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/OpenAI.SDK/Managers/OpenAIAudioService.cs b/OpenAI.SDK/Managers/OpenAIAudioService.cs index 123e21ad..3b671973 100644 --- a/OpenAI.SDK/Managers/OpenAIAudioService.cs +++ b/OpenAI.SDK/Managers/OpenAIAudioService.cs @@ -39,19 +39,11 @@ private async Task Create(AudioCreateTranscrip if (audioCreateTranscriptionRequest.File != null) { - multipartContent.Add( - new ByteArrayContent(audioCreateTranscriptionRequest.File), - "file", - audioCreateTranscriptionRequest.FileName - ); + multipartContent.Add(new ByteArrayContent(audioCreateTranscriptionRequest.File), "file", audioCreateTranscriptionRequest.FileName); } else if (audioCreateTranscriptionRequest.FileStream != null) { - multipartContent.Add( - new StreamContent(audioCreateTranscriptionRequest.FileStream), - "file", - audioCreateTranscriptionRequest.FileName - ); + multipartContent.Add(new StreamContent(audioCreateTranscriptionRequest.FileStream), "file", audioCreateTranscriptionRequest.FileName); } multipartContent.Add(new StringContent(audioCreateTranscriptionRequest.Model), "model"); @@ -85,8 +77,7 @@ private async Task Create(AudioCreateTranscrip } - if (null == audioCreateTranscriptionRequest.ResponseFormat || - StaticValues.AudioStatics.ResponseFormat.Json == audioCreateTranscriptionRequest.ResponseFormat || + if (null == audioCreateTranscriptionRequest.ResponseFormat || StaticValues.AudioStatics.ResponseFormat.Json == audioCreateTranscriptionRequest.ResponseFormat || StaticValues.AudioStatics.ResponseFormat.VerboseJson == audioCreateTranscriptionRequest.ResponseFormat) { return await _httpClient.PostFileAndReadAsAsync(uri, multipartContent, cancellationToken); @@ -99,6 +90,5 @@ private async Task Create(AudioCreateTranscrip } return response.baseResponse; - } } \ No newline at end of file diff --git a/OpenAI.SDK/Managers/OpenAIBatchService.cs b/OpenAI.SDK/Managers/OpenAIBatchService.cs index b87ac15b..8fc9aced 100644 --- a/OpenAI.SDK/Managers/OpenAIBatchService.cs +++ b/OpenAI.SDK/Managers/OpenAIBatchService.cs @@ -1,8 +1,8 @@ -using OpenAI.Extensions; +using System.Net.Http.Json; +using OpenAI.Extensions; using OpenAI.Interfaces; using OpenAI.ObjectModels.RequestModels; using OpenAI.ObjectModels.ResponseModels.BatchResponseModel; -using System.Net.Http.Json; namespace OpenAI.Managers; @@ -23,6 +23,6 @@ public async Task BatchCreate(BatchCreateRequest request, Cancell /// public async Task BatchCancel(string batchId, CancellationToken cancellationToken = default) { - return await _httpClient.PostAndReadAsAsync(_endpointProvider.BatchCancel(batchId),null, cancellationToken); + return await _httpClient.PostAndReadAsAsync(_endpointProvider.BatchCancel(batchId), null, cancellationToken); } } \ No newline at end of file diff --git a/OpenAI.SDK/Managers/OpenAIChatCompletions.cs b/OpenAI.SDK/Managers/OpenAIChatCompletions.cs index cb3e712f..baf2ded1 100644 --- a/OpenAI.SDK/Managers/OpenAIChatCompletions.cs +++ b/OpenAI.SDK/Managers/OpenAIChatCompletions.cs @@ -1,8 +1,6 @@ using System.Runtime.CompilerServices; -using System.Text.Json; using OpenAI.Extensions; using OpenAI.Interfaces; -using OpenAI.ObjectModels; using OpenAI.ObjectModels.RequestModels; using OpenAI.ObjectModels.ResponseModels; @@ -35,9 +33,6 @@ public async IAsyncEnumerable CreateCompletionAsSt yield break; } - await foreach (var baseResponse in response.AsStream(cancellationToken: cancellationToken)) yield return baseResponse; - + await foreach (var baseResponse in response.AsStream(cancellationToken: cancellationToken)) yield return baseResponse; } - - } \ No newline at end of file diff --git a/OpenAI.SDK/Managers/OpenAIFile.cs b/OpenAI.SDK/Managers/OpenAIFile.cs index 301c6f77..e1531c0c 100644 --- a/OpenAI.SDK/Managers/OpenAIFile.cs +++ b/OpenAI.SDK/Managers/OpenAIFile.cs @@ -21,8 +21,8 @@ public async Task UploadFile(string purpose, byte[] file, st { var multipartContent = new MultipartFormDataContent { - {new StringContent(purpose), "purpose"}, - {new ByteArrayContent(file), "file", fileName} + { new StringContent(purpose), "purpose" }, + { new ByteArrayContent(file), "file", fileName } }; return await _httpClient.PostFileAndReadAsAsync(_endpointProvider.FilesUpload(), multipartContent, cancellationToken); @@ -47,29 +47,29 @@ public async Task RetrieveFile(string fileId, CancellationToken ca if (typeof(T) == typeof(string)) { - return new FileContentResponse + return new() { - Content = (T) (object) await response.Content.ReadAsStringAsync(cancellationToken) + Content = (T)(object)await response.Content.ReadAsStringAsync(cancellationToken) }; } if (typeof(T) == typeof(byte[])) { - return new FileContentResponse + return new() { - Content = (T) (object) await response.Content.ReadAsByteArrayAsync(cancellationToken) + Content = (T)(object)await response.Content.ReadAsByteArrayAsync(cancellationToken) }; } if (typeof(T) == typeof(Stream)) { - return new FileContentResponse + return new() { - Content = (T) (object) await response.Content.ReadAsStreamAsync(cancellationToken) + Content = (T)(object)await response.Content.ReadAsStreamAsync(cancellationToken) }; } - return new FileContentResponse + return new() { Content = await response.Content.ReadFromJsonAsync(cancellationToken: cancellationToken) }; diff --git a/OpenAI.SDK/Managers/OpenAIFineTuningJob.cs b/OpenAI.SDK/Managers/OpenAIFineTuningJob.cs index 694d05b5..baa2fa9d 100644 --- a/OpenAI.SDK/Managers/OpenAIFineTuningJob.cs +++ b/OpenAI.SDK/Managers/OpenAIFineTuningJob.cs @@ -1,38 +1,35 @@ -using System.Net; +using System.Net.Http.Json; using OpenAI.Extensions; using OpenAI.Interfaces; using OpenAI.ObjectModels.RequestModels; using OpenAI.ObjectModels.ResponseModels.FineTuningJobResponseModels; -using System.Net.Http.Json; -namespace OpenAI.Managers +namespace OpenAI.Managers; + +public partial class OpenAIService : IFineTuningJobService { - public partial class OpenAIService : IFineTuningJobService + public async Task CreateFineTuningJob(FineTuningJobCreateRequest createFineTuningJobRequest, CancellationToken cancellationToken = default) { - public async Task CreateFineTuningJob(FineTuningJobCreateRequest createFineTuningJobRequest, CancellationToken cancellationToken = default) - { - return await _httpClient.PostAndReadAsAsync(_endpointProvider.FineTuningJobCreate(), createFineTuningJobRequest, cancellationToken); - } - - public async Task ListFineTuningJobs(FineTuningJobListRequest? fineTuningJobListRequest, CancellationToken cancellationToken = default) - { + return await _httpClient.PostAndReadAsAsync(_endpointProvider.FineTuningJobCreate(), createFineTuningJobRequest, cancellationToken); + } - return (await _httpClient.GetFromJsonAsync(_endpointProvider.FineTuningJobList(fineTuningJobListRequest), cancellationToken))!; - } + public async Task ListFineTuningJobs(FineTuningJobListRequest? fineTuningJobListRequest, CancellationToken cancellationToken = default) + { + return (await _httpClient.GetFromJsonAsync(_endpointProvider.FineTuningJobList(fineTuningJobListRequest), cancellationToken))!; + } - public async Task RetrieveFineTuningJob(string fineTuningJobId, CancellationToken cancellationToken = default) - { - return (await _httpClient.GetFromJsonAsync(_endpointProvider.FineTuningJobRetrieve(fineTuningJobId), cancellationToken))!; - } + public async Task RetrieveFineTuningJob(string fineTuningJobId, CancellationToken cancellationToken = default) + { + return (await _httpClient.GetFromJsonAsync(_endpointProvider.FineTuningJobRetrieve(fineTuningJobId), cancellationToken))!; + } - public async Task CancelFineTuningJob(string fineTuningJobId, CancellationToken cancellationToken = default) - { - return await _httpClient.PostAndReadAsAsync(_endpointProvider.FineTuningJobCancel(fineTuningJobId),null, cancellationToken: cancellationToken); - } + public async Task CancelFineTuningJob(string fineTuningJobId, CancellationToken cancellationToken = default) + { + return await _httpClient.PostAndReadAsAsync(_endpointProvider.FineTuningJobCancel(fineTuningJobId), null, cancellationToken); + } - public async Task ListFineTuningJobEvents(FineTuningJobListEventsRequest fineTuningJobRequestModel, bool? stream = null, CancellationToken cancellationToken = default) - { - return await _httpClient.GetStreamAsync(_endpointProvider.FineTuningJobListEvents(fineTuningJobRequestModel.FineTuningJobId), cancellationToken); - } + public async Task ListFineTuningJobEvents(FineTuningJobListEventsRequest fineTuningJobRequestModel, bool? stream = null, CancellationToken cancellationToken = default) + { + return await _httpClient.GetStreamAsync(_endpointProvider.FineTuningJobListEvents(fineTuningJobRequestModel.FineTuningJobId), cancellationToken); } -} +} \ No newline at end of file diff --git a/OpenAI.SDK/Managers/OpenAIMessageService.cs b/OpenAI.SDK/Managers/OpenAIMessageService.cs index b2265764..63a99f63 100644 --- a/OpenAI.SDK/Managers/OpenAIMessageService.cs +++ b/OpenAI.SDK/Managers/OpenAIMessageService.cs @@ -44,19 +44,19 @@ public async Task ListMessages(string threadId, PaginationR return await _httpClient.GetReadAsAsync(_endpointProvider.MessageList(threadId, request), cancellationToken); } - /// + /// public async Task RetrieveMessage(string threadId, string messageId, CancellationToken cancellationToken = default) { return await _httpClient.GetReadAsAsync(_endpointProvider.MessageRetrieve(threadId, messageId), cancellationToken); } - /// + /// public async Task ModifyMessage(string threadId, string messageId, ModifyMessageRequest requestBody, CancellationToken cancellationToken = default) { return await _httpClient.PostAndReadAsAsync(_endpointProvider.MessageModify(threadId, messageId), requestBody, cancellationToken); } - /// + /// public async Task DeleteMessage(string threadId, string messageId, CancellationToken cancellationToken = default) { return await _httpClient.DeleteAndReadAsAsync(_endpointProvider.MessageDelete(threadId, messageId), cancellationToken); diff --git a/OpenAI.SDK/Managers/OpenAIRunService.cs b/OpenAI.SDK/Managers/OpenAIRunService.cs index 8ce7abbb..5a7812cd 100644 --- a/OpenAI.SDK/Managers/OpenAIRunService.cs +++ b/OpenAI.SDK/Managers/OpenAIRunService.cs @@ -1,8 +1,8 @@ -using OpenAI.Extensions; +using System.Runtime.CompilerServices; +using OpenAI.Extensions; using OpenAI.Interfaces; using OpenAI.ObjectModels.RequestModels; using OpenAI.ObjectModels.SharedModels; -using System.Runtime.CompilerServices; namespace OpenAI.Managers; @@ -24,12 +24,11 @@ public async Task RunCreate(string threadId, RunCreateRequest reque throw new ArgumentNullException(nameof(threadId)); } - request.ProcessModelId(modelId, _defaultModelId,true); + request.ProcessModelId(modelId, _defaultModelId, true); return await _httpClient.PostAndReadAsAsync(_endpointProvider.RunCreate(threadId), request, cancellationToken); } /// - /// /// /// /// @@ -37,14 +36,13 @@ public async Task RunCreate(string threadId, RunCreateRequest reque /// /// /// - public async IAsyncEnumerable RunCreateAsStream(string threadId, RunCreateRequest request, string? modelId = null, bool justDataMode = true, - [EnumeratorCancellation] CancellationToken cancellationToken = default) + public async IAsyncEnumerable RunCreateAsStream(string threadId, RunCreateRequest request, string? modelId = null, bool justDataMode = true, [EnumeratorCancellation] CancellationToken cancellationToken = default) { // Mark the request as streaming request.Stream = true; // Send the request to the CompletionCreate endpoint - request.ProcessModelId(modelId, _defaultModelId,true); + request.ProcessModelId(modelId, _defaultModelId, true); using var response = _httpClient.PostAsStreamAsync(_endpointProvider.RunCreate(threadId), request, cancellationToken); @@ -55,10 +53,9 @@ public async IAsyncEnumerable RunCreateAsStream(string threadId, Ru } await foreach (var baseResponse in response.AsStream(cancellationToken: cancellationToken)) yield return baseResponse; - } - + /// public async Task RunModify(string threadId, string runId, RunModifyRequest request, CancellationToken cancellationToken = default) { @@ -66,10 +63,12 @@ public async Task RunModify(string threadId, string runId, RunModif { throw new ArgumentNullException(nameof(threadId)); } + if (string.IsNullOrWhiteSpace(runId)) { throw new ArgumentNullException(nameof(runId)); } + return await _httpClient.PostAndReadAsAsync(_endpointProvider.RunModify(threadId, runId), request, cancellationToken); } @@ -165,7 +164,7 @@ public async Task CreateThreadAndRun(CreateThreadAndRunRequest requ { return await _httpClient.PostAndReadAsAsync(_endpointProvider.ThreadAndRunCreate(), requestBody, cancellationToken); } - + public async IAsyncEnumerable CreateThreadAndRunAsStream(CreateThreadAndRunRequest createThreadAndRunRequest, string? modelId = null, bool justDataMode = true, [EnumeratorCancellation] CancellationToken cancellationToken = default) { @@ -173,7 +172,7 @@ public async IAsyncEnumerable CreateThreadAndRunAsStream(CreateThre createThreadAndRunRequest.Stream = true; // Send the request to the CompletionCreate endpoint - createThreadAndRunRequest.ProcessModelId(modelId, _defaultModelId,allowNull:true); + createThreadAndRunRequest.ProcessModelId(modelId, _defaultModelId, true); using var response = _httpClient.PostAsStreamAsync(_endpointProvider.ThreadAndRunCreate(), createThreadAndRunRequest, cancellationToken); @@ -184,13 +183,11 @@ public async IAsyncEnumerable CreateThreadAndRunAsStream(CreateThre } await foreach (var baseResponse in response.AsStream(cancellationToken: cancellationToken)) yield return baseResponse; - } - /// + /// public async Task ListRuns(string threadId, PaginationRequest runListRequest, CancellationToken cancellationToken = default) { return await _httpClient.GetReadAsAsync(_endpointProvider.RunList(threadId, runListRequest), cancellationToken); } - } \ No newline at end of file diff --git a/OpenAI.SDK/Managers/OpenAIRunStepService.cs b/OpenAI.SDK/Managers/OpenAIRunStepService.cs index 02d84e6a..997fb8a6 100644 --- a/OpenAI.SDK/Managers/OpenAIRunStepService.cs +++ b/OpenAI.SDK/Managers/OpenAIRunStepService.cs @@ -10,7 +10,7 @@ public partial class OpenAIService : IRunStepService /// public async Task RunStepsList(string threadId, string runId, PaginationRequest? request = null, CancellationToken cancellationToken = default) { - return await _httpClient.GetReadAsAsync(_endpointProvider.RunStepList(threadId, runId,request), cancellationToken); + return await _httpClient.GetReadAsAsync(_endpointProvider.RunStepList(threadId, runId, request), cancellationToken); } /// diff --git a/OpenAI.SDK/Managers/OpenAIService.cs b/OpenAI.SDK/Managers/OpenAIService.cs index c5cd91eb..74cbf178 100644 --- a/OpenAI.SDK/Managers/OpenAIService.cs +++ b/OpenAI.SDK/Managers/OpenAIService.cs @@ -13,8 +13,7 @@ public partial class OpenAIService : IOpenAIService, IDisposable private string? _defaultModelId; [ActivatorUtilitiesConstructor] - public OpenAIService(IOptions settings, HttpClient httpClient) - : this(settings.Value, httpClient) + public OpenAIService(IOptions settings, HttpClient httpClient) : this(settings.Value, httpClient) { } @@ -25,14 +24,14 @@ public OpenAIService(OpenAiOptions settings, HttpClient? httpClient = null) if (httpClient == null) { _disposeHttpClient = true; - _httpClient = new HttpClient(); + _httpClient = new(); } else { _httpClient = httpClient; } - _httpClient.BaseAddress = new Uri(settings.BaseDomain); + _httpClient.BaseAddress = new(settings.BaseDomain); switch (settings.ProviderType) { @@ -46,6 +45,7 @@ public OpenAIService(OpenAiOptions settings, HttpClient? httpClient = null) { _httpClient.DefaultRequestHeaders.Add("OpenAI-Beta", settings.Assistants); } + break; } @@ -105,7 +105,7 @@ public void Dispose() /// public IAudioService Audio => this; - + /// public IBatchService Batch => this; diff --git a/OpenAI.SDK/Managers/OpenAIThreadService.cs b/OpenAI.SDK/Managers/OpenAIThreadService.cs index a3b4b205..95143bf0 100644 --- a/OpenAI.SDK/Managers/OpenAIThreadService.cs +++ b/OpenAI.SDK/Managers/OpenAIThreadService.cs @@ -53,7 +53,7 @@ public async Task ThreadDelete(string threadId, Cancella return await _httpClient.DeleteAndReadAsAsync(_endpointProvider.ThreadDelete(threadId), cancellationToken); } - /// + /// public async Task ModifyThread(string threadId, ModifyThreadRequest requestBody, CancellationToken cancellationToken = default) { return await _httpClient.PostAndReadAsAsync(_endpointProvider.ThreadModify(threadId), requestBody, cancellationToken); diff --git a/OpenAI.SDK/Managers/OpenAIVectorStoreService.cs b/OpenAI.SDK/Managers/OpenAIVectorStoreService.cs index 1769afe4..a5146715 100644 --- a/OpenAI.SDK/Managers/OpenAIVectorStoreService.cs +++ b/OpenAI.SDK/Managers/OpenAIVectorStoreService.cs @@ -5,15 +5,16 @@ using OpenAI.ObjectModels.SharedModels; namespace OpenAI.Managers; + public partial class OpenAIService : IVectorStores { - /// + /// public async Task ListVectorStores(PaginationRequest request, CancellationToken cancellationToken = default) { return await _httpClient.GetReadAsAsync(_endpointProvider.VectorStoreList(request), cancellationToken); } - /// + /// public async Task CreateVectorStore(CreateVectorStoreRequest requestBody, CancellationToken cancellationToken = default) { return await _httpClient.PostAndReadAsAsync(_endpointProvider.VectorStoreCreate(), requestBody, cancellationToken); @@ -24,18 +25,19 @@ public async Task RetrieveVectorStore(string vectorSt return await _httpClient.GetReadAsAsync(_endpointProvider.VectorStoreRetrieve(vectorStoreId), cancellationToken); } - /// + /// public async Task ModifyVectorStore(string vectorStoreId, UpdateVectorStoreRequest requestBody, CancellationToken cancellationToken = default) { return await _httpClient.PostAndReadAsAsync(_endpointProvider.VectorStoreModify(vectorStoreId), requestBody, cancellationToken); } - /// + /// public async Task DeleteVectorStore(string vectorStoreId, CancellationToken cancellationToken = default) { return await _httpClient.DeleteAndReadAsAsync(_endpointProvider.VectorStoreDelete(vectorStoreId), cancellationToken); } } + public partial class OpenAIService : IVectorStoreFiles { public async Task ListVectorStoreFiles(string vectorStoreId, VectorStoreFileListRequest vectorStoreFileListRequest, CancellationToken cancellationToken = default) @@ -43,19 +45,19 @@ public async Task ListVectorStoreFiles(string vectorS return await _httpClient.GetReadAsAsync(_endpointProvider.VectorStoreFileList(vectorStoreId, vectorStoreFileListRequest), cancellationToken); } - /// + /// public async Task CreateVectorStoreFile(string vectorStoreId, CreateVectorStoreFileRequest requestBody, CancellationToken cancellationToken = default) { return await _httpClient.PostAndReadAsAsync(_endpointProvider.VectorStoreFileCreate(vectorStoreId), requestBody, cancellationToken); } - /// + /// public async Task GetVectorStoreFile(string vectorStoreId, string fileId, CancellationToken cancellationToken = default) { return await _httpClient.GetReadAsAsync(_endpointProvider.VectorStoreFileRetrieve(vectorStoreId, fileId), cancellationToken); } - /// + /// public async Task DeleteVectorStoreFile(string vectorStoreId, string fileId, CancellationToken cancellationToken = default) { return await _httpClient.DeleteAndReadAsAsync(_endpointProvider.VectorStoreFileDelete(vectorStoreId, fileId), cancellationToken); @@ -66,22 +68,22 @@ public async Task CreateVectorStoreFileBatch(string return await _httpClient.PostAndReadAsAsync(_endpointProvider.VectorStoreFileBatchCreate(vectorStoreId), requestBody, cancellationToken); } - /// + /// public async Task GetVectorStoreFileBatch(string vectorStoreId, string batchId, CancellationToken cancellationToken = default) { return await _httpClient.GetReadAsAsync(_endpointProvider.VectorStoreFileBatchRetrieve(vectorStoreId, batchId), cancellationToken); } - /// + /// public async Task CancelVectorStoreFileBatch(string vectorStoreId, string batchId, CancellationToken cancellationToken = default) { - return await _httpClient.PostAndReadAsAsync(_endpointProvider.VectorStoreFileBatchCancel(vectorStoreId, batchId), null,cancellationToken); + return await _httpClient.PostAndReadAsAsync(_endpointProvider.VectorStoreFileBatchCancel(vectorStoreId, batchId), null, cancellationToken); } - /// + /// public async Task ListFilesInVectorStoreBatch(string vectorStoreId, string batchId, PaginationRequest baseListRequest, CancellationToken cancellationToken = default) { return await _httpClient.GetReadAsAsync(_endpointProvider.VectorStoreFileBatchList(vectorStoreId, batchId, baseListRequest), cancellationToken); } -} +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/Converters.cs b/OpenAI.SDK/ObjectModels/Converters.cs index 8b63fb7c..ce6e74cb 100644 --- a/OpenAI.SDK/ObjectModels/Converters.cs +++ b/OpenAI.SDK/ObjectModels/Converters.cs @@ -68,8 +68,8 @@ public class AssistantsApiToolChoiceConverter : JsonConverter new() { AsString= reader.GetString() }, - JsonTokenType.StartObject => new() { AsObject= JsonSerializer.Deserialize(ref reader, options) }, + JsonTokenType.String => new() { AsString = reader.GetString() }, + JsonTokenType.StartObject => new() { AsObject = JsonSerializer.Deserialize(ref reader, options) }, _ => throw new JsonException() }; } diff --git a/OpenAI.SDK/ObjectModels/Models.cs b/OpenAI.SDK/ObjectModels/Models.cs index 6b170353..b5d6d242 100644 --- a/OpenAI.SDK/ObjectModels/Models.cs +++ b/OpenAI.SDK/ObjectModels/Models.cs @@ -71,12 +71,10 @@ public enum Model CodeDavinciV2, - [Obsolete("Use Gpt_3_5_Turbo instead")] - ChatGpt3_5Turbo, + [Obsolete("Use Gpt_3_5_Turbo instead")] ChatGpt3_5Turbo, Gpt_3_5_Turbo, - [Obsolete("Use Gpt_3_5_Turbo_0301 instead")] - ChatGpt3_5Turbo0301, + [Obsolete("Use Gpt_3_5_Turbo_0301 instead")] ChatGpt3_5Turbo0301, Gpt_3_5_Turbo_0301, Gpt_3_5_Turbo_16k, @@ -100,7 +98,7 @@ public enum Model Gpt_4_turbo_2024_04_09, Gpt_4o, Gpt_4o_2024_05_13, - + WhisperV1, Dall_e_2, @@ -111,7 +109,7 @@ public enum Model Text_moderation_007, Text_moderation_latest, - Text_moderation_stable, + Text_moderation_stable } public enum Subject @@ -175,22 +173,25 @@ public enum Subject public static string Gpt_4_32k_0613 => "gpt-4-32k-0613"; /// - /// The latest GPT-4 model with improved instruction following, JSON mode, reproducible outputs, parallel function calling, and more. + /// The latest GPT-4 model with improved instruction following, JSON mode, reproducible outputs, parallel function + /// calling, and more. /// Returns a maximum of 4,096 output tokens. This preview model is not yet suited for production traffic. /// 128,000 tokens Up to Apr 2023 /// public static string Gpt_4_1106_preview => "gpt-4-1106-preview"; public static string Gpt_4_0125_preview => "gpt-4-0125-preview"; + /// /// Ability to understand images, in addition to all other GPT-4 Turbo capabilties. - /// Returns a maximum of 4,096 output tokens. This is a preview model version and not suited yet for production traffic. + /// Returns a maximum of 4,096 output tokens. This is a preview model version and not suited yet for production + /// traffic. /// 128,000 tokens Up to Apr 2023 /// public static string Gpt_4_vision_preview => "gpt-4-vision-preview"; public static string Gpt_4_turbo_preview => "gpt-4-turbo-preview"; - + /// /// The latest GPT-4 Turbo model with vision capabilities. Vision requests can now use JSON mode and function calling. /// Currently points to gpt-4-turbo-2024-04-09 as of 04/09/2024. @@ -199,23 +200,23 @@ public enum Subject public static string Gpt_4_turbo => "gpt-4-turbo"; /// - /// GPT-4 Turbo with Vision model. Vision requests can now use JSON mode and function calling. + /// GPT-4 Turbo with Vision model. Vision requests can now use JSON mode and function calling. /// `gpt-4-turbo` currently points to this version. /// 128,000 tokens Up to Dec 2023 /// public static string Gpt_4_turbo_2024_04_09 => "gpt-4-turbo-2024-04-09"; - + /// - /// Our most advanced, multimodal flagship model that’s cheaper and faster than GPT-4 Turbo. - /// Currently points to gpt-4o-2024-05-13. - /// 128,000 tokens Up to Oct 2023 + /// Our most advanced, multimodal flagship model that’s cheaper and faster than GPT-4 Turbo. + /// Currently points to gpt-4o-2024-05-13. + /// 128,000 tokens Up to Oct 2023 /// public static string Gpt_4o => "gpt-4o"; - + /// - /// Our most advanced, multimodal flagship model that’s cheaper and faster than GPT-4 Turbo. - /// Currently points to gpt-4o-2024-05-13. - /// 128,000 tokens Up to Oct 2023 + /// Our most advanced, multimodal flagship model that’s cheaper and faster than GPT-4 Turbo. + /// Currently points to gpt-4o-2024-05-13. + /// 128,000 tokens Up to Oct 2023 /// public static string Gpt_4o_2024_05_13 => "gpt-4o-2024-05-13"; @@ -313,20 +314,23 @@ public enum Subject /// 4,096 tokens Up to Sep 2021 /// public static string Gpt_3_5_Turbo_0613 => "gpt-3.5-turbo-0613"; - + /// - /// The latest GPT-3.5 Turbo model with improved instruction following, JSON mode, reproducible outputs, parallel function calling, and more. + /// The latest GPT-3.5 Turbo model with improved instruction following, JSON mode, reproducible outputs, parallel + /// function calling, and more. /// 16,384 tokens Up to Sep 2021 /// public static string Gpt_3_5_Turbo_1106 => "gpt-3.5-turbo-1106"; public static string Gpt_3_5_Turbo_0125 => "gpt-3.5-turbo-0125"; + /// /// Snapshot of gpt-3.5-turbo from June 13th 2023 with function calling data. Unlike gpt-3.5-turbo, /// this model will not receive updates, and will be deprecated 3 months after a new version is released. /// 4,096 tokens Up to Sep 2021 /// public static string Gpt_3_5_Turbo_16k_0613 => "gpt-3.5-turbo-16k-0613"; + /// /// Similar capabilities as text-davinci-003 but compatible with legacy Completions endpoint and not Chat Completions. /// 4,096 tokens Up to Sep 2021 @@ -337,25 +341,27 @@ public enum Subject public static string WhisperV1 => "whisper-1"; /// - /// The previous DALL·E model released in Nov 2022. The 2nd iteration of DALL·E with more realistic, accurate, and 4x greater resolution images than the original model. + /// The previous DALL·E model released in Nov 2022. The 2nd iteration of DALL·E with more realistic, accurate, and 4x + /// greater resolution images than the original model. /// public static string Dall_e_2 => "dall-e-2"; + /// - /// The latest DALL·E model released in Nov 2023. + /// The latest DALL·E model released in Nov 2023. /// public static string Dall_e_3 => "dall-e-3"; /// - /// TTS is an AI model that converts text to natural sounding spoken text. - /// tts-1 is optimized for real time text to speech use cases. - /// Released in Nov 2023. + /// TTS is an AI model that converts text to natural sounding spoken text. + /// tts-1 is optimized for real time text to speech use cases. + /// Released in Nov 2023. /// public static string Tts_1 => "tts-1"; /// - /// TTS is an AI model that converts text to natural sounding spoken text. - /// tts-1-hd is optimized for quality - /// Released in Nov 2023. + /// TTS is an AI model that converts text to natural sounding spoken text. + /// tts-1-hd is optimized for quality + /// Released in Nov 2023. /// public static string Tts_1_hd => "tts-1-hd"; @@ -486,6 +492,7 @@ public static string EnumToString(this Subject subject, string? baseModel) _ => throw new ArgumentOutOfRangeException(nameof(subject), subject, null) }; } + return string.Format(subject switch { //{0}-{1} @@ -504,4 +511,4 @@ public static string EnumToString(this Subject subject, string? baseModel) _ => throw new ArgumentOutOfRangeException(nameof(subject), subject, null) }, baseModel); } -} +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/RequestModels/AssistantCreateRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/AssistantCreateRequest.cs index 05ac169d..2739517a 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/AssistantCreateRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/AssistantCreateRequest.cs @@ -70,7 +70,7 @@ public class AssistantCreateRequest : IOpenAiModels.IModel, IOpenAiModels.IMetaD /// about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of /// 512 characters long. /// - [JsonPropertyName("metadata")] + [JsonPropertyName("metadata")] public Dictionary? Metadata { get; set; } /// diff --git a/OpenAI.SDK/ObjectModels/RequestModels/AssistantModifyRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/AssistantModifyRequest.cs index 2d3f12b1..8a6dc7f2 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/AssistantModifyRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/AssistantModifyRequest.cs @@ -37,25 +37,6 @@ public class AssistantModifyRequest : IOpenAiModels.IModel, IOpenAiModels.IMetaD [JsonPropertyName("tool_resources")] public ToolResources? ToolResources { get; set; } - /// - /// Set of 16 key-value pairs that can be attached to an object. - /// - [JsonPropertyName("metadata")] - public Dictionary? Metadata { get; set; } - - /// - /// ID of the model to use - /// - [JsonPropertyName("model")] - public string Model { get; set; } - - /// - /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while - /// lower values like 0.2 will make it more focused and deterministic. - /// - [JsonPropertyName("temperature")] - public float? Temperature { get; set; } - /// /// An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the /// tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are @@ -81,4 +62,23 @@ public class AssistantModifyRequest : IOpenAiModels.IModel, IOpenAiModels.IMetaD /// [JsonPropertyName("response_format")] public ResponseFormatOneOfType? ResponseFormat { get; set; } + + /// + /// Set of 16 key-value pairs that can be attached to an object. + /// + [JsonPropertyName("metadata")] + public Dictionary? Metadata { get; set; } + + /// + /// ID of the model to use + /// + [JsonPropertyName("model")] + public string Model { get; set; } + + /// + /// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while + /// lower values like 0.2 will make it more focused and deterministic. + /// + [JsonPropertyName("temperature")] + public float? Temperature { get; set; } } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/RequestModels/AudioCreateSpeechRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/AudioCreateSpeechRequest.cs index 929eddc1..25df9f1c 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/AudioCreateSpeechRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/AudioCreateSpeechRequest.cs @@ -5,12 +5,6 @@ namespace OpenAI.ObjectModels.RequestModels; public record AudioCreateSpeechRequest : IOpenAiModels.IModel { - /// - /// ID of the model to use. One of the available TTS models: tts-1 or tts-1-hd - /// - [JsonPropertyName("model")] - public string Model { get; set; } - /// /// The text to generate audio for. The maximum length is 4096 characters. /// @@ -36,4 +30,10 @@ public record AudioCreateSpeechRequest : IOpenAiModels.IModel /// [JsonPropertyName("speed")] public float? Speed { get; set; } -} + + /// + /// ID of the model to use. One of the available TTS models: tts-1 or tts-1-hd + /// + [JsonPropertyName("model")] + public string Model { get; set; } +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/RequestModels/ChatCompletionCreateRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/ChatCompletionCreateRequest.cs index 0202d6a3..6a797985 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/ChatCompletionCreateRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/ChatCompletionCreateRequest.cs @@ -45,7 +45,7 @@ public enum ResponseFormats public bool? Stream { get; set; } /// - /// Options for streaming response. Only set this when you set : true. + /// Options for streaming response. Only set this when you set : true. /// [JsonPropertyName("stream_options")] public StreamOptions? StreamOptions { get; set; } @@ -129,13 +129,15 @@ public IList? StopCalculated public IList? Tools { get; set; } - [JsonIgnore] public object? ToolsAsObject { get; set; } + [JsonIgnore] + public object? ToolsAsObject { get; set; } /// /// A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list /// of functions the model may generate JSON inputs for. /// - [JsonPropertyName("tools")] public object? ToolsCalculated + [JsonPropertyName("tools")] + public object? ToolsCalculated { get { @@ -219,7 +221,7 @@ public ResponseFormats? ChatResponseFormat throw new ValidationException("ResponseFormat and ChatResponseFormat can not be assigned at the same time. One of them is should be null."); } - ResponseFormat = new ResponseFormat + ResponseFormat = new() { Type = value switch { @@ -239,6 +241,21 @@ public ResponseFormats? ChatResponseFormat [JsonPropertyName("seed")] public int? Seed { get; set; } + /// + /// Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each + /// output token returned in the content of message. + /// + [JsonPropertyName("logprobs")] + public bool? LogProbs { get; set; } + + + /// + /// An integer between 0 and 20 specifying the number of most likely tokens to return at each token position, each with + /// an associated log probability. logprobs must be set to true if this parameter is used. + /// + [JsonPropertyName("top_logprobs")] + public int? TopLogprobs { get; set; } + /// /// ID of the model to use. For models supported see start with Gpt_ /// @@ -263,17 +280,4 @@ public IEnumerable Validate() /// [JsonPropertyName("user")] public string User { get; set; } - - /// - /// Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the content of message. - /// - [JsonPropertyName("logprobs")] - public bool? LogProbs { get; set; } - - - /// - /// An integer between 0 and 20 specifying the number of most likely tokens to return at each token position, each with an associated log probability. logprobs must be set to true if this parameter is used. - /// - [JsonPropertyName("top_logprobs")] - public int? TopLogprobs { get; set; } } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/RequestModels/ChatMessage.cs b/OpenAI.SDK/ObjectModels/RequestModels/ChatMessage.cs index 3e3e1a71..5b41dbc3 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/ChatMessage.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/ChatMessage.cs @@ -58,9 +58,11 @@ public ChatMessage(string role, IList contents, string? name = n [JsonPropertyName("role")] public string Role { get; set; } - [JsonIgnore] public string? Content { get; set; } + [JsonIgnore] + public string? Content { get; set; } - [JsonIgnore] public IList? Contents { get; set; } + [JsonIgnore] + public IList? Contents { get; set; } /// /// The contents of the message. @@ -72,9 +74,7 @@ public object ContentCalculated { if (Content is not null && Contents is not null) { - throw new ValidationException( - "Content and Contents can not be assigned at the same time. One of them must be null." - ); + throw new ValidationException("Content and Contents can not be assigned at the same time. One of them must be null."); } if (Content is not null) diff --git a/OpenAI.SDK/ObjectModels/RequestModels/CompletionCreateRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/CompletionCreateRequest.cs index e33b3258..d8f28e14 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/CompletionCreateRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/CompletionCreateRequest.cs @@ -41,7 +41,7 @@ public IList? PromptCalculated if (Prompt != null) { - return new List {Prompt}; + return new List { Prompt }; } @@ -125,7 +125,7 @@ public IList? StopCalculated if (Stop != null) { - return new List {Stop}; + return new List { Stop }; } return StopAsList; @@ -184,7 +184,8 @@ public IList? StopCalculated [JsonPropertyName("logprobs")] public int? LogProbs { get; set; } - [JsonPropertyName("model")] public string? Model { get; set; } + [JsonPropertyName("model")] + public string? Model { get; set; } public IEnumerable Validate() { diff --git a/OpenAI.SDK/ObjectModels/RequestModels/CreateModerationRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/CreateModerationRequest.cs index cf623e16..f7cc3bb0 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/CreateModerationRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/CreateModerationRequest.cs @@ -31,7 +31,7 @@ public IList? InputCalculated if (Input != null) { - return new List {Input}; + return new List { Input }; } return InputAsList; diff --git a/OpenAI.SDK/ObjectModels/RequestModels/CreateThreadAndRunRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/CreateThreadAndRunRequest.cs index ce920599..7a6bd173 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/CreateThreadAndRunRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/CreateThreadAndRunRequest.cs @@ -3,25 +3,11 @@ namespace OpenAI.ObjectModels.RequestModels; -public class CreateThreadAndRunRequest : IOpenAiModels.IAssistantId,IOpenAiModels.IModel +public class CreateThreadAndRunRequest : IOpenAiModels.IAssistantId, IOpenAiModels.IModel { - /// - /// The ID of the [assistant](/docs/api-reference/assistants) to use to execute this run. - /// - [JsonPropertyName("assistant_id")] - public string AssistantId { get; set; } - [JsonPropertyName("thread")] public ThreadCreateRequest Thread { get; set; } - /// - /// The ID of the [Model](/docs/api-reference/models) to be used to execute this run. If a value is provided here, it - /// will override the model associated with the assistant. If not, the model associated with the assistant will be - /// used. - /// - [JsonPropertyName("model")] - public string Model { get; set; } - /// /// Override the default system message of the assistant. This is useful for modifying the behavior on a per-run basis. /// @@ -106,7 +92,7 @@ public class CreateThreadAndRunRequest : IOpenAiModels.IAssistantId,IOpenAiModel /// function", "function": {"name": "my_function"}}` forces the model to call that /// tool. /// - + [JsonPropertyName("tool_choice")] public AssistantsApiToolChoiceOneOfType ToolChoice { get; set; } @@ -124,8 +110,21 @@ public class CreateThreadAndRunRequest : IOpenAiModels.IAssistantId,IOpenAiModel [JsonPropertyName("response_format")] public ResponseFormatOneOfType ResponseFormat { get; set; } - + /// + /// The ID of the [assistant](/docs/api-reference/assistants) to use to execute this run. + /// + [JsonPropertyName("assistant_id")] + public string AssistantId { get; set; } + + /// + /// The ID of the [Model](/docs/api-reference/models) to be used to execute this run. If a value is provided here, it + /// will override the model associated with the assistant. If not, the model associated with the assistant will be + /// used. + /// + [JsonPropertyName("model")] + public string Model { get; set; } } + [JsonConverter(typeof(AssistantsApiToolChoiceConverter))] public class AssistantsApiToolChoiceOneOfType { @@ -133,7 +132,7 @@ public class AssistantsApiToolChoiceOneOfType public string? AsString { get; set; } [JsonIgnore] - public ToolChoice? AsObject{ get; set; } + public ToolChoice? AsObject { get; set; } } public class ToolResources @@ -143,17 +142,19 @@ public class ToolResources [JsonPropertyName("file_search")] public FileSearch FileSearch { get; set; } - } + public class FileSearch { /// - /// The vector store attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. + /// The vector store attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. /// [JsonPropertyName("vector_store_ids")] public List? VectorStoreIds { get; set; } + /// - /// A helper to create a vector store with file_ids and attach it to this assistant. There can be a maximum of 1 vector store attached to the assistant. + /// A helper to create a vector store with file_ids and attach it to this assistant. There can be a maximum of 1 vector + /// store attached to the assistant. /// [JsonPropertyName("vector_stores")] public List? VectorStores { get; set; } @@ -162,28 +163,34 @@ public class FileSearch public class VectorStores : IOpenAiModels.IFileIds, IOpenAiModels.IMetaData { /// - /// A list of file IDs to add to the vector store. There can be a maximum of 10000 files in a vector store. + /// A list of file IDs to add to the vector store. There can be a maximum of 10000 files in a vector store. /// [JsonPropertyName("file_ids")] public List? FileIds { get; set; } + /// - /// Set of 16 key-value pairs that can be attached to a vector store. This can be useful for storing additional information about the vector store in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. + /// Set of 16 key-value pairs that can be attached to a vector store. This can be useful for storing additional + /// information about the vector store in a structured format. Keys can be a maximum of 64 characters long and values + /// can be a maxium of 512 characters long. /// [JsonPropertyName("metadata")] public Dictionary? Metadata { get; set; } } + public class CodeInterpreter : IOpenAiModels.IFileIds { /// - /// A list of file IDs made available to the code_interpreter tool. There can be a maximum of 20 files associated with the tool. + /// A list of file IDs made available to the code_interpreter tool. There can be a maximum of 20 files associated with + /// the tool. /// [JsonPropertyName("file_ids")] public List? FileIds { get; set; } } + public class ToolsItem { /// - /// The type of the tool. Currently, only `function` is supported. + /// The type of the tool. Currently, only `function` is supported. /// [JsonPropertyName("type")] public string Type { get; set; } @@ -195,19 +202,20 @@ public class ToolsItem public class Function { /// - /// The name of the function. + /// The name of the function. /// [JsonPropertyName("name")] public string Name { get; set; } /// - /// The arguments passed to the function. + /// The arguments passed to the function. /// [JsonPropertyName("arguments")] public string Arguments { get; set; } /// - /// The output of the function. This will be `null` if the outputs have not been [submitted](/docs/api-reference/runs/submitToolOutputs) yet. + /// The output of the function. This will be `null` if the outputs have not been + /// [submitted](/docs/api-reference/runs/submitToolOutputs) yet. /// [JsonPropertyName("output")] public string? Output { get; set; } diff --git a/OpenAI.SDK/ObjectModels/RequestModels/CreateVectorStoreFileBatchRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/CreateVectorStoreFileBatchRequest.cs index 6a41fce0..f8d6f076 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/CreateVectorStoreFileBatchRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/CreateVectorStoreFileBatchRequest.cs @@ -5,7 +5,8 @@ namespace OpenAI.ObjectModels.RequestModels; public class CreateVectorStoreFileBatchRequest { /// - /// A list of [File](/docs/api-reference/files) IDs that the vector store should use. Useful for tools like `file_search` that can access files. + /// A list of [File](/docs/api-reference/files) IDs that the vector store should use. Useful for tools like + /// `file_search` that can access files. /// [JsonPropertyName("file_ids")] public List FileIds { get; set; } diff --git a/OpenAI.SDK/ObjectModels/RequestModels/CreateVectorStoreFileRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/CreateVectorStoreFileRequest.cs index dda5bb63..573c321b 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/CreateVectorStoreFileRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/CreateVectorStoreFileRequest.cs @@ -5,7 +5,8 @@ namespace OpenAI.ObjectModels.RequestModels; public class CreateVectorStoreFileRequest { /// - /// A [File](/docs/api-reference/files) ID that the vector store should use. Useful for tools like `file_search` that can access files. + /// A [File](/docs/api-reference/files) ID that the vector store should use. Useful for tools like `file_search` that + /// can access files. /// [JsonPropertyName("file_id")] public string FileId { get; set; } diff --git a/OpenAI.SDK/ObjectModels/RequestModels/CreateVectorStoreRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/CreateVectorStoreRequest.cs index 97be4978..4ac72e88 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/CreateVectorStoreRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/CreateVectorStoreRequest.cs @@ -6,25 +6,28 @@ namespace OpenAI.ObjectModels.RequestModels; public class CreateVectorStoreRequest { /// - /// A list of [File](/docs/api-reference/files) IDs that the vector store should use. Useful for tools like `file_search` that can access files. + /// A list of [File](/docs/api-reference/files) IDs that the vector store should use. Useful for tools like + /// `file_search` that can access files. /// [JsonPropertyName("file_ids")] public List? FileIds { get; set; } /// - /// The name of the vector store. + /// The name of the vector store. /// [JsonPropertyName("name")] public string? Name { get; set; } /// - /// The expiration policy for a vector store. + /// The expiration policy for a vector store. /// [JsonPropertyName("expires_after")] public ExpiresAfter? ExpiresAfter { get; set; } /// - /// Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. + /// Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information + /// about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of + /// 512 characters long. /// [JsonPropertyName("metadata")] public Dictionary? Metadata { get; set; } diff --git a/OpenAI.SDK/ObjectModels/RequestModels/EditCreateRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/EditCreateRequest.cs index c6371e87..ec4306cd 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/EditCreateRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/EditCreateRequest.cs @@ -43,7 +43,8 @@ public record EditCreateRequest : IModelValidate, IOpenAiModels.ITemperature, IO public float? TopP { get; set; } - [JsonPropertyName("model")] public string? Model { get; set; } + [JsonPropertyName("model")] + public string? Model { get; set; } public IEnumerable Validate() { diff --git a/OpenAI.SDK/ObjectModels/RequestModels/EmbeddingCreateRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/EmbeddingCreateRequest.cs index 4b5d7d1c..2c3035bc 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/EmbeddingCreateRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/EmbeddingCreateRequest.cs @@ -44,7 +44,7 @@ public IList? InputCalculated if (Input != null) { - return new List {Input}; + return new List { Input }; } return InputAsList; @@ -52,27 +52,28 @@ public IList? InputCalculated } /// - /// ID of the model to use. You can use the [List models](/docs/api-reference/models/list) API to see all of your - /// available models, or see our [Model overview](/docs/models/overview) for descriptions of them. - /// - /// - [JsonPropertyName("model")] - public string? Model { get; set; } - - /// - /// The number of dimensions the resulting output embeddings should have. Only supported in text-embedding-3 and later models. + /// The number of dimensions the resulting output embeddings should have. Only supported in text-embedding-3 and later + /// models. /// /// [JsonPropertyName("dimensions")] public int? Dimensions { get; set; } /// - /// The format to return the embeddings in. Can be either float or base64. + /// The format to return the embeddings in. Can be either float or base64. /// /// [JsonPropertyName("encoding_format")] public string? EncodingFormat { get; set; } + /// + /// ID of the model to use. You can use the [List models](/docs/api-reference/models/list) API to see all of your + /// available models, or see our [Model overview](/docs/models/overview) for descriptions of them. + /// + /// + [JsonPropertyName("model")] + public string? Model { get; set; } + public IEnumerable Validate() { throw new NotImplementedException(); diff --git a/OpenAI.SDK/ObjectModels/RequestModels/FineTuneCancelRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/FineTuneCancelRequest.cs index a1c96604..920c75ab 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/FineTuneCancelRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/FineTuneCancelRequest.cs @@ -4,5 +4,6 @@ namespace OpenAI.ObjectModels.RequestModels; public record FineTuneCancelRequest { - [JsonPropertyName("fine_tune_id")] public string FineTuneId { get; set; } + [JsonPropertyName("fine_tune_id")] + public string FineTuneId { get; set; } } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/RequestModels/FineTuningJobListEventsRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/FineTuningJobListEventsRequest.cs index e788c1d8..dedf4dbc 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/FineTuningJobListEventsRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/FineTuningJobListEventsRequest.cs @@ -1,29 +1,28 @@ using System.Text.Json.Serialization; -namespace OpenAI.ObjectModels.RequestModels +namespace OpenAI.ObjectModels.RequestModels; + +public class FineTuningJobListEventsRequest : FineTuningJobListRequest { - public class FineTuningJobListEventsRequest:FineTuningJobListRequest - { - /// - /// The ID of the fine-tuning job to get events for. - /// - [JsonIgnore] - public string FineTuningJobId { get; set; } - } + /// + /// The ID of the fine-tuning job to get events for. + /// + [JsonIgnore] + public string FineTuningJobId { get; set; } +} - public class FineTuningJobListRequest - { - /// - /// Identifier for the last job from the previous pagination request. - /// - [JsonPropertyName("after")] - public string? After { get; set; } +public class FineTuningJobListRequest +{ + /// + /// Identifier for the last job from the previous pagination request. + /// + [JsonPropertyName("after")] + public string? After { get; set; } - /// - /// Number of fine-tuning jobs to retrieve. - /// Defaults to 20. - /// - [JsonPropertyName("limit")] - public int? Limit { get; set; } - } -} + /// + /// Number of fine-tuning jobs to retrieve. + /// Defaults to 20. + /// + [JsonPropertyName("limit")] + public int? Limit { get; set; } +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/RequestModels/ImageCreateRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/ImageCreateRequest.cs index 2fd7d6a0..374d43d9 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/ImageCreateRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/ImageCreateRequest.cs @@ -18,25 +18,27 @@ public ImageCreateRequest(string prompt) } /// - /// A text description of the desired image(s). The maximum length is 1000 characters for dall-e-2 and 4000 characters for dall-e-3 + /// A text description of the desired image(s). The maximum length is 1000 characters for dall-e-2 and 4000 characters + /// for dall-e-3 /// [JsonPropertyName("prompt")] public string Prompt { get; set; } /// /// The quality of the image that will be generated. Possible values are 'standard' or 'hd' (default is 'standard'). - /// Hd creates images with finer details and greater consistency across the image. + /// Hd creates images with finer details and greater consistency across the image. /// This param is only supported for dall-e-3 model. - ///

Check for possible values + ///

Check for possible values ///
[JsonPropertyName("quality")] public string? Quality { get; set; } /// - /// The style of the generated images. Must be one of vivid or natural. - /// Vivid causes the model to lean towards generating hyper-real and dramatic images. - /// Natural causes the model to produce more natural, less hyper-real looking images. This param is only supported for dall-e-3. - ///

Check for possible values + /// The style of the generated images. Must be one of vivid or natural. + /// Vivid causes the model to lean towards generating hyper-real and dramatic images. + /// Natural causes the model to produce more natural, less hyper-real looking images. This param is only supported for + /// dall-e-3. + ///

Check for possible values ///
[JsonPropertyName("style")] public string? Style { get; set; } diff --git a/OpenAI.SDK/ObjectModels/RequestModels/MessageContent.cs b/OpenAI.SDK/ObjectModels/RequestModels/MessageContent.cs index 41ecb786..2c75d6dc 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/MessageContent.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/MessageContent.cs @@ -9,7 +9,6 @@ public class MessageContent { /// /// The value of Type property must be one of "text", "image_url" - /// /// note: Currently openAI doesn't support images in the first system message. /// [JsonPropertyName("type")] @@ -31,8 +30,8 @@ public class MessageContent public MessageImageFile? ImageFile { get; set; } /// - /// Static helper method to create MessageContent Text - /// The text content + /// Static helper method to create MessageContent Text + /// The text content /// public static MessageContent TextContent(string text) { @@ -40,10 +39,10 @@ public static MessageContent TextContent(string text) } /// - /// Static helper method to create MessageContent with Url - /// OpenAI currently supports PNG, JPEG, WEBP, and non-animated GIF - /// The url of an image - /// The detail property + /// Static helper method to create MessageContent with Url + /// OpenAI currently supports PNG, JPEG, WEBP, and non-animated GIF + /// The url of an image + /// The detail property /// public static MessageContent ImageUrlContent(string imageUrl, string? detail = null) { @@ -62,31 +61,24 @@ public static MessageContent ImageFileContent(string fileId, string detail) ImageFile = new() { FileId = fileId, Detail = detail } }; } + /// - /// Static helper method to create MessageContent from binary image - /// OpenAI currently supports PNG, JPEG, WEBP, and non-animated GIF - /// The image binary data as byte array - /// The type of image - /// The detail property + /// Static helper method to create MessageContent from binary image + /// OpenAI currently supports PNG, JPEG, WEBP, and non-animated GIF + /// The image binary data as byte array + /// The type of image + /// The detail property /// - public static MessageContent ImageBinaryContent( - byte[] binaryImage, - string imageType, - string? detail = "auto" - ) + public static MessageContent ImageBinaryContent(byte[] binaryImage, string imageType, string? detail = "auto") { return new() { Type = "image_url", ImageUrl = new() { - Url = string.Format( - "data:image/{0};base64,{1}", - imageType, - Convert.ToBase64String(binaryImage) - ), + Url = string.Format("data:image/{0};base64,{1}", imageType, Convert.ToBase64String(binaryImage)), Detail = detail } }; } -} +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/RequestModels/MessageCreateRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/MessageCreateRequest.cs index aad15c49..533eaccc 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/MessageCreateRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/MessageCreateRequest.cs @@ -1,5 +1,4 @@ -using System.Text.Json; -using System.Text.Json.Serialization; +using System.Text.Json.Serialization; using OpenAI.ObjectModels.SharedModels; namespace OpenAI.ObjectModels.RequestModels; @@ -17,6 +16,7 @@ public MessageCreateRequest(string role, MessageContentOneOfType content, List /// The role of the entity that is creating the message. /// Currently only user is supported. @@ -28,11 +28,11 @@ public MessageCreateRequest(string role, MessageContentOneOfType content, List [JsonPropertyName("content")] - + public MessageContentOneOfType Content { get; set; } /// - ///A list of files attached to the message, and the tools they should be added to. + /// A list of files attached to the message, and the tools they should be added to. /// [JsonPropertyName("attachments")] public List? Attachments { get; set; } @@ -49,15 +49,19 @@ public MessageCreateRequest(string role, MessageContentOneOfType content, List - /// The ID of the file to attach. See list of supported file extensions . + /// The ID of the file to attach. + /// + /// See list of supported file + /// extensions + /// + /// . /// [JsonPropertyName("file_id")] public string FileId { get; set; } /// - /// The tools to add this file to. + /// The tools to add this file to. /// [JsonPropertyName("tools")] public List Tools { get; set; } -} - +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/RequestModels/ModifyMessageRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/ModifyMessageRequest.cs index 129a6fb0..db867328 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/ModifyMessageRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/ModifyMessageRequest.cs @@ -5,7 +5,9 @@ namespace OpenAI.ObjectModels.RequestModels; public class ModifyMessageRequest { /// - /// Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. + /// Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information + /// about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of + /// 512 characters long. /// [JsonPropertyName("metadata")] public Dictionary? Metadata { get; set; } diff --git a/OpenAI.SDK/ObjectModels/RequestModels/RunModifyRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/RunModifyRequest.cs index e12b4a02..124571ae 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/RunModifyRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/RunModifyRequest.cs @@ -3,7 +3,7 @@ namespace OpenAI.ObjectModels.RequestModels; -public class RunModifyRequest:IOpenAiModels.IMetaData +public class RunModifyRequest : IOpenAiModels.IMetaData { /// /// Set of 16 key-value pairs that can be attached to an object. diff --git a/OpenAI.SDK/ObjectModels/RequestModels/StreamOptions.cs b/OpenAI.SDK/ObjectModels/RequestModels/StreamOptions.cs index a870001b..172cebd3 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/StreamOptions.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/StreamOptions.cs @@ -8,11 +8,12 @@ namespace OpenAI.ObjectModels.RequestModels; public sealed class StreamOptions { /// - /// If set, an additional chunk will be streamed before the done message. + /// If set, an additional chunk will be streamed before the done message. /// /// - /// This usage field on this chunk shows the token usage statistics for the entire request, and the choices field will always be an empty array. + /// This usage field on this chunk shows the token usage statistics for the entire request, and the choices field will + /// always be an empty array. /// [JsonPropertyName("include_usage")] public bool IncludeUsage { get; set; } -} +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/RequestModels/SubmitToolOutputsToRunRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/SubmitToolOutputsToRunRequest.cs index 1e86de06..54ccbc9b 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/SubmitToolOutputsToRunRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/SubmitToolOutputsToRunRequest.cs @@ -13,7 +13,8 @@ public class SubmitToolOutputsToRunRequest public List ToolOutputs { get; set; } /// - /// If true, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a data: [DONE] message. + /// If true, returns a stream of events that happen during the Run as server-sent events, terminating when the Run + /// enters a terminal state with a data: [DONE] message. /// [JsonPropertyName("stream")] public bool? Stream { get; set; } diff --git a/OpenAI.SDK/ObjectModels/RequestModels/ToolChoiceFunction.cs b/OpenAI.SDK/ObjectModels/RequestModels/ToolChoiceFunction.cs index 1f4dbfc7..d8260b72 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/ToolChoiceFunction.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/ToolChoiceFunction.cs @@ -7,14 +7,6 @@ public class ToolChoice { public static ToolChoice None => new() { Type = StaticValues.CompletionStatics.ToolChoiceType.None }; public static ToolChoice Auto => new() { Type = StaticValues.CompletionStatics.ToolChoiceType.Auto }; - public static ToolChoice FunctionChoice(string functionName) => new() - { - Type = StaticValues.CompletionStatics.ToolChoiceType.Function, - Function = new FunctionTool() - { - Name = functionName - } - }; /// /// "none" is the default when no functions are present.
@@ -26,21 +18,34 @@ public class ToolChoice [JsonPropertyName("type")] public string Type { get; set; } - [JsonPropertyName("function")] public FunctionTool? Function { get; set; } + [JsonPropertyName("function")] + public FunctionTool? Function { get; set; } + + public static ToolChoice FunctionChoice(string functionName) + { + return new() + { + Type = StaticValues.CompletionStatics.ToolChoiceType.Function, + Function = new() + { + Name = functionName + } + }; + } public class FunctionTool { - [JsonPropertyName("name")] public string Name { get; set; } + [JsonPropertyName("name")] + public string Name { get; set; } } } - [JsonConverter(typeof(ToolChoiceOneOfTypeConverter))] public class ToolChoiceOneOfType { public ToolChoiceOneOfType(string toolChoiceAsString) { - AsString = toolChoiceAsString; + AsString = toolChoiceAsString; } public ToolChoiceOneOfType(ToolChoice toolChoiceAsObject) @@ -86,5 +91,4 @@ public override void Write(Utf8JsonWriter writer, ToolChoiceOneOfType? value, Js } } } -} - +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/RequestModels/ToolDefinition.cs b/OpenAI.SDK/ObjectModels/RequestModels/ToolDefinition.cs index 59ae1f57..2877e693 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/ToolDefinition.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/ToolDefinition.cs @@ -14,14 +14,14 @@ public class ToolDefinition [JsonPropertyName("type")] public string Type { get; set; } - + /// /// A list of functions the model may generate JSON inputs for. /// [JsonIgnore] public FunctionDefinition? Function { get; set; } - [JsonIgnore] + [JsonIgnore] public object? FunctionsAsObject { get; set; } /// @@ -41,26 +41,37 @@ public object? FunctionCalculated } } - public static ToolDefinition DefineFunction(FunctionDefinition function) => new() + public static ToolDefinition DefineFunction(FunctionDefinition function) { - Type = StaticValues.CompletionStatics.ToolType.Function, - Function = function - }; + return new() + { + Type = StaticValues.CompletionStatics.ToolType.Function, + Function = function + }; + } - public static ToolDefinition DefineCodeInterpreter() => new() + public static ToolDefinition DefineCodeInterpreter() { - Type = StaticValues.AssistantsStatics.ToolCallTypes.CodeInterpreter, - }; + return new() + { + Type = StaticValues.AssistantsStatics.ToolCallTypes.CodeInterpreter + }; + } [Obsolete("Retrieval is now called FileSearch")] - public static ToolDefinition DefineRetrieval() => new() + public static ToolDefinition DefineRetrieval() { - Type = StaticValues.AssistantsStatics.ToolCallTypes.FileSearch, - }; + return new() + { + Type = StaticValues.AssistantsStatics.ToolCallTypes.FileSearch + }; + } - public static ToolDefinition DefineFileSearch() => new() + public static ToolDefinition DefineFileSearch() { - Type = StaticValues.AssistantsStatics.ToolCallTypes.FileSearch, - }; - + return new() + { + Type = StaticValues.AssistantsStatics.ToolCallTypes.FileSearch + }; + } } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/RequestModels/UpdateVectorStoreRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/UpdateVectorStoreRequest.cs index 84c72f0c..b44199e7 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/UpdateVectorStoreRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/UpdateVectorStoreRequest.cs @@ -6,19 +6,21 @@ namespace OpenAI.ObjectModels.RequestModels; public class UpdateVectorStoreRequest { /// - /// The name of the vector store. + /// The name of the vector store. /// [JsonPropertyName("name")] public string? Name { get; set; } /// - /// The expiration policy for a vector store. + /// The expiration policy for a vector store. /// [JsonPropertyName("expires_after")] public ExpiresAfter ExpiresAfter { get; set; } /// - /// Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. + /// Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information + /// about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of + /// 512 characters long. /// [JsonPropertyName("metadata")] public Dictionary? Metadata { get; set; } diff --git a/OpenAI.SDK/ObjectModels/RequestModels/VisionImageUrl.cs b/OpenAI.SDK/ObjectModels/RequestModels/VisionImageUrl.cs index 2175ccf3..efee5ba5 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/VisionImageUrl.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/VisionImageUrl.cs @@ -9,42 +9,47 @@ public class MessageImageUrl { /// /// The Url property - /// Images are made available to the model in two main ways: by passing a link to the image or by passing the base64 encoded image directly in the url property. - /// link example: "url" : "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg" + /// Images are made available to the model in two main ways: by passing a link to the image or by passing the base64 + /// encoded image directly in the url property. + /// link example: "url" : + /// "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg" /// base64 encoded image example: "url" : "data:image/jpeg;base64,{base64_image}" - /// /// Limitations: - /// OpenAI currently supports PNG (.png), JPEG (.jpeg and .jpg), WEBP (.webp), and non-animated GIF (.gif) image formats + /// OpenAI currently supports PNG (.png), JPEG (.jpeg and .jpg), WEBP (.webp), and non-animated GIF (.gif) image + /// formats /// Image upload size is limited to 20MB per image /// Captcha submission is blocked - /// /// [JsonPropertyName("url")] public string Url { get; set; } /// - /// The optional Detail property controls low or high fidelity image understanding - /// It has three options, low, high, or auto, you have control over how the model processes the image and generates its textual understanding. - /// By default, the model will use the auto setting which will look at the image input size and decide if it should use the low or high setting. - /// - /// low will disable the “high res” model. The model will receive a low-res 512px x 512px version of the image. - /// high will enable “high res” mode, which first allows the model to see the low res image and then creates detailed crops of input images - /// as 512px squares based on the input image size. + /// The optional Detail property controls low or high fidelity image understanding + /// It has three options, low, high, or auto, you have control over how the model processes the image and generates its + /// textual understanding. + /// By default, the model will use the auto setting which will look at the image input size and decide if it should use + /// the low or high setting. + /// low will disable the “high res” model. The model will receive a low-res 512px x 512px version of the image. + /// high will enable “high res” mode, which first allows the model to see the low res image and then creates detailed + /// crops of input images + /// as 512px squares based on the input image size. /// [JsonPropertyName("detail")] public string? Detail { get; set; } - } public class MessageImageFile { /// - /// The File ID of the image in the message content. Set purpose="vision" when uploading the File if you need to later display the file content. + /// The File ID of the image in the message content. Set purpose="vision" when uploading the File if you need to later + /// display the file content. /// [JsonPropertyName("file_id")] public string FileId { get; set; } + /// - /// Specifies the detail level of the image if specified by the user. low uses fewer tokens, you can opt in to high resolution using high. + /// Specifies the detail level of the image if specified by the user. low uses fewer tokens, you can opt in to high + /// resolution using high. /// [JsonPropertyName("detail")] public string Detail { get; set; } diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/AudioCreateTranscriptionResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/AudioCreateTranscriptionResponse.cs index 6b04a9ba..b500b2d8 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/AudioCreateTranscriptionResponse.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/AudioCreateTranscriptionResponse.cs @@ -4,50 +4,69 @@ namespace OpenAI.ObjectModels.ResponseModels; public record AudioCreateTranscriptionResponse : BaseResponse { - [JsonPropertyName("text")] public string Text { get; set; } + [JsonPropertyName("text")] + public string Text { get; set; } - [JsonPropertyName("task")] public string Task { get; set; } + [JsonPropertyName("task")] + public string Task { get; set; } - [JsonPropertyName("language")] public string Language { get; set; } + [JsonPropertyName("language")] + public string Language { get; set; } - [JsonPropertyName("duration")] public float Duration { get; set; } + [JsonPropertyName("duration")] + public float Duration { get; set; } - [JsonPropertyName("words")] public List Words { get; set; } + [JsonPropertyName("words")] + public List Words { get; set; } + + [JsonPropertyName("segments")] + public List Segments { get; set; } - [JsonPropertyName("segments")] public List Segments { get; set; } - public class WordSegment { - [JsonPropertyName("word")] public string Word { get; set; } + [JsonPropertyName("word")] + public string Word { get; set; } - [JsonPropertyName("start")] public float Start { get; set; } + [JsonPropertyName("start")] + public float Start { get; set; } - [JsonPropertyName("end")] public float End { get; set; } + [JsonPropertyName("end")] + public float End { get; set; } } public class Segment { - [JsonPropertyName("id")] public int Id { get; set; } + [JsonPropertyName("id")] + public int Id { get; set; } - [JsonPropertyName("seek")] public int Seek { get; set; } + [JsonPropertyName("seek")] + public int Seek { get; set; } - [JsonPropertyName("start")] public float Start { get; set; } + [JsonPropertyName("start")] + public float Start { get; set; } - [JsonPropertyName("end")] public float End { get; set; } + [JsonPropertyName("end")] + public float End { get; set; } - [JsonPropertyName("text")] public string Text { get; set; } + [JsonPropertyName("text")] + public string Text { get; set; } - [JsonPropertyName("tokens")] public List Tokens { get; set; } + [JsonPropertyName("tokens")] + public List Tokens { get; set; } - [JsonPropertyName("temperature")] public float Temperature { get; set; } + [JsonPropertyName("temperature")] + public float Temperature { get; set; } - [JsonPropertyName("avg_logprob")] public float Avglogprob { get; set; } + [JsonPropertyName("avg_logprob")] + public float Avglogprob { get; set; } [JsonPropertyName("compression_ratio")] public float CompressionRatio { get; set; } - [JsonPropertyName("no_speech_prob")] public float Nospeechprob { get; set; } + [JsonPropertyName("no_speech_prob")] + public float Nospeechprob { get; set; } - [JsonPropertyName("transient")] public bool Transient { get; set; } + [JsonPropertyName("transient")] + public bool Transient { get; set; } } } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/BaseResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/BaseResponse.cs index 743ec531..9e5e0f07 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/BaseResponse.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/BaseResponse.cs @@ -7,9 +7,14 @@ namespace OpenAI.ObjectModels.ResponseModels; public record BaseResponse { - [JsonPropertyName("object")] public string? ObjectTypeName { get; set; } + [JsonPropertyName("object")] + public string? ObjectTypeName { get; set; } + public bool Successful => Error == null; - [JsonPropertyName("error")] public Error? Error { get; set; } + + [JsonPropertyName("error")] + public Error? Error { get; set; } + public HttpStatusCode HttpStatusCode { get; set; } public ResponseHeaderValues? HeaderValues { get; set; } } @@ -54,9 +59,10 @@ public record ResponseHeaderValues public OpenAIInfo? OpenAI { get; set; } } -public record DataWithPagingBaseResponse : BaseResponse where T :IList +public record DataWithPagingBaseResponse : BaseResponse where T : IList { - [JsonPropertyName("data")] public T? Data { get; set; } + [JsonPropertyName("data")] + public T? Data { get; set; } [JsonPropertyName("first_id")] public string FirstId { get; set; } @@ -67,27 +73,36 @@ public record DataWithPagingBaseResponse : BaseResponse where T :IList [JsonPropertyName("has_more")] public bool HasMore { get; set; } } + public record DataBaseResponse : BaseResponse { - [JsonPropertyName("data")] public T? Data { get; set; } + [JsonPropertyName("data")] + public T? Data { get; set; } } -public record ErrorList: DataBaseResponse> +public record ErrorList : DataBaseResponse> { } + public class Error { - [JsonPropertyName("code")] public string? Code { get; set; } + [JsonPropertyName("code")] + public string? Code { get; set; } - [JsonPropertyName("param")] public string? Param { get; set; } + [JsonPropertyName("param")] + public string? Param { get; set; } - [JsonPropertyName("type")] public string? Type { get; set; } + [JsonPropertyName("type")] + public string? Type { get; set; } [JsonPropertyName("line")] public int? Line { get; set; } - [JsonIgnore] public string? Message { get; private set; } - [JsonIgnore] public List Messages { get; private set; } + [JsonIgnore] + public string? Message { get; private set; } + + [JsonIgnore] + public List Messages { get; private set; } [JsonPropertyName("message")] [JsonConverter(typeof(MessageConverter))] diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/BatchResponseModel/BatchResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/BatchResponseModel/BatchResponse.cs index a063b6e4..8fc5b600 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/BatchResponseModel/BatchResponse.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/BatchResponseModel/BatchResponse.cs @@ -3,10 +3,9 @@ namespace OpenAI.ObjectModels.ResponseModels.BatchResponseModel; -public record BatchResponse : BaseResponse,IOpenAiModels.IMetaData +public record BatchResponse : BaseResponse, IOpenAiModels.IMetaData { /// - /// /// [JsonPropertyName("id")] public string Id { get; set; } diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/ChatCompletionCreateResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/ChatCompletionCreateResponse.cs index 096ce70d..64abb2cb 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/ChatCompletionCreateResponse.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/ChatCompletionCreateResponse.cs @@ -5,14 +5,21 @@ namespace OpenAI.ObjectModels.ResponseModels; public record ChatCompletionCreateResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.ICreatedAt { - [JsonPropertyName("model")] public string Model { get; set; } + [JsonPropertyName("model")] + public string Model { get; set; } - [JsonPropertyName("choices")] public List Choices { get; set; } + [JsonPropertyName("choices")] + public List Choices { get; set; } - [JsonPropertyName("usage")] public UsageResponse Usage { get; set; } + [JsonPropertyName("usage")] + public UsageResponse Usage { get; set; } - [JsonPropertyName("created")] public int CreatedAt { get; set; } + [JsonPropertyName("system_fingerprint")] + public string SystemFingerPrint { get; set; } - [JsonPropertyName("id")] public string Id { get; set; } - [JsonPropertyName("system_fingerprint")] public string SystemFingerPrint { get; set; } + [JsonPropertyName("created")] + public int CreatedAt { get; set; } + + [JsonPropertyName("id")] + public string Id { get; set; } } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/CompletionCreateResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/CompletionCreateResponse.cs index fc7f3ad5..7ce26a49 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/CompletionCreateResponse.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/CompletionCreateResponse.cs @@ -5,13 +5,18 @@ namespace OpenAI.ObjectModels.ResponseModels; public record CompletionCreateResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.ICreatedAt { - [JsonPropertyName("model")] public string Model { get; set; } + [JsonPropertyName("model")] + public string Model { get; set; } - [JsonPropertyName("choices")] public List Choices { get; set; } + [JsonPropertyName("choices")] + public List Choices { get; set; } - [JsonPropertyName("usage")] public UsageResponse Usage { get; set; } + [JsonPropertyName("usage")] + public UsageResponse Usage { get; set; } - [JsonPropertyName("created")] public int CreatedAt { get; set; } + [JsonPropertyName("created")] + public int CreatedAt { get; set; } - [JsonPropertyName("id")] public string Id { get; set; } + [JsonPropertyName("id")] + public string Id { get; set; } } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/CreateModerationResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/CreateModerationResponse.cs index d997dca1..1f7bde47 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/CreateModerationResponse.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/CreateModerationResponse.cs @@ -5,70 +5,96 @@ namespace OpenAI.ObjectModels.ResponseModels; public record CreateModerationResponse : BaseResponse, IOpenAiModels.IModel, IOpenAiModels.IId { - [JsonPropertyName("results")] public List Results { get; set; } + [JsonPropertyName("results")] + public List Results { get; set; } - [JsonPropertyName("id")] public string Id { get; set; } + [JsonPropertyName("id")] + public string Id { get; set; } - [JsonPropertyName("model")] public string Model { get; set; } + [JsonPropertyName("model")] + public string Model { get; set; } } public record Result { - [JsonPropertyName("categories")] public Categories Categories { get; set; } + [JsonPropertyName("categories")] + public Categories Categories { get; set; } - [JsonPropertyName("category_scores")] public CategoryScores CategoryScores { get; set; } + [JsonPropertyName("category_scores")] + public CategoryScores CategoryScores { get; set; } - [JsonPropertyName("flagged")] public bool Flagged { get; set; } + [JsonPropertyName("flagged")] + public bool Flagged { get; set; } } public record Categories { - [JsonPropertyName("hate")] public bool Hate { get; set; } + [JsonPropertyName("hate")] + public bool Hate { get; set; } - [JsonPropertyName("hate/threatening")] public bool HateThreatening { get; set; } + [JsonPropertyName("hate/threatening")] + public bool HateThreatening { get; set; } - [JsonPropertyName("harassment")] public bool Harassment { get; set; } + [JsonPropertyName("harassment")] + public bool Harassment { get; set; } [JsonPropertyName("harassment/threatening")] public bool HarassmentThreatening { get; set; } - [JsonPropertyName("self-harm")] public bool SelfHarm { get; set; } - [JsonPropertyName("self-harm/intent")] public bool SelfHarmIntent { get; set; } + [JsonPropertyName("self-harm")] + public bool SelfHarm { get; set; } + + [JsonPropertyName("self-harm/intent")] + public bool SelfHarmIntent { get; set; } [JsonPropertyName("self-harm/instructions")] public bool SelfHarmInstructions { get; set; } - [JsonPropertyName("sexual")] public bool Sexual { get; set; } + [JsonPropertyName("sexual")] + public bool Sexual { get; set; } - [JsonPropertyName("sexual/minors")] public bool SexualMinors { get; set; } + [JsonPropertyName("sexual/minors")] + public bool SexualMinors { get; set; } - [JsonPropertyName("violence")] public bool Violence { get; set; } + [JsonPropertyName("violence")] + public bool Violence { get; set; } - [JsonPropertyName("violence/graphic")] public bool ViolenceGraphic { get; set; } + [JsonPropertyName("violence/graphic")] + public bool ViolenceGraphic { get; set; } } public record CategoryScores { - [JsonPropertyName("hate")] public float Hate { get; set; } + [JsonPropertyName("hate")] + public float Hate { get; set; } - [JsonPropertyName("hate/threatening")] public float HateThreatening { get; set; } + [JsonPropertyName("hate/threatening")] + public float HateThreatening { get; set; } - [JsonPropertyName("harassment")] public float Harassment { get; set; } + [JsonPropertyName("harassment")] + public float Harassment { get; set; } [JsonPropertyName("harassment/threatening")] public float HarassmentThreatening { get; set; } - [JsonPropertyName("self-harm")] public float SelfHarm { get; set; } - [JsonPropertyName("self-harm/intent")] public float SelfHarmIntent { get; set; } + [JsonPropertyName("self-harm")] + public float SelfHarm { get; set; } + + [JsonPropertyName("self-harm/intent")] + public float SelfHarmIntent { get; set; } [JsonPropertyName("self-harm/instructions")] public float SelfHarmInstructions { get; set; } - [JsonPropertyName("sexual")] public float Sexual { get; set; } + [JsonPropertyName("sexual")] + public float Sexual { get; set; } - [JsonPropertyName("sexual/minors")] public float SexualMinors { get; set; } + [JsonPropertyName("sexual/minors")] + public float SexualMinors { get; set; } - [JsonPropertyName("violence")] public float Violence { get; set; } + [JsonPropertyName("violence")] + public float Violence { get; set; } - [JsonPropertyName("violence/graphic")] public float ViolenceGraphic { get; set; } + [JsonPropertyName("violence/graphic")] + public float ViolenceGraphic { get; set; } } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/EditCreateResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/EditCreateResponse.cs index ae203906..6e0f7ac1 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/EditCreateResponse.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/EditCreateResponse.cs @@ -5,11 +5,15 @@ namespace OpenAI.ObjectModels.ResponseModels; public record EditCreateResponse : BaseResponse, IOpenAiModels.ICreatedAt { - [JsonPropertyName("model")] public string Model { get; set; } + [JsonPropertyName("model")] + public string Model { get; set; } - [JsonPropertyName("choices")] public List Choices { get; set; } + [JsonPropertyName("choices")] + public List Choices { get; set; } - [JsonPropertyName("usage")] public UsageResponse Usage { get; set; } + [JsonPropertyName("usage")] + public UsageResponse Usage { get; set; } - [JsonPropertyName("created")] public int CreatedAt { get; set; } + [JsonPropertyName("created")] + public int CreatedAt { get; set; } } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/EmbeddingCreateResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/EmbeddingCreateResponse.cs index 4e8b0c30..34ccc649 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/EmbeddingCreateResponse.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/EmbeddingCreateResponse.cs @@ -4,16 +4,21 @@ namespace OpenAI.ObjectModels.ResponseModels; public record EmbeddingCreateResponse : BaseResponse { - [JsonPropertyName("model")] public string Model { get; set; } + [JsonPropertyName("model")] + public string Model { get; set; } - [JsonPropertyName("data")] public List Data { get; set; } + [JsonPropertyName("data")] + public List Data { get; set; } - [JsonPropertyName("usage")] public UsageResponse Usage { get; set; } + [JsonPropertyName("usage")] + public UsageResponse Usage { get; set; } } public record EmbeddingResponse { - [JsonPropertyName("index")] public int? Index { get; set; } + [JsonPropertyName("index")] + public int? Index { get; set; } - [JsonPropertyName("embedding")] public List Embedding { get; set; } + [JsonPropertyName("embedding")] + public List Embedding { get; set; } } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/FileResponseModels/FileDeleteResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/FileResponseModels/FileDeleteResponse.cs index 6f167448..958581d3 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/FileResponseModels/FileDeleteResponse.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/FileResponseModels/FileDeleteResponse.cs @@ -5,6 +5,9 @@ namespace OpenAI.ObjectModels.ResponseModels.FileResponseModels; public record FileDeleteResponse : BaseResponse, IOpenAiModels.IId { - [JsonPropertyName("deleted")] public bool Deleted { get; set; } - [JsonPropertyName("id")] public string Id { get; set; } + [JsonPropertyName("deleted")] + public bool Deleted { get; set; } + + [JsonPropertyName("id")] + public string Id { get; set; } } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/FileResponseModels/FileListResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/FileResponseModels/FileListResponse.cs index 7f9f3f7f..de4ec2f4 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/FileResponseModels/FileListResponse.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/FileResponseModels/FileListResponse.cs @@ -5,5 +5,6 @@ namespace OpenAI.ObjectModels.ResponseModels.FileResponseModels; public record FileListResponse : BaseResponse { - [JsonPropertyName("data")] public List Data { get; set; } + [JsonPropertyName("data")] + public List Data { get; set; } } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/FileResponseModels/FileUploadResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/FileResponseModels/FileUploadResponse.cs index 711d1219..55a231b3 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/FileResponseModels/FileUploadResponse.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/FileResponseModels/FileUploadResponse.cs @@ -5,13 +5,18 @@ namespace OpenAI.ObjectModels.ResponseModels.FileResponseModels; public record FileUploadResponse : BaseResponse, IOpenAiModels.ICreatedAt { - [JsonPropertyName("id")] public string Id { get; set; } + [JsonPropertyName("id")] + public string Id { get; set; } - [JsonPropertyName("bytes")] public int Bytes { get; set; } + [JsonPropertyName("bytes")] + public int Bytes { get; set; } - [JsonPropertyName("filename")] public string FileName { get; set; } + [JsonPropertyName("filename")] + public string FileName { get; set; } - [JsonPropertyName("purpose")] public string Purpose { get; set; } + [JsonPropertyName("purpose")] + public string Purpose { get; set; } - [JsonPropertyName("created_at")] public int CreatedAt { get; set; } + [JsonPropertyName("created_at")] + public int CreatedAt { get; set; } } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/FineTuneResponseModels/FineTuneListEventsResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/FineTuneResponseModels/FineTuneListEventsResponse.cs index e3b07536..9f7995f0 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/FineTuneResponseModels/FineTuneListEventsResponse.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/FineTuneResponseModels/FineTuneListEventsResponse.cs @@ -5,5 +5,6 @@ namespace OpenAI.ObjectModels.ResponseModels.FineTuneResponseModels; public record FineTuneListEventsResponse : BaseResponse { - [JsonPropertyName("data")] public List Data { get; set; } + [JsonPropertyName("data")] + public List Data { get; set; } } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/FineTuneResponseModels/FineTuneListResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/FineTuneResponseModels/FineTuneListResponse.cs index c580c65b..7c3b3ba4 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/FineTuneResponseModels/FineTuneListResponse.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/FineTuneResponseModels/FineTuneListResponse.cs @@ -4,5 +4,6 @@ namespace OpenAI.ObjectModels.ResponseModels.FineTuneResponseModels; public record FineTuneListResponse : BaseResponse { - [JsonPropertyName("data")] public List Data { get; set; } + [JsonPropertyName("data")] + public List Data { get; set; } } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/FineTuneResponseModels/FineTuneResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/FineTuneResponseModels/FineTuneResponse.cs index ad50a3fc..c9b877a5 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/FineTuneResponseModels/FineTuneResponse.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/FineTuneResponseModels/FineTuneResponse.cs @@ -5,26 +5,39 @@ namespace OpenAI.ObjectModels.ResponseModels.FineTuneResponseModels; public record FineTuneResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.IModel, IOpenAiModels.ICreatedAt { - [JsonPropertyName("events")] public List Events { get; set; } + [JsonPropertyName("events")] + public List Events { get; set; } - [JsonPropertyName("fine_tuned_model")] public string FineTunedModel { get; set; } + [JsonPropertyName("fine_tuned_model")] + public string FineTunedModel { get; set; } - [JsonPropertyName("hyperparams")] public HyperParametersResponse HyperParams { get; set; } + [JsonPropertyName("hyperparams")] + public HyperParametersResponse HyperParams { get; set; } - [JsonPropertyName("organization_id")] public string OrganizationId { get; set; } + [JsonPropertyName("organization_id")] + public string OrganizationId { get; set; } - [JsonPropertyName("result_files")] public List ResultFiles { get; set; } + [JsonPropertyName("result_files")] + public List ResultFiles { get; set; } - [JsonPropertyName("status")] public string Status { get; set; } + [JsonPropertyName("status")] + public string Status { get; set; } - [JsonPropertyName("validation_files")] public List ValidationFiles { get; set; } + [JsonPropertyName("validation_files")] + public List ValidationFiles { get; set; } - [JsonPropertyName("training_files")] public List TrainingFiles { get; set; } + [JsonPropertyName("training_files")] + public List TrainingFiles { get; set; } - [JsonPropertyName("updated_at")] public int? UpdatedAt { get; set; } + [JsonPropertyName("updated_at")] + public int? UpdatedAt { get; set; } - [JsonPropertyName("created_at")] public int CreatedAt { get; set; } - [JsonPropertyName("id")] public string Id { get; set; } + [JsonPropertyName("created_at")] + public int CreatedAt { get; set; } - [JsonPropertyName("model")] public string Model { get; set; } + [JsonPropertyName("id")] + public string Id { get; set; } + + [JsonPropertyName("model")] + public string Model { get; set; } } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/FineTuningJobResponseModels/FineTuningJobListEventsResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/FineTuningJobResponseModels/FineTuningJobListEventsResponse.cs index be4ca12b..4554f203 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/FineTuningJobResponseModels/FineTuningJobListEventsResponse.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/FineTuningJobResponseModels/FineTuningJobListEventsResponse.cs @@ -1,5 +1,5 @@ -using OpenAI.ObjectModels.SharedModels; -using System.Text.Json.Serialization; +using System.Text.Json.Serialization; +using OpenAI.ObjectModels.SharedModels; namespace OpenAI.ObjectModels.ResponseModels.FineTuningJobResponseModels; @@ -7,8 +7,7 @@ public record FineTuningJobListEventsResponse : BaseResponse { [JsonPropertyName("data")] public List Data { get; set; } - + [JsonPropertyName("has_more")] public bool HasMore { get; set; } -} - +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/FineTuningJobResponseModels/FineTuningJobListResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/FineTuningJobResponseModels/FineTuningJobListResponse.cs index 3f13cd78..d32c1a70 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/FineTuningJobResponseModels/FineTuningJobListResponse.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/FineTuningJobResponseModels/FineTuningJobListResponse.cs @@ -9,5 +9,4 @@ public record FineTuningJobListResponse : BaseResponse [JsonPropertyName("has_more")] public bool HasMore { get; set; } -} - +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/FineTuningJobResponseModels/FineTuningJobResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/FineTuningJobResponseModels/FineTuningJobResponse.cs index dd50aaa6..54071c21 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/FineTuningJobResponseModels/FineTuningJobResponse.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/FineTuningJobResponseModels/FineTuningJobResponse.cs @@ -88,7 +88,7 @@ public class Hyperparameters /// The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset. /// "Auto" decides the optimal number of epochs based on the size of the dataset. If setting the number manually, we /// support any number between 1 and 50 epochs. - /// "Auto" == -1 + /// "Auto" == -1 /// [JsonPropertyName("n_epochs")] [JsonConverter(typeof(NEpochsConverter))] diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/ImageResponseModel/ImageCreateResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/ImageResponseModel/ImageCreateResponse.cs index d1f436a8..e5902f10 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/ImageResponseModel/ImageCreateResponse.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/ImageResponseModel/ImageCreateResponse.cs @@ -5,14 +5,21 @@ namespace OpenAI.ObjectModels.ResponseModels.ImageResponseModel; public record ImageCreateResponse : BaseResponse, IOpenAiModels.ICreatedAt { - [JsonPropertyName("data")] public List Results { get; set; } + [JsonPropertyName("data")] + public List Results { get; set; } - [JsonPropertyName("created")] public int CreatedAt { get; set; } + [JsonPropertyName("created")] + public int CreatedAt { get; set; } public record ImageDataResult { - [JsonPropertyName("url")] public string Url { get; set; } - [JsonPropertyName("b64_json")] public string B64 { get; set; } - [JsonPropertyName("revised_prompt")] public string RevisedPrompt { get; set; } + [JsonPropertyName("url")] + public string Url { get; set; } + + [JsonPropertyName("b64_json")] + public string B64 { get; set; } + + [JsonPropertyName("revised_prompt")] + public string RevisedPrompt { get; set; } } } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/MessageListResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/MessageListResponse.cs index 9feaf530..ed3ea56d 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/MessageListResponse.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/MessageListResponse.cs @@ -1,8 +1,7 @@ -using System.Text.Json.Serialization; -using OpenAI.ObjectModels.SharedModels; +using OpenAI.ObjectModels.SharedModels; namespace OpenAI.ObjectModels.ResponseModels; public record MessageListResponse : DataWithPagingBaseResponse> { -} +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/ModelResponseModels/ModelDeleteResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/ModelResponseModels/ModelDeleteResponse.cs index 4bc146bb..d9639b36 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/ModelResponseModels/ModelDeleteResponse.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/ModelResponseModels/ModelDeleteResponse.cs @@ -4,7 +4,9 @@ namespace OpenAI.ObjectModels.ResponseModels.ModelResponseModels; public record ModelDeleteResponse : BaseResponse { - [JsonPropertyName("id")] public string Id { get; set; } + [JsonPropertyName("id")] + public string Id { get; set; } - [JsonPropertyName("deleted")] public bool Deleted { get; set; } + [JsonPropertyName("deleted")] + public bool Deleted { get; set; } } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/ModelResponseModels/ModelListResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/ModelResponseModels/ModelListResponse.cs index c0edd2ae..ccf9654b 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/ModelResponseModels/ModelListResponse.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/ModelResponseModels/ModelListResponse.cs @@ -4,5 +4,6 @@ namespace OpenAI.ObjectModels.ResponseModels.ModelResponseModels; public record ModelListResponse : BaseResponse { - [JsonPropertyName("data")] public List Models { get; set; } + [JsonPropertyName("data")] + public List Models { get; set; } } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/ModelResponseModels/ModelRetrieveResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/ModelResponseModels/ModelRetrieveResponse.cs index b53114ba..bbc08ed7 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/ModelResponseModels/ModelRetrieveResponse.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/ModelResponseModels/ModelRetrieveResponse.cs @@ -3,52 +3,68 @@ namespace OpenAI.ObjectModels.ResponseModels.ModelResponseModels; public record ModelRetrieveResponse : ModelResponse - // ReSharper disable once RedundantRecordBody +// ReSharper disable once RedundantRecordBody { } public record ModelResponse : BaseResponse { - [JsonPropertyName("id")] public string Id { get; set; } + [JsonPropertyName("id")] + public string Id { get; set; } - [JsonPropertyName("owned_by")] public string Owner { get; set; } + [JsonPropertyName("owned_by")] + public string Owner { get; set; } - [JsonPropertyName("permission")] public List Permissions { get; set; } = new(); + [JsonPropertyName("permission")] + public List Permissions { get; set; } = new(); + + [JsonPropertyName("created")] + public int Created { get; set; } - [JsonPropertyName("created")] public int Created { get; set; } public DateTimeOffset CreatedTime => DateTimeOffset.FromUnixTimeSeconds(Created); - [JsonPropertyName("root")] public string? Root { get; set; } + [JsonPropertyName("root")] + public string? Root { get; set; } - [JsonPropertyName("parent")] public string? Parent { get; set; } + [JsonPropertyName("parent")] + public string? Parent { get; set; } } public record Permission : BaseResponse { - [JsonPropertyName("id")] public string Id { get; set; } + [JsonPropertyName("id")] + public string Id { get; set; } + + [JsonPropertyName("created")] + public int Created { get; set; } - [JsonPropertyName("created")] public int Created { get; set; } public DateTimeOffset CreatedTime => DateTimeOffset.FromUnixTimeSeconds(Created); [JsonPropertyName("allow_create_engine")] public bool AllowCreateEngine { get; set; } - [JsonPropertyName("allow_sampling")] public bool AllowSampling { get; set; } + [JsonPropertyName("allow_sampling")] + public bool AllowSampling { get; set; } - [JsonPropertyName("allow_logprobs")] public bool AllowLogprobs { get; set; } + [JsonPropertyName("allow_logprobs")] + public bool AllowLogprobs { get; set; } [JsonPropertyName("allow_search_indices")] public bool AllowSearchIndices { get; set; } - [JsonPropertyName("allow_view")] public bool AllowView { get; set; } + [JsonPropertyName("allow_view")] + public bool AllowView { get; set; } [JsonPropertyName("allow_fine_tuning")] public bool AllowFineTuning { get; set; } - [JsonPropertyName("organization")] public string Organization { get; set; } + [JsonPropertyName("organization")] + public string Organization { get; set; } - [JsonPropertyName("group")] public object Group { get; set; } + [JsonPropertyName("group")] + public object Group { get; set; } - [JsonPropertyName("is_blocking")] public bool IsBlocking { get; set; } + [JsonPropertyName("is_blocking")] + public bool IsBlocking { get; set; } } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/UsageResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/UsageResponse.cs index 34460959..5dbd4715 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/UsageResponse.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/UsageResponse.cs @@ -4,10 +4,12 @@ namespace OpenAI.ObjectModels.ResponseModels; public record UsageResponse { - [JsonPropertyName("prompt_tokens")] public int PromptTokens { get; set; } + [JsonPropertyName("prompt_tokens")] + public int PromptTokens { get; set; } [JsonPropertyName("completion_tokens")] public int? CompletionTokens { get; set; } - [JsonPropertyName("total_tokens")] public int TotalTokens { get; set; } + [JsonPropertyName("total_tokens")] + public int TotalTokens { get; set; } } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/VectorStoreResponseModels/ExpiresAfter.cs b/OpenAI.SDK/ObjectModels/ResponseModels/VectorStoreResponseModels/ExpiresAfter.cs index 90d21a7f..06108156 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/VectorStoreResponseModels/ExpiresAfter.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/VectorStoreResponseModels/ExpiresAfter.cs @@ -5,13 +5,13 @@ namespace OpenAI.ObjectModels.ResponseModels.VectorStoreResponseModels; public record ExpiresAfter { /// - /// Anchor timestamp after which the expiration policy applies. Supported anchors: `last_active_at`. + /// Anchor timestamp after which the expiration policy applies. Supported anchors: `last_active_at`. /// [JsonPropertyName("anchor")] public string Anchor { get; set; } /// - /// The number of days after the anchor time that the vector store will expire. + /// The number of days after the anchor time that the vector store will expire. /// [JsonPropertyName("days")] public int Days { get; set; } diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/VectorStoreResponseModels/FileCounts.cs b/OpenAI.SDK/ObjectModels/ResponseModels/VectorStoreResponseModels/FileCounts.cs index 50eaf5bf..baebb7fa 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/VectorStoreResponseModels/FileCounts.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/VectorStoreResponseModels/FileCounts.cs @@ -5,31 +5,31 @@ namespace OpenAI.ObjectModels.ResponseModels.VectorStoreResponseModels; public record FileCounts { /// - /// The number of files that are currently being processed. + /// The number of files that are currently being processed. /// [JsonPropertyName("in_progress")] public int InProgress { get; set; } /// - /// The number of files that have been processed. + /// The number of files that have been processed. /// [JsonPropertyName("completed")] public int Completed { get; set; } /// - /// The number of files that have failed to process. + /// The number of files that have failed to process. /// [JsonPropertyName("failed")] public int Failed { get; set; } /// - /// The number of files that where cancelled. + /// The number of files that where cancelled. /// [JsonPropertyName("cancelled")] public int Cancelled { get; set; } /// - /// The total number of files. + /// The total number of files. /// [JsonPropertyName("total")] public int Total { get; set; } diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/VectorStoreResponseModels/VectorStoreFileBatchObject.cs b/OpenAI.SDK/ObjectModels/ResponseModels/VectorStoreResponseModels/VectorStoreFileBatchObject.cs index 43cd7e10..e158efaf 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/VectorStoreResponseModels/VectorStoreFileBatchObject.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/VectorStoreResponseModels/VectorStoreFileBatchObject.cs @@ -2,29 +2,31 @@ namespace OpenAI.ObjectModels.ResponseModels.VectorStoreResponseModels; -public record VectorStoreFileBatchObject:BaseResponse +public record VectorStoreFileBatchObject : BaseResponse { /// - /// The identifier, which can be referenced in API endpoints. + /// The identifier, which can be referenced in API endpoints. /// [JsonPropertyName("id")] public string Id { get; set; } /// - /// The Unix timestamp (in seconds) for when the vector store files batch was created. + /// The Unix timestamp (in seconds) for when the vector store files batch was created. /// [JsonPropertyName("created_at")] public int CreatedAt { get; set; } /// - /// The ID of the [vector store](/docs/api-reference/vector-stores/object) that the [File](/docs/api-reference/files) is attached to. + /// The ID of the [vector store](/docs/api-reference/vector-stores/object) that the [File](/docs/api-reference/files) + /// is attached to. /// [JsonPropertyName("vector_store_id")] public string VectorStoreId { get; set; } /// - /// The status of the vector store files batch, which can be either `in_progress`, `completed`, `cancelled` or `failed`. + /// The status of the vector store files batch, which can be either `in_progress`, `completed`, `cancelled` or + /// `failed`. /// [JsonPropertyName("status")] public string Status { get; set; } diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/VectorStoreResponseModels/VectorStoreFileObject.cs b/OpenAI.SDK/ObjectModels/ResponseModels/VectorStoreResponseModels/VectorStoreFileObject.cs index 63101d99..65780d06 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/VectorStoreResponseModels/VectorStoreFileObject.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/VectorStoreResponseModels/VectorStoreFileObject.cs @@ -1,44 +1,48 @@ using System.Text.Json.Serialization; namespace OpenAI.ObjectModels.ResponseModels.VectorStoreResponseModels; + public record VectorStoreFileListObject : DataWithPagingBaseResponse> { } + public record VectorStoreFileObject : BaseResponse { /// - /// The identifier, which can be referenced in API endpoints. + /// The identifier, which can be referenced in API endpoints. /// [JsonPropertyName("id")] public string Id { get; set; } /// - /// The total vector store usage in bytes. Note that this may be different from the original file size. + /// The total vector store usage in bytes. Note that this may be different from the original file size. /// [JsonPropertyName("usage_bytes")] public int UsageBytes { get; set; } /// - /// The Unix timestamp (in seconds) for when the vector store file was created. + /// The Unix timestamp (in seconds) for when the vector store file was created. /// [JsonPropertyName("created_at")] public int CreatedAt { get; set; } /// - /// The ID of the [vector store](/docs/api-reference/vector-stores/object) that the [File](/docs/api-reference/files) is attached to. + /// The ID of the [vector store](/docs/api-reference/vector-stores/object) that the [File](/docs/api-reference/files) + /// is attached to. /// [JsonPropertyName("vector_store_id")] public string VectorStoreId { get; set; } /// - /// The status of the vector store file, which can be either `in_progress`, `completed`, `cancelled`, or `failed`. The status `completed` indicates that the vector store file is ready for use. + /// The status of the vector store file, which can be either `in_progress`, `completed`, `cancelled`, or `failed`. The + /// status `completed` indicates that the vector store file is ready for use. /// [JsonPropertyName("status")] public string Status { get; set; } /// - /// The last error associated with this vector store file. Will be `null` if there are no errors. + /// The last error associated with this vector store file. Will be `null` if there are no errors. /// [JsonPropertyName("last_error")] public Error? LastError { get; set; } diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/VectorStoreResponseModels/VectorStoreFileResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/VectorStoreResponseModels/VectorStoreFileResponse.cs deleted file mode 100644 index add3623a..00000000 --- a/OpenAI.SDK/ObjectModels/ResponseModels/VectorStoreResponseModels/VectorStoreFileResponse.cs +++ /dev/null @@ -1,4 +0,0 @@ -using System.Text.Json.Serialization; - -namespace OpenAI.ObjectModels.ResponseModels.VectorStoreResponseModels; - diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/VectorStoreResponseModels/VectorStoreObjectResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/VectorStoreResponseModels/VectorStoreObjectResponse.cs index f6317fcb..49c414e7 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/VectorStoreResponseModels/VectorStoreObjectResponse.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/VectorStoreResponseModels/VectorStoreObjectResponse.cs @@ -2,28 +2,28 @@ namespace OpenAI.ObjectModels.ResponseModels.VectorStoreResponseModels; -public record VectorStoreObjectResponse:BaseResponse +public record VectorStoreObjectResponse : BaseResponse { /// - /// The identifier, which can be referenced in API endpoints. + /// The identifier, which can be referenced in API endpoints. /// [JsonPropertyName("id")] public string Id { get; set; } /// - /// The Unix timestamp (in seconds) for when the vector store was created. + /// The Unix timestamp (in seconds) for when the vector store was created. /// [JsonPropertyName("created_at")] public int CreatedAt { get; set; } /// - /// The name of the vector store. + /// The name of the vector store. /// [JsonPropertyName("name")] public string Name { get; set; } /// - /// The total number of bytes used by the files in the vector store. + /// The total number of bytes used by the files in the vector store. /// [JsonPropertyName("usage_bytes")] public int UsageBytes { get; set; } @@ -32,34 +32,35 @@ public record VectorStoreObjectResponse:BaseResponse public FileCounts FileCounts { get; set; } /// - /// The status of the vector store, which can be either `expired`, `in_progress`, or `completed`. A status of `completed` indicates that the vector store is ready for use. + /// The status of the vector store, which can be either `expired`, `in_progress`, or `completed`. A status of + /// `completed` indicates that the vector store is ready for use. /// [JsonPropertyName("status")] public string Status { get; set; } /// - /// The expiration policy for a vector store. + /// The expiration policy for a vector store. /// [JsonPropertyName("expires_after")] public ExpiresAfter ExpiresAfter { get; set; } /// - /// The Unix timestamp (in seconds) for when the vector store will expire. + /// The Unix timestamp (in seconds) for when the vector store will expire. /// [JsonPropertyName("expires_at")] public int? ExpiresAt { get; set; } /// - /// The Unix timestamp (in seconds) for when the vector store was last active. + /// The Unix timestamp (in seconds) for when the vector store was last active. /// [JsonPropertyName("last_active_at")] public int? LastActiveAt { get; set; } /// - /// Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. + /// Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information + /// about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of + /// 512 characters long. /// [JsonPropertyName("metadata")] public Dictionary? Metadata { get; set; } - - } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/SharedModels/AssistantResponse.cs b/OpenAI.SDK/ObjectModels/SharedModels/AssistantResponse.cs index f7afb9cd..a861a005 100644 --- a/OpenAI.SDK/ObjectModels/SharedModels/AssistantResponse.cs +++ b/OpenAI.SDK/ObjectModels/SharedModels/AssistantResponse.cs @@ -4,7 +4,7 @@ namespace OpenAI.ObjectModels.SharedModels; -public record AssistantResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.ICreatedAt, IOpenAiModels.IModel, IOpenAiModels.IMetaData,IOpenAiModels.ITools +public record AssistantResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.ICreatedAt, IOpenAiModels.IModel, IOpenAiModels.IMetaData, IOpenAiModels.ITools { /// /// The name of the assistant. The maximum length is 256 characters. @@ -25,12 +25,6 @@ public record AssistantResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels [JsonPropertyName("instructions")] public string? Instructions { get; set; } - /// - /// A list of tools enabled on the assistant. - /// - [JsonPropertyName("tools")] - public List Tools { get; set; } - /// /// A list of file IDs attached to this assistant. /// There can be a maximum of 20 files attached to the assistant. @@ -63,4 +57,10 @@ public record AssistantResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels /// [JsonPropertyName("model")] public string Model { get; set; } + + /// + /// A list of tools enabled on the assistant. + /// + [JsonPropertyName("tools")] + public List Tools { get; set; } } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/SharedModels/ChatChoiceResponse.cs b/OpenAI.SDK/ObjectModels/SharedModels/ChatChoiceResponse.cs index ad4bf0ac..de14b9c7 100644 --- a/OpenAI.SDK/ObjectModels/SharedModels/ChatChoiceResponse.cs +++ b/OpenAI.SDK/ObjectModels/SharedModels/ChatChoiceResponse.cs @@ -12,38 +12,51 @@ public ChatMessage Delta set => Message = value; } - [JsonPropertyName("message")] public ChatMessage Message { get; set; } + [JsonPropertyName("message")] + public ChatMessage Message { get; set; } - [JsonPropertyName("index")] public int? Index { get; set; } + [JsonPropertyName("index")] + public int? Index { get; set; } - [JsonPropertyName("finish_reason")] public string FinishReason { get; set; } + [JsonPropertyName("finish_reason")] + public string FinishReason { get; set; } - [JsonPropertyName("finish_details")] public FinishDetailsResponse? FinishDetails { get; set; } + [JsonPropertyName("finish_details")] + public FinishDetailsResponse? FinishDetails { get; set; } + + [JsonPropertyName("logprobs")] + public ChatLogProbsResponse LogProbs { get; set; } - [JsonPropertyName("logprobs")] public ChatLogProbsResponse LogProbs { get; set; } public class FinishDetailsResponse { [JsonPropertyName("type")] public string Type { get; set; } + [JsonPropertyName("stop")] public string Stop { get; set; } } public record ChatLogProbsResponse { - [JsonPropertyName("content")] public List Content { get; set; } + [JsonPropertyName("content")] + public List Content { get; set; } } public record ContentItemBase { - [JsonPropertyName("token")] public string Token { get; set; } + [JsonPropertyName("token")] + public string Token { get; set; } - [JsonPropertyName("logprob")] public double LogProb { get; set; } + [JsonPropertyName("logprob")] + public double LogProb { get; set; } - [JsonPropertyName("bytes")] public List Bytes { get; set; } + [JsonPropertyName("bytes")] + public List Bytes { get; set; } } + public record ContentItem : ContentItemBase { - [JsonPropertyName("top_logprobs")] public List TopLogProbs { get; set; } + [JsonPropertyName("top_logprobs")] + public List TopLogProbs { get; set; } } } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/SharedModels/ChoiceResponse.cs b/OpenAI.SDK/ObjectModels/SharedModels/ChoiceResponse.cs index 4a2548ae..c0a0ea8a 100644 --- a/OpenAI.SDK/ObjectModels/SharedModels/ChoiceResponse.cs +++ b/OpenAI.SDK/ObjectModels/SharedModels/ChoiceResponse.cs @@ -4,11 +4,15 @@ namespace OpenAI.ObjectModels.SharedModels; public record ChoiceResponse : IOpenAiModels.ILogProbsResponse { - [JsonPropertyName("text")] public string Text { get; set; } + [JsonPropertyName("text")] + public string Text { get; set; } - [JsonPropertyName("index")] public int? Index { get; set; } + [JsonPropertyName("index")] + public int? Index { get; set; } - [JsonPropertyName("finish_reason")] public string FinishReason { get; set; } + [JsonPropertyName("finish_reason")] + public string FinishReason { get; set; } - [JsonPropertyName("logprobs")] public LogProbsResponse LogProbs { get; set; } + [JsonPropertyName("logprobs")] + public LogProbsResponse LogProbs { get; set; } } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/SharedModels/EventResponse.cs b/OpenAI.SDK/ObjectModels/SharedModels/EventResponse.cs index 9d74f2e6..e6f6d94e 100644 --- a/OpenAI.SDK/ObjectModels/SharedModels/EventResponse.cs +++ b/OpenAI.SDK/ObjectModels/SharedModels/EventResponse.cs @@ -4,13 +4,21 @@ namespace OpenAI.ObjectModels.SharedModels; public record EventResponse { - [JsonPropertyName("object")] public string? ObjectTypeName { get; set; } - [JsonPropertyName("id")] public string? Id { get; set; } + [JsonPropertyName("object")] + public string? ObjectTypeName { get; set; } - [JsonPropertyName("created_at")] public int? CreatedAt { get; set; } + [JsonPropertyName("id")] + public string? Id { get; set; } - [JsonPropertyName("level")] public string Level { get; set; } + [JsonPropertyName("created_at")] + public int? CreatedAt { get; set; } - [JsonPropertyName("message")] public string Message { get; set; } - [JsonPropertyName("type")] public string Type { get; set; } + [JsonPropertyName("level")] + public string Level { get; set; } + + [JsonPropertyName("message")] + public string Message { get; set; } + + [JsonPropertyName("type")] + public string Type { get; set; } } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/SharedModels/FileResponse.cs b/OpenAI.SDK/ObjectModels/SharedModels/FileResponse.cs index 6da91bcf..32c1ae36 100644 --- a/OpenAI.SDK/ObjectModels/SharedModels/FileResponse.cs +++ b/OpenAI.SDK/ObjectModels/SharedModels/FileResponse.cs @@ -5,11 +5,23 @@ namespace OpenAI.ObjectModels.SharedModels; public record FileResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.ICreatedAt { - [JsonPropertyName("bytes")] public int? Bytes { get; set; } - [JsonPropertyName("filename")] public string FileName { get; set; } + [JsonPropertyName("bytes")] + public int? Bytes { get; set; } + + [JsonPropertyName("filename")] + public string FileName { get; set; } + public UploadFilePurposes.UploadFilePurpose PurposeEnum => UploadFilePurposes.ToEnum(Purpose); - [JsonPropertyName("purpose")] public string Purpose { get; set; } - [JsonPropertyName("status")] public string Status { get; set; } - [JsonPropertyName("created_at")] public int CreatedAt { get; set; } - [JsonPropertyName("id")] public string Id { get; set; } + + [JsonPropertyName("purpose")] + public string Purpose { get; set; } + + [JsonPropertyName("status")] + public string Status { get; set; } + + [JsonPropertyName("created_at")] + public int CreatedAt { get; set; } + + [JsonPropertyName("id")] + public string Id { get; set; } } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/SharedModels/FunctionParameters.cs b/OpenAI.SDK/ObjectModels/SharedModels/FunctionParameters.cs index 19a1936e..0ad5fd29 100644 --- a/OpenAI.SDK/ObjectModels/SharedModels/FunctionParameters.cs +++ b/OpenAI.SDK/ObjectModels/SharedModels/FunctionParameters.cs @@ -80,7 +80,7 @@ public enum FunctionObjectTypes public static PropertyDefinition DefineArray(PropertyDefinition? arrayItems = null) { - return new PropertyDefinition + return new() { Items = arrayItems, Type = ConvertTypeToString(FunctionObjectTypes.Array) @@ -89,7 +89,7 @@ public static PropertyDefinition DefineArray(PropertyDefinition? arrayItems = nu public static PropertyDefinition DefineEnum(List enumList, string? description = null) { - return new PropertyDefinition + return new() { Description = description, Enum = enumList, @@ -99,7 +99,7 @@ public static PropertyDefinition DefineEnum(List enumList, string? descr public static PropertyDefinition DefineInteger(string? description = null) { - return new PropertyDefinition + return new() { Description = description, Type = ConvertTypeToString(FunctionObjectTypes.Integer) @@ -108,7 +108,7 @@ public static PropertyDefinition DefineInteger(string? description = null) public static PropertyDefinition DefineNumber(string? description = null) { - return new PropertyDefinition + return new() { Description = description, Type = ConvertTypeToString(FunctionObjectTypes.Number) @@ -117,7 +117,7 @@ public static PropertyDefinition DefineNumber(string? description = null) public static PropertyDefinition DefineString(string? description = null) { - return new PropertyDefinition + return new() { Description = description, Type = ConvertTypeToString(FunctionObjectTypes.String) @@ -126,7 +126,7 @@ public static PropertyDefinition DefineString(string? description = null) public static PropertyDefinition DefineBoolean(string? description = null) { - return new PropertyDefinition + return new() { Description = description, Type = ConvertTypeToString(FunctionObjectTypes.Boolean) @@ -135,7 +135,7 @@ public static PropertyDefinition DefineBoolean(string? description = null) public static PropertyDefinition DefineNull(string? description = null) { - return new PropertyDefinition + return new() { Description = description, Type = ConvertTypeToString(FunctionObjectTypes.Null) @@ -144,7 +144,7 @@ public static PropertyDefinition DefineNull(string? description = null) public static PropertyDefinition DefineObject(IDictionary? properties, IList? required, bool? additionalProperties, string? description, IList? @enum) { - return new PropertyDefinition + return new() { Properties = properties, Required = required, diff --git a/OpenAI.SDK/ObjectModels/SharedModels/HyperParametersResponse.cs b/OpenAI.SDK/ObjectModels/SharedModels/HyperParametersResponse.cs index f64ca5a5..fa7fab46 100644 --- a/OpenAI.SDK/ObjectModels/SharedModels/HyperParametersResponse.cs +++ b/OpenAI.SDK/ObjectModels/SharedModels/HyperParametersResponse.cs @@ -5,7 +5,8 @@ namespace OpenAI.ObjectModels.SharedModels; public record HyperParametersResponse { - [JsonPropertyName("batch_size")] public int? BatchSize { get; set; } + [JsonPropertyName("batch_size")] + public int? BatchSize { get; set; } [JsonPropertyName("learning_rate_multiplier")] public float? LearningRateMultiplier { get; set; } diff --git a/OpenAI.SDK/ObjectModels/SharedModels/IOpenAiModels.cs b/OpenAI.SDK/ObjectModels/SharedModels/IOpenAiModels.cs index 0e5d05bf..4fef320b 100644 --- a/OpenAI.SDK/ObjectModels/SharedModels/IOpenAiModels.cs +++ b/OpenAI.SDK/ObjectModels/SharedModels/IOpenAiModels.cs @@ -1,5 +1,4 @@ using OpenAI.ObjectModels.RequestModels; -using System.Text.Json.Serialization; namespace OpenAI.ObjectModels.SharedModels; @@ -28,7 +27,7 @@ public interface ILogProbsResponse public interface ITemperature { float? Temperature { get; set; } - } + } public interface IAssistantId { @@ -64,7 +63,7 @@ public interface IMetaData public interface IFileIds { - public List FileIds { get; set;} + public List FileIds { get; set; } } public interface ITools diff --git a/OpenAI.SDK/ObjectModels/SharedModels/LogProbsResponse.cs b/OpenAI.SDK/ObjectModels/SharedModels/LogProbsResponse.cs index cdea71e0..1729a54d 100644 --- a/OpenAI.SDK/ObjectModels/SharedModels/LogProbsResponse.cs +++ b/OpenAI.SDK/ObjectModels/SharedModels/LogProbsResponse.cs @@ -4,19 +4,24 @@ namespace OpenAI.ObjectModels.SharedModels; public record LogProbsResponse { - [JsonPropertyName("tokens")] public List Tokens { get; set; } + [JsonPropertyName("tokens")] + public List Tokens { get; set; } - [JsonPropertyName("token_logprobs")] public List TokenLogProbs { get; set; } + [JsonPropertyName("token_logprobs")] + public List TokenLogProbs { get; set; } - [JsonPropertyName("top_logprobs")] public List> TopLogProbsRaw { get; set; } + [JsonPropertyName("top_logprobs")] + public List> TopLogProbsRaw { get; set; } public List TopLogProbs => TopLogProbsRaw.SelectMany(r => r.Select(a => new TopLogProbResponse - { - Key = a.Key, - LogProp = a.Value - })).ToList(); + { + Key = a.Key, + LogProp = a.Value + })) + .ToList(); - [JsonPropertyName("text_offset")] public List TextOffset { get; set; } + [JsonPropertyName("text_offset")] + public List TextOffset { get; set; } } public class TopLogProbResponse diff --git a/OpenAI.SDK/ObjectModels/SharedModels/MessageImageFile.cs b/OpenAI.SDK/ObjectModels/SharedModels/MessageImageFile.cs deleted file mode 100644 index 1636e8ca..00000000 --- a/OpenAI.SDK/ObjectModels/SharedModels/MessageImageFile.cs +++ /dev/null @@ -1,4 +0,0 @@ -using System.Text.Json.Serialization; - -namespace OpenAI.ObjectModels.SharedModels; - diff --git a/OpenAI.SDK/ObjectModels/SharedModels/MessageResponse.cs b/OpenAI.SDK/ObjectModels/SharedModels/MessageResponse.cs index 738f86d0..1135538f 100644 --- a/OpenAI.SDK/ObjectModels/SharedModels/MessageResponse.cs +++ b/OpenAI.SDK/ObjectModels/SharedModels/MessageResponse.cs @@ -7,7 +7,7 @@ namespace OpenAI.ObjectModels.SharedModels; /// /// Represents a message within a thread. /// -public record MessageResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.ICreatedAt, IOpenAiModels.IMetaData,IOpenAiModels.IAssistantId +public record MessageResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.ICreatedAt, IOpenAiModels.IMetaData, IOpenAiModels.IAssistantId { /// /// The thread ID that this message belongs to. @@ -35,7 +35,7 @@ public record MessageResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.I /// - /// On an incomplete message, details about why the message is incomplete. + /// On an incomplete message, details about why the message is incomplete. /// [JsonPropertyName("incomplete_details")] public IncompleteDetails? IncompleteDetails { get; set; } @@ -45,7 +45,7 @@ public record MessageResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.I /// [JsonPropertyName("completed_at")] public int? CompletedAt { get; set; } - + /// /// The Unix timestamp (in seconds) for when the run was completed. /// @@ -53,13 +53,8 @@ public record MessageResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.I public int? IncompleteAt { get; set; } /// - /// If applicable, the ID of the assistant that authored this message. - /// - [JsonPropertyName("assistant_id")] - public string? AssistantId { get; set; } - - /// - /// The ID of the run associated with the creation of this message. Value is null when messages are created manually using the create message or create thread endpoints. + /// The ID of the run associated with the creation of this message. Value is null when messages are created manually + /// using the create message or create thread endpoints. /// [JsonPropertyName("run_id")] public string? RunId { get; set; } @@ -72,6 +67,12 @@ public record MessageResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.I [JsonPropertyName("attachments")] public List Attachments { get; set; } + /// + /// If applicable, the ID of the assistant that authored this message. + /// + [JsonPropertyName("assistant_id")] + public string? AssistantId { get; set; } + /// /// The Unix timestamp (in seconds) for when the message was created. /// @@ -115,7 +116,7 @@ public record MessageContentResponse public MessageText? Text { get; set; } /// - /// References an image URL in the content of a message. + /// References an image URL in the content of a message. /// [JsonPropertyName("image_url")] public MessageImageUrl? ImageUrl { get; set; } diff --git a/OpenAI.SDK/ObjectModels/SharedModels/RunResponse.cs b/OpenAI.SDK/ObjectModels/SharedModels/RunResponse.cs index 6263f230..05a0904a 100644 --- a/OpenAI.SDK/ObjectModels/SharedModels/RunResponse.cs +++ b/OpenAI.SDK/ObjectModels/SharedModels/RunResponse.cs @@ -6,12 +6,10 @@ namespace OpenAI.ObjectModels.SharedModels; public record RunListResponse : DataWithPagingBaseResponse> { - } public record RunResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.IModel, IOpenAiModels.ICreatedAt, IOpenAiModels.IFileIds, IOpenAiModels.IMetaData { - /// /// The ID of the thread that was executed on as a part of this run. /// @@ -43,7 +41,7 @@ public record RunResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.IMode /// [JsonPropertyName("last_error")] public Error? LastError { get; set; } - + /// /// Details on why the run is incomplete. Will be null if the run is not incomplete. @@ -94,7 +92,8 @@ public record RunResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.IMode public List? Tools { get; set; } /// - /// Usage statistics related to the run. This value will be null if the run is not in a terminal state (i.e. in_progress, queued, etc.). + /// Usage statistics related to the run. This value will be null if the run is not in a terminal state (i.e. + /// in_progress, queued, etc.). /// [JsonPropertyName("usage")] public UsageResponse? Usage { get; set; } @@ -124,15 +123,18 @@ public record RunResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.IMode public TruncationStrategy? TruncationStrategy { get; set; } /// - /// Controls which (if any) tool is called by the model. none means the model will not call any tools and instead generates a message. + /// Controls which (if any) tool is called by the model. none means the model will not call any tools and instead + /// generates a message. /// auto is the default value and means the model can pick between generating a message or calling a tool. - /// Specifying a particular tool like {"type": "TOOL_TYPE"} or {"type": "function", "function": {"name": "my_function"}} forces the model to call that tool. + /// Specifying a particular tool like {"type": "TOOL_TYPE"} or {"type": "function", "function": {"name": + /// "my_function"}} forces the model to call that tool. /// [JsonPropertyName("tool_choice")] public object? ToolChoice { get; set; } /// - /// Specifies the format that the model must output. Compatible with GPT-4 Turbo and all GPT-3.5 Turbo models newer than gpt-3.5-turbo-1106. + /// Specifies the format that the model must output. Compatible with GPT-4 Turbo and all GPT-3.5 Turbo models newer + /// than gpt-3.5-turbo-1106. /// [JsonPropertyName("response_format")] public object? ResponseFormat { get; set; } diff --git a/OpenAI.SDK/ObjectModels/SharedModels/SharedImageRequestBaseModel.cs b/OpenAI.SDK/ObjectModels/SharedModels/SharedImageRequestBaseModel.cs index 8e74b512..a5fd609e 100644 --- a/OpenAI.SDK/ObjectModels/SharedModels/SharedImageRequestBaseModel.cs +++ b/OpenAI.SDK/ObjectModels/SharedModels/SharedImageRequestBaseModel.cs @@ -12,10 +12,10 @@ public record SharedImageRequestBaseModel public int? N { get; set; } /// - /// The size of the generated images. - /// Must be one of 256x256, 512x512, or 1024x1024 for dall-e-2. + /// The size of the generated images. + /// Must be one of 256x256, 512x512, or 1024x1024 for dall-e-2. /// Must be one of 1024x1024, 1792x1024, or 1024x1792 for dall-e-3 models. - ///

Check for possible values + ///

Check for possible values ///
[JsonPropertyName("size")] public string? Size { get; set; } @@ -39,4 +39,4 @@ public record SharedImageRequestBaseModel ///
[JsonPropertyName("model")] public string? Model { get; set; } -} +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/StaticValueHelper.cs b/OpenAI.SDK/ObjectModels/StaticValueHelper.cs index 1473fe0d..234d8544 100644 --- a/OpenAI.SDK/ObjectModels/StaticValueHelper.cs +++ b/OpenAI.SDK/ObjectModels/StaticValueHelper.cs @@ -14,6 +14,7 @@ public static class ToolType { public static string Function => "function"; } + public static class ToolChoiceType { public static string Function => ToolType.Function; @@ -21,6 +22,7 @@ public static class ToolChoiceType public static string None => "none"; } } + public static class ImageStatics { public static class Size @@ -28,11 +30,13 @@ public static class Size public static string Size256 => "256x256"; public static string Size512 => "512x512"; public static string Size1024 => "1024x1024"; + /// /// Only dall-e-3 model /// // ReSharper disable once InconsistentNaming public static string Size1792x1024 => "1792x1024"; + /// /// Only dall-e-3 model /// @@ -71,7 +75,6 @@ public static class ImageDetailTypes public static string High => "high"; public static string Low => "low"; public static string Auto => "auto"; - } } @@ -85,13 +88,13 @@ public static class ResponseFormat public static string VerboseJson => "verbose_json"; public static string Vtt => "vtt"; } - + public static class TimestampGranularity { public static string Word => "word"; public static string Segment => "segment"; } - + public static class CreateSpeechResponseFormat { public static string Mp3 => "mp3"; @@ -118,7 +121,6 @@ public static class ChatMessageRoles public static string Assistant => "assistant"; public static string Tool => "tool"; public static string Function => "function"; - } public static class AssistantsStatics @@ -170,5 +172,4 @@ public static class RequiredActionTypes public static string SubmitToolOutputs => "submit_tool_outputs"; } } - } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/UploadFilePurposes.cs b/OpenAI.SDK/ObjectModels/UploadFilePurposes.cs index 41b331d5..0e2faa92 100644 --- a/OpenAI.SDK/ObjectModels/UploadFilePurposes.cs +++ b/OpenAI.SDK/ObjectModels/UploadFilePurposes.cs @@ -5,7 +5,10 @@ /// Use "assistants" for Assistants and Message files, "vision" for Assistants image file inputs, "batch" for Batch /// API, and "fine-tune" for Fine-tuning. /// Upload File Purposes -/// Upload File Purpose Responses +/// +/// Upload File Purpose +/// Responses +/// ///
public static class UploadFilePurposes { @@ -17,7 +20,7 @@ public enum UploadFilePurpose AssistantsOutput, Vision, Batch, - BatchOutput, + BatchOutput } public const string Assistants = "assistants"; diff --git a/OpenAI.SDK/OpenAiOptions.cs b/OpenAI.SDK/OpenAiOptions.cs index d13d8cf7..bf42a08b 100644 --- a/OpenAI.SDK/OpenAiOptions.cs +++ b/OpenAI.SDK/OpenAiOptions.cs @@ -38,11 +38,12 @@ public class OpenAiOptions public ProviderType ProviderType { get; set; } = ProviderType.OpenAi; /// - /// Calls to the Assistants API require that you pass a beta HTTP header. - /// This is handled automatically if you’re using OpenAI’s official Python or Node.js SDKs. - /// assistants overview page. + /// Calls to the Assistants API require that you pass a beta HTTP header. + /// This is handled automatically if you’re using OpenAI’s official Python or Node.js SDKs. + /// assistants overview page. /// public string? Assistants => $"assistants={OpenAiDefaultAssistantsApiVersion}"; + /// /// For users who belong to multiple organizations, you can pass a header to specify which organization is used for an /// API request. Usage from these API requests will count against the specified organization's subscription quota. @@ -138,7 +139,7 @@ public string? DefaultEngineId /// A valid OpenAiSettings instance configured with the method inputs private static OpenAiOptions CreateAzureSettings(string apiKey, string deploymentId, string resourceName, string? apiVersion) { - return new OpenAiOptions + return new() { ProviderType = ProviderType.Azure, ResourceName = resourceName, @@ -158,7 +159,7 @@ private static OpenAiOptions CreateAzureSettings(string apiKey, string deploymen /// A valid OpenAiSettings instance configured with the method inputs private static OpenAiOptions CreateAzureSettingsWithBaseDomain(string apiKey, string deploymentId, string baseDomain, string? apiVersion) { - return new OpenAiOptions + return new() { ProviderType = ProviderType.Azure, BaseDomain = baseDomain, diff --git a/OpenAI.SDK/Tokenizer/GPT3/GPT3Settings.cs b/OpenAI.SDK/Tokenizer/GPT3/GPT3Settings.cs index 6951d0f0..172a4cf3 100644 --- a/OpenAI.SDK/Tokenizer/GPT3/GPT3Settings.cs +++ b/OpenAI.SDK/Tokenizer/GPT3/GPT3Settings.cs @@ -18,13 +18,13 @@ internal static class TokenizerGpt3Settings private static Dictionary, int> BuildBpeRanks() { var lines = EmbeddedResource.Read("vocab.bpe").Split('\n'); - var bpeMerges = new ArraySegment(lines, 1, lines.Length - 1) - .Where(x => x.Trim().Length > 0) + var bpeMerges = new ArraySegment(lines, 1, lines.Length - 1).Where(x => x.Trim().Length > 0) .Select(x => { var y = x.Split(' '); return new Tuple(y[0], y[1]); - }).ToList(); + }) + .ToList(); return DictZip(bpeMerges, Range(0, bpeMerges.Count)); } diff --git a/OpenAI.SDK/Tokenizer/GPT3/TokenizerGpt3.cs b/OpenAI.SDK/Tokenizer/GPT3/TokenizerGpt3.cs index 31103ec0..bdfe8c07 100644 --- a/OpenAI.SDK/Tokenizer/GPT3/TokenizerGpt3.cs +++ b/OpenAI.SDK/Tokenizer/GPT3/TokenizerGpt3.cs @@ -86,12 +86,9 @@ private static int Ord(string x) private static ConcurrentDictionary InitializeBytesToUnicodeCache() { - var bytes = Enumerable.Range(Ord("!"), Ord("~") + 1 - Ord("!")) - .Concat(Enumerable.Range(Ord("¡"), Ord("¬") + 1 - Ord("¡"))) - .Concat(Enumerable.Range(Ord("®"), Ord("ÿ") + 1 - Ord("®"))) - .ToList(); + var bytes = Enumerable.Range(Ord("!"), Ord("~") + 1 - Ord("!")).Concat(Enumerable.Range(Ord("¡"), Ord("¬") + 1 - Ord("¡"))).Concat(Enumerable.Range(Ord("®"), Ord("ÿ") + 1 - Ord("®"))).ToList(); - var chars = (from x in bytes select (char) x).ToList(); + var chars = (from x in bytes select (char)x).ToList(); var n = 0; for (var b = 0; b < 256; b++) @@ -102,12 +99,10 @@ private static ConcurrentDictionary InitializeBytesToUnicodeCache() } bytes.Add(b); - chars.Add((char) (256 + n++)); + chars.Add((char)(256 + n++)); } - return new ConcurrentDictionary(bytes - .Zip(chars, (k, v) => new {k, v}) - .ToDictionary(x => x.k, x => x.v)); + return new(bytes.Zip(chars, (k, v) => new { k, v }).ToDictionary(x => x.k, x => x.v)); } private static string BytePairEncoding(string token) @@ -204,7 +199,7 @@ private static Dictionary> GetPairs(IReadOnlyList w var currentChar = word[i]; if (!result.ContainsKey(prevChar)) { - result[prevChar] = new List(); + result[prevChar] = new(); } result[prevChar].Add(currentChar); diff --git a/OpenAI.Utilities.Tests/FunctionCallingHelperTests.cs b/OpenAI.Utilities.Tests/FunctionCallingHelperTests.cs index f6c95183..36cca248 100644 --- a/OpenAI.Utilities.Tests/FunctionCallingHelperTests.cs +++ b/OpenAI.Utilities.Tests/FunctionCallingHelperTests.cs @@ -243,25 +243,10 @@ internal class FunctionCallingTestClass public string StringParameter = null!; [FunctionDescription("Test Function")] - public int TestFunction( - [ParameterDescription("Int Parameter")] - int intParameter, - [ParameterDescription("Float Parameter")] - float floatParameter, - [ParameterDescription("Bool Parameter")] - bool boolParameter, - [ParameterDescription("String Parameter")] - string stringParameter, - [ParameterDescription(Description = "Enum Parameter", Enum = "Value1, Value2, Value3")] - TestEnum enumParameter, - [ParameterDescription("Enum Parameter 2")] - TestEnum enumParameter2, - [ParameterDescription(Description = "Required Int Parameter", Required = true)] - int requiredIntParameter, - [ParameterDescription(Description = "Not required Int Parameter", Required = false)] - int notRequiredIntParameter, - [ParameterDescription(Name = "OverriddenName", Description = "Overridden")] - int overriddenNameParameter) + public int TestFunction([ParameterDescription("Int Parameter")] int intParameter, [ParameterDescription("Float Parameter")] float floatParameter, [ParameterDescription("Bool Parameter")] bool boolParameter, + [ParameterDescription("String Parameter")] string stringParameter, [ParameterDescription(Description = "Enum Parameter", Enum = "Value1, Value2, Value3")] TestEnum enumParameter, + [ParameterDescription("Enum Parameter 2")] TestEnum enumParameter2, [ParameterDescription(Description = "Required Int Parameter", Required = true)] int requiredIntParameter, + [ParameterDescription(Description = "Not required Int Parameter", Required = false)] int notRequiredIntParameter, [ParameterDescription(Name = "OverriddenName", Description = "Overridden")] int overriddenNameParameter) { IntParameter = intParameter; @@ -301,4 +286,4 @@ public enum TestEnum Value1, Value2, Value3 -} +} \ No newline at end of file diff --git a/OpenAI.Utilities.Tests/OpenAI.Utilities.Tests.csproj b/OpenAI.Utilities.Tests/OpenAI.Utilities.Tests.csproj index 4cbd99bd..78d966d2 100644 --- a/OpenAI.Utilities.Tests/OpenAI.Utilities.Tests.csproj +++ b/OpenAI.Utilities.Tests/OpenAI.Utilities.Tests.csproj @@ -1,30 +1,30 @@  - - net8.0 - enable - enable - Latest - false - true - + + net8.0 + enable + enable + Latest + false + true + - - - - - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - - + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + - - - + + + - + \ No newline at end of file diff --git a/OpenAI.Utilities/Embedding/EmbeddingTools.cs b/OpenAI.Utilities/Embedding/EmbeddingTools.cs index 1ebb2a17..52c21412 100644 --- a/OpenAI.Utilities/Embedding/EmbeddingTools.cs +++ b/OpenAI.Utilities/Embedding/EmbeddingTools.cs @@ -5,7 +5,6 @@ using MathNet.Numerics; using Microsoft.Data.Analysis; using OpenAI.Interfaces; -using OpenAI.ObjectModels.RequestModels; using OpenAI.ObjectModels.ResponseModels; using OpenAI.Tokenizer.GPT3; @@ -134,7 +133,7 @@ public async Task ReadFilesAndCreateEmbeddingDataAsCsv(IEnumerable ReadFilesAndCreateEmbeddingDataAsCsv(IEnumerable public IEnumerable LoadFilesFromDirectory(string pathToDirectory) { - return !Path.Exists(pathToDirectory) - ? new List() - : Directory.EnumerateFiles(pathToDirectory).Select(LoadFile).Where(r => r != null).ToList()!; + return !Path.Exists(pathToDirectory) ? new() : Directory.EnumerateFiles(pathToDirectory).Select(LoadFile).Where(r => r != null).ToList()!; } /// @@ -268,11 +266,12 @@ public DataFrame ReadAndSplitData(string outputFilePath) /// public async Task> GetEmbeddings(IEnumerable texts) { - var embeddingTasks = texts.Select(async text => await _sdk.Embeddings.CreateEmbedding(new EmbeddingCreateRequest - { - Input = text, - Model = _embeddingModel - })).ToList(); + var embeddingTasks = texts.Select(async text => await _sdk.Embeddings.CreateEmbedding(new() + { + Input = text, + Model = _embeddingModel + })) + .ToList(); return (await Task.WhenAll(embeddingTasks)).ToList(); } @@ -292,7 +291,7 @@ public DataFrame AddEmbeddingsToDf(DataFrame df, List e var failedResult = embeddingResults.FirstOrDefault(result => !result.Successful); if (failedResult?.Error == null) { - throw new Exception("Unknown Error"); + throw new("Unknown Error"); } Console.WriteLine($"{failedResult.Error.Code}: {failedResult.Error.Message}"); @@ -358,7 +357,7 @@ public IEnumerable SplitIntoMany(string text) if (currentChunk.Length > 0) { chunks.Add(currentChunk); - currentChunk = new StringBuilder(); + currentChunk = new(); tokensInCurrentChunk = 0; } @@ -414,9 +413,7 @@ public PrimitiveDataFrameColumn DistancesFromEmbeddings(List qEm var text = File.ReadAllText(file, Encoding.UTF8); - var fileName = Path.GetFileNameWithoutExtension(file) - .Replace('-', ' ') - .Replace('_', ' '); + var fileName = Path.GetFileNameWithoutExtension(file).Replace('-', ' ').Replace('_', ' '); var textFile = new TextEmbeddingData { @@ -439,4 +436,4 @@ public async Task ReadAllDataInFolderAndCreateEmbeddingData(string pa var files = LoadFilesFromDirectory(pathToDirectory); return await PerformTextEmbedding(files, outputFileName); } -} +} \ No newline at end of file diff --git a/OpenAI.Utilities/Extensions/StringExtensions.cs b/OpenAI.Utilities/Extensions/StringExtensions.cs index 7d0bfbdd..f13b774e 100644 --- a/OpenAI.Utilities/Extensions/StringExtensions.cs +++ b/OpenAI.Utilities/Extensions/StringExtensions.cs @@ -24,4 +24,4 @@ public static string RemoveNewlines(this string input) [GeneratedRegex(" {2,}")] private static partial Regex MultipleSpacesToSingleSpace(); -} +} \ No newline at end of file diff --git a/OpenAI.Utilities/FunctionCalling/FunctionCallingHelper.cs b/OpenAI.Utilities/FunctionCalling/FunctionCallingHelper.cs index 9c8177a7..38616b25 100644 --- a/OpenAI.Utilities/FunctionCalling/FunctionCallingHelper.cs +++ b/OpenAI.Utilities/FunctionCalling/FunctionCallingHelper.cs @@ -21,8 +21,7 @@ public static FunctionDefinition GetFunctionDefinition(MethodInfo methodInfo) { var methodDescriptionAttribute = methodInfo.GetCustomAttribute(); - var result = new FunctionDefinitionBuilder( - methodDescriptionAttribute?.Name ?? methodInfo.Name, methodDescriptionAttribute?.Description); + var result = new FunctionDefinitionBuilder(methodDescriptionAttribute?.Name ?? methodInfo.Name, methodDescriptionAttribute?.Description); var parameters = methodInfo.GetParameters().ToList(); @@ -36,7 +35,7 @@ public static FunctionDefinition GetFunctionDefinition(MethodInfo methodInfo) switch (parameter.ParameterType, parameterDescriptionAttribute?.Type == null) { case (_, false): - definition = new PropertyDefinition + definition = new() { Type = parameterDescriptionAttribute!.Type!, Description = description @@ -57,22 +56,16 @@ public static FunctionDefinition GetFunctionDefinition(MethodInfo methodInfo) break; case ({ IsEnum: true }, _): - var enumValues = string.IsNullOrEmpty(parameterDescriptionAttribute?.Enum) - ? Enum.GetNames(parameter.ParameterType).ToList() - : parameterDescriptionAttribute.Enum.Split(',').Select(x => x.Trim()).ToList(); + var enumValues = string.IsNullOrEmpty(parameterDescriptionAttribute?.Enum) ? Enum.GetNames(parameter.ParameterType).ToList() : parameterDescriptionAttribute.Enum.Split(',').Select(x => x.Trim()).ToList(); - definition = - PropertyDefinition.DefineEnum(enumValues, description); + definition = PropertyDefinition.DefineEnum(enumValues, description); break; default: - throw new Exception($"Parameter type '{parameter.ParameterType}' not supported"); + throw new($"Parameter type '{parameter.ParameterType}' not supported"); } - result.AddParameter( - parameterDescriptionAttribute?.Name ?? parameter.Name!, - definition, - parameterDescriptionAttribute?.Required ?? true); + result.AddParameter(parameterDescriptionAttribute?.Name ?? parameter.Name!, definition, parameterDescriptionAttribute?.Required ?? true); } return result.Build(); @@ -80,12 +73,13 @@ public static FunctionDefinition GetFunctionDefinition(MethodInfo methodInfo) public static ToolDefinition GetToolDefinition(MethodInfo methodInfo) { - return new ToolDefinition() + return new() { Type = "function", Function = GetFunctionDefinition(methodInfo) }; } + /// /// Enumerates the methods in the provided object, and a returns a of /// for all methods @@ -118,14 +112,14 @@ public static List GetToolDefinitions(Type type) { var methods = type.GetMethods(); - var result = methods - .Select(method => new + var result = methods.Select(method => new { method, methodDescriptionAttribute = method.GetCustomAttribute() }) .Where(t => t.methodDescriptionAttribute != null) - .Select(t => GetToolDefinition(t.method)).ToList(); + .Select(t => GetToolDefinition(t.method)) + .ToList(); return result; } @@ -164,8 +158,7 @@ public static List GetToolDefinitions(Type type) if (!methodInfo.ReturnType.IsAssignableTo(typeof(T))) { - throw new InvalidFunctionCallException( - $"Method '{functionCall.Name}' on type '{obj.GetType()}' has return type '{methodInfo.ReturnType}' but expected '{typeof(T)}'"); + throw new InvalidFunctionCallException($"Method '{functionCall.Name}' on type '{obj.GetType()}' has return type '{methodInfo.ReturnType}' but expected '{typeof(T)}'"); } var parameters = methodInfo.GetParameters().ToList(); @@ -174,8 +167,7 @@ public static List GetToolDefinitions(Type type) foreach (var parameter in parameters) { - var parameterDescriptionAttribute = - parameter.GetCustomAttribute(); + var parameterDescriptionAttribute = parameter.GetCustomAttribute(); var name = parameterDescriptionAttribute?.Name ?? parameter.Name!; var argument = arguments.FirstOrDefault(x => x.Key == name); @@ -189,7 +181,7 @@ public static List GetToolDefinitions(Type type) } else { - throw new Exception($"Argument '{name}' not found"); + throw new($"Argument '{name}' not found"); } } else @@ -219,11 +211,8 @@ public static List GetToolDefinitions(Type type) } // If not found, then look for methods with the custom attribute - var methodsWithAttributes = type - .GetMethods() - .FirstOrDefault(m => m.GetCustomAttributes(typeof(FunctionDescriptionAttribute), false).FirstOrDefault() is FunctionDescriptionAttribute attr && attr.Name == functionCall.Name); + var methodsWithAttributes = type.GetMethods().FirstOrDefault(m => m.GetCustomAttributes(typeof(FunctionDescriptionAttribute), false).FirstOrDefault() is FunctionDescriptionAttribute attr && attr.Name == functionCall.Name); return methodsWithAttributes; } - -} +} \ No newline at end of file diff --git a/OpenAI.Utilities/FunctionCalling/FunctionDescriptionAttribute.cs b/OpenAI.Utilities/FunctionCalling/FunctionDescriptionAttribute.cs index 76e013c2..9b4d0d6f 100644 --- a/OpenAI.Utilities/FunctionCalling/FunctionDescriptionAttribute.cs +++ b/OpenAI.Utilities/FunctionCalling/FunctionDescriptionAttribute.cs @@ -24,4 +24,4 @@ public FunctionDescriptionAttribute(string? description = null) /// Description of the function /// public string? Description { get; set; } -} +} \ No newline at end of file diff --git a/OpenAI.Utilities/FunctionCalling/InvalidFunctionCallException.cs b/OpenAI.Utilities/FunctionCalling/InvalidFunctionCallException.cs index 257f1eec..ddb75e46 100644 --- a/OpenAI.Utilities/FunctionCalling/InvalidFunctionCallException.cs +++ b/OpenAI.Utilities/FunctionCalling/InvalidFunctionCallException.cs @@ -11,4 +11,4 @@ public class InvalidFunctionCallException : Exception public InvalidFunctionCallException(string message) : base(message) { } -} +} \ No newline at end of file diff --git a/OpenAI.Utilities/FunctionCalling/ParameterDescriptionAttribute.cs b/OpenAI.Utilities/FunctionCalling/ParameterDescriptionAttribute.cs index 20884917..748facb8 100644 --- a/OpenAI.Utilities/FunctionCalling/ParameterDescriptionAttribute.cs +++ b/OpenAI.Utilities/FunctionCalling/ParameterDescriptionAttribute.cs @@ -39,4 +39,4 @@ public ParameterDescriptionAttribute(string? description = null) /// Whether the parameter is required. If not provided, the parameter will be required. Default is true /// public bool Required { get; set; } = true; -} +} \ No newline at end of file diff --git a/OpenAI.UtilitiesPlayground/Program.cs b/OpenAI.UtilitiesPlayground/Program.cs index b736180b..8b7d2fbc 100644 --- a/OpenAI.UtilitiesPlayground/Program.cs +++ b/OpenAI.UtilitiesPlayground/Program.cs @@ -5,8 +5,7 @@ using OpenAI.Interfaces; using OpenAI.UtilitiesPlayground.TestHelpers; -var builder = new ConfigurationBuilder() - .AddUserSecrets(); +var builder = new ConfigurationBuilder().AddUserSecrets(); IConfiguration configuration = builder.Build(); var serviceCollection = new ServiceCollection(); diff --git a/OpenAI.UtilitiesPlayground/TestHelpers/EmbeddingTestHelpers.cs b/OpenAI.UtilitiesPlayground/TestHelpers/EmbeddingTestHelpers.cs index 3b9b1edd..c289b68a 100644 --- a/OpenAI.UtilitiesPlayground/TestHelpers/EmbeddingTestHelpers.cs +++ b/OpenAI.UtilitiesPlayground/TestHelpers/EmbeddingTestHelpers.cs @@ -11,9 +11,7 @@ public static async Task ExerciseEmbeddingTools(IOpenAIService openAIService) { IEmbeddingTools embeddingTools = new EmbeddingTools(openAIService, 500, Models.TextEmbeddingAdaV2); - var dataFrame = - await embeddingTools.ReadFilesAndCreateEmbeddingDataAsCsv(Path.Combine("Data", "OpenAI"), - "processed/scraped.csv"); + var dataFrame = await embeddingTools.ReadFilesAndCreateEmbeddingDataAsCsv(Path.Combine("Data", "OpenAI"), "processed/scraped.csv"); var dataFrame2 = embeddingTools.LoadEmbeddedDataFromCsv("processed/scraped.csv"); @@ -26,21 +24,17 @@ await embeddingTools.ReadFilesAndCreateEmbeddingDataAsCsv(Path.Combine("Data", " { var context = embeddingTools.CreateContext(question, dataFrame); - var completionResponse = await openAIService.ChatCompletion.CreateCompletion( - new ChatCompletionCreateRequest + var completionResponse = await openAIService.ChatCompletion.CreateCompletion(new() + { + Model = Models.Gpt_4, + Messages = new List { - Model = Models.Gpt_4, - Messages = new List - { - ChatMessage.FromSystem( - $"Answer the question based on the context below, and if the question can't be answered based on the context, say \"I don't know\".\n\nContext: {context}"), - ChatMessage.FromUser(question) - } - }); - - Console.WriteLine(completionResponse.Successful - ? completionResponse.Choices.First().Message.Content - : completionResponse.Error?.Message); + ChatMessage.FromSystem($"Answer the question based on the context below, and if the question can't be answered based on the context, say \"I don't know\".\n\nContext: {context}"), + ChatMessage.FromUser(question) + } + }); + + Console.WriteLine(completionResponse.Successful ? completionResponse.Choices.First().Message.Content : completionResponse.Error?.Message); } } while (true); } diff --git a/OpenAI.UtilitiesPlayground/TestHelpers/FunctionCallingTestHelpers.cs b/OpenAI.UtilitiesPlayground/TestHelpers/FunctionCallingTestHelpers.cs index eca42028..77b4ebc5 100644 --- a/OpenAI.UtilitiesPlayground/TestHelpers/FunctionCallingTestHelpers.cs +++ b/OpenAI.UtilitiesPlayground/TestHelpers/FunctionCallingTestHelpers.cs @@ -88,4 +88,4 @@ public float AdvancedMath(float a, float b, AdvancedOperators advancedOperator) }; } } -} +} \ No newline at end of file From 64e376b900c18473877f405ab1ae653bfd1f812d Mon Sep 17 00:00:00 2001 From: Tolga Kayhan Date: Sat, 15 Jun 2024 17:59:35 +0100 Subject: [PATCH 2/3] Improved Assistant streaming methods --- .../AssistantHelpers/RunTestHelper.cs | 137 ++++++++++++++++-- .../Extensions/JsonToObjectRouterExtension.cs | 22 +++ .../Extensions/StreamHandleExtension.cs | 39 ++++- OpenAI.SDK/Interfaces/IRunService.cs | 13 +- OpenAI.SDK/Managers/OpenAIRunService.cs | 20 ++- .../ResponseModels/BaseResponse.cs | 8 +- .../SharedModels/MessageResponse.cs | 5 + 7 files changed, 216 insertions(+), 28 deletions(-) create mode 100644 OpenAI.SDK/Extensions/JsonToObjectRouterExtension.cs diff --git a/OpenAI.Playground/TestHelpers/AssistantHelpers/RunTestHelper.cs b/OpenAI.Playground/TestHelpers/AssistantHelpers/RunTestHelper.cs index 1e6ec2ed..d0f7b0fd 100644 --- a/OpenAI.Playground/TestHelpers/AssistantHelpers/RunTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/AssistantHelpers/RunTestHelper.cs @@ -165,19 +165,58 @@ public static async Task CreateRunAsStreamTest(IOpenAIService openAI) var result = openAI.Beta.Runs.RunCreateAsStream(CreatedThreadId, new() { AssistantId = assistantResult.Id - }); + },justDataMode:false); await foreach (var run in result) { if (run.Successful) { - if (string.IsNullOrEmpty(run.Status)) + Console.WriteLine($"Event:{run.StreamEvent}"); + if (run is RunResponse runResponse) { - Console.Write("."); + if (string.IsNullOrEmpty(runResponse.Status)) + { + Console.Write("."); + } + else + { + ConsoleExtensions.WriteLine($"Run Id: {runResponse.Id}, Status: {runResponse.Status}"); + } + } + + else if (run is RunStepResponse runStepResponse) + { + if (string.IsNullOrEmpty(runStepResponse.Status)) + { + Console.Write("."); + } + else + { + ConsoleExtensions.WriteLine($"Run Step Id: {runStepResponse.Id}, Status: {runStepResponse.Status}"); + } + } + + else if (run is MessageResponse messageResponse) + { + if (string.IsNullOrEmpty(messageResponse.Id)) + { + Console.Write("."); + } + else + { + ConsoleExtensions.WriteLine($"Message Id: {messageResponse.Id}, Message: {messageResponse.Content?.FirstOrDefault()?.Text?.Value}"); + } } else { - ConsoleExtensions.WriteLine($"Run Id: {run.Id}, Status: {run.Status}"); + if (run.StreamEvent!=null) + { + Console.WriteLine(run.StreamEvent); + } + else + { + Console.Write("."); + } } } else @@ -450,13 +489,52 @@ public static async Task SubmitToolOutputsAsStreamToRunTest(IOpenAIService openA { if (run.Successful) { - if (string.IsNullOrEmpty(run.Status)) + Console.WriteLine($"Event:{run.StreamEvent}"); + if (run is RunResponse runResponse) { - Console.Write("."); + if (string.IsNullOrEmpty(runResponse.Status)) + { + Console.Write("."); + } + else + { + ConsoleExtensions.WriteLine($"Run Id: {runResponse.Id}, Status: {runResponse.Status}"); + } + } + + else if (run is RunStepResponse runStepResponse) + { + if (string.IsNullOrEmpty(runStepResponse.Status)) + { + Console.Write("."); + } + else + { + ConsoleExtensions.WriteLine($"Run Step Id: {runStepResponse.Id}, Status: {runStepResponse.Status}"); + } + } + + else if (run is MessageResponse messageResponse) + { + if (string.IsNullOrEmpty(messageResponse.Id)) + { + Console.Write("."); + } + else + { + ConsoleExtensions.WriteLine($"Message Id: {messageResponse.Id}, Message: {messageResponse.Content?.FirstOrDefault()?.Text?.Value}"); + } } else { - ConsoleExtensions.WriteLine($"Run Id: {run.Id}, Status: {run.Status}"); + if (run.StreamEvent != null) + { + Console.WriteLine(run.StreamEvent); + } + else + { + Console.Write("."); + } } } else @@ -642,13 +720,52 @@ public static async Task CreateThreadAndRunAsStream(IOpenAIService sdk) { if (run.Successful) { - if (string.IsNullOrEmpty(run.Status)) + Console.WriteLine($"Event:{run.StreamEvent}"); + if (run is RunResponse runResponse) { - Console.Write("."); + if (string.IsNullOrEmpty(runResponse.Status)) + { + Console.Write("."); + } + else + { + ConsoleExtensions.WriteLine($"Run Id: {runResponse.Id}, Status: {runResponse.Status}"); + } + } + + else if (run is RunStepResponse runStepResponse) + { + if (string.IsNullOrEmpty(runStepResponse.Status)) + { + Console.Write("."); + } + else + { + ConsoleExtensions.WriteLine($"Run Step Id: {runStepResponse.Id}, Status: {runStepResponse.Status}"); + } + } + + else if (run is MessageResponse messageResponse) + { + if (string.IsNullOrEmpty(messageResponse.Id)) + { + Console.Write("."); + } + else + { + ConsoleExtensions.WriteLine($"Message Id: {messageResponse.Id}, Message: {messageResponse.Content?.FirstOrDefault()?.Text?.Value}"); + } } else { - ConsoleExtensions.WriteLine($"Run Id: {run.Id}, Status: {run.Status}"); + if (run.StreamEvent != null) + { + Console.WriteLine(run.StreamEvent); + } + else + { + Console.Write("."); + } } } else diff --git a/OpenAI.SDK/Extensions/JsonToObjectRouterExtension.cs b/OpenAI.SDK/Extensions/JsonToObjectRouterExtension.cs new file mode 100644 index 00000000..fda64928 --- /dev/null +++ b/OpenAI.SDK/Extensions/JsonToObjectRouterExtension.cs @@ -0,0 +1,22 @@ +using System.Text.Json; +using OpenAI.ObjectModels.ResponseModels; +using OpenAI.ObjectModels.SharedModels; + +namespace OpenAI.Extensions; + +public static class JsonToObjectRouterExtension +{ + public static Type Route(string json) + { + var apiResponse = JsonSerializer.Deserialize(json); + + return apiResponse?.ObjectTypeName switch + { + "thread.run.step" => typeof(RunStepResponse), + "thread.run" => typeof(RunResponse), + "thread.message" => typeof(MessageResponse), + "thread.message.delta" => typeof(MessageResponse), + _ => typeof(BaseResponse) + }; + } +} \ No newline at end of file diff --git a/OpenAI.SDK/Extensions/StreamHandleExtension.cs b/OpenAI.SDK/Extensions/StreamHandleExtension.cs index 60c68a5c..3344bda4 100644 --- a/OpenAI.SDK/Extensions/StreamHandleExtension.cs +++ b/OpenAI.SDK/Extensions/StreamHandleExtension.cs @@ -1,4 +1,5 @@ -using System.Runtime.CompilerServices; +using System.Collections.Generic; +using System.Runtime.CompilerServices; using System.Text.Json; using OpenAI.ObjectModels; using OpenAI.ObjectModels.RequestModels; @@ -8,6 +9,10 @@ namespace OpenAI.Extensions; public static class StreamHandleExtension { + public static async IAsyncEnumerable AsStream(this HttpResponseMessage response, bool justDataMode = true, [EnumeratorCancellation] CancellationToken cancellationToken = default) + { + await foreach (var baseResponse in AsStream(response, justDataMode, cancellationToken)) yield return baseResponse; + } public static async IAsyncEnumerable AsStream(this HttpResponseMessage response, bool justDataMode = true, [EnumeratorCancellation] CancellationToken cancellationToken = default) where TResponse : BaseResponse, new() { @@ -20,13 +25,15 @@ public static async IAsyncEnumerable AsStream(this HttpRes await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken); using var reader = new StreamReader(stream); - + string? tempStreamEvent = null; + bool isEventDelta; // Continuously read the stream until the end of it while (true) { cancellationToken.ThrowIfCancellationRequested(); var line = await reader.ReadLineAsync(); + // Console.WriteLine("---" + line); // Break the loop if we have reached the end of the stream if (line == null) { @@ -39,11 +46,28 @@ public static async IAsyncEnumerable AsStream(this HttpRes continue; } + if (line.StartsWith("event: ")) + { + line = line.RemoveIfStartWith("event: "); + tempStreamEvent = line; + isEventDelta = true; + } + else + { + isEventDelta = false; + } + if (justDataMode && !line.StartsWith("data: ")) { continue; } + if (!justDataMode && isEventDelta ) + { + yield return new(){ObjectTypeName = "base.stream.event",StreamEvent = tempStreamEvent}; + continue; + } + line = line.RemoveIfStartWith("data: "); // Exit the loop if the stream is done @@ -56,7 +80,14 @@ public static async IAsyncEnumerable AsStream(this HttpRes try { // When the response is good, each line is a serializable CompletionCreateRequest - block = JsonSerializer.Deserialize(line); + if (typeof(TResponse) == typeof(BaseResponse)) + { + block =JsonSerializer.Deserialize(line, JsonToObjectRouterExtension.Route(line), new JsonSerializerOptions()) as TResponse; + } + else + { + block = JsonSerializer.Deserialize(line); + } } catch (Exception) { @@ -78,6 +109,8 @@ public static async IAsyncEnumerable AsStream(this HttpRes { block.HttpStatusCode = httpStatusCode; block.HeaderValues = headerValues; + block.StreamEvent = tempStreamEvent; + tempStreamEvent = null; yield return block; } } diff --git a/OpenAI.SDK/Interfaces/IRunService.cs b/OpenAI.SDK/Interfaces/IRunService.cs index 85c5c5dd..dceec99e 100644 --- a/OpenAI.SDK/Interfaces/IRunService.cs +++ b/OpenAI.SDK/Interfaces/IRunService.cs @@ -1,5 +1,6 @@ using System.Runtime.CompilerServices; using OpenAI.ObjectModels.RequestModels; +using OpenAI.ObjectModels.ResponseModels; using OpenAI.ObjectModels.SharedModels; namespace OpenAI.Interfaces; @@ -24,8 +25,8 @@ public interface IRunService /// /// /// - /// - IAsyncEnumerable RunCreateAsStream(string threadId, RunCreateRequest request, string? modelId = null, bool justDataMode = true, [EnumeratorCancellation] CancellationToken cancellationToken = default); + /// also returns ,, + IAsyncEnumerable RunCreateAsStream(string threadId, RunCreateRequest request, string? modelId = null, bool justDataMode = true, [EnumeratorCancellation] CancellationToken cancellationToken = default); /// /// Retrieves a run. @@ -71,9 +72,10 @@ public interface IRunService /// /// /// + /// /// - /// - IAsyncEnumerable RunSubmitToolOutputsAsStream(string threadId, string runId, SubmitToolOutputsToRunRequest request, [EnumeratorCancellation] CancellationToken cancellationToken = default); + /// also returns ,, + IAsyncEnumerable RunSubmitToolOutputsAsStream(string threadId, string runId, SubmitToolOutputsToRunRequest request, bool justDataMode = true, [EnumeratorCancellation] CancellationToken cancellationToken = default); /// /// Modifies a run. @@ -93,7 +95,8 @@ public interface IRunService /// /// Create a thread and run it in one request as Stream. /// - IAsyncEnumerable CreateThreadAndRunAsStream(CreateThreadAndRunRequest createThreadAndRunRequest, string? modelId = null, bool justDataMode = true, [EnumeratorCancellation] CancellationToken cancellationToken = default); + /// also returns ,, + IAsyncEnumerable CreateThreadAndRunAsStream(CreateThreadAndRunRequest createThreadAndRunRequest, string? modelId = null, bool justDataMode = true, [EnumeratorCancellation] CancellationToken cancellationToken = default); /// /// Returns a list of runs belonging to a thread. diff --git a/OpenAI.SDK/Managers/OpenAIRunService.cs b/OpenAI.SDK/Managers/OpenAIRunService.cs index 5a7812cd..274b5525 100644 --- a/OpenAI.SDK/Managers/OpenAIRunService.cs +++ b/OpenAI.SDK/Managers/OpenAIRunService.cs @@ -2,6 +2,7 @@ using OpenAI.Extensions; using OpenAI.Interfaces; using OpenAI.ObjectModels.RequestModels; +using OpenAI.ObjectModels.ResponseModels; using OpenAI.ObjectModels.SharedModels; namespace OpenAI.Managers; @@ -36,7 +37,7 @@ public async Task RunCreate(string threadId, RunCreateRequest reque /// /// /// - public async IAsyncEnumerable RunCreateAsStream(string threadId, RunCreateRequest request, string? modelId = null, bool justDataMode = true, [EnumeratorCancellation] CancellationToken cancellationToken = default) + public async IAsyncEnumerable RunCreateAsStream(string threadId, RunCreateRequest request, string? modelId = null, bool justDataMode = true, [EnumeratorCancellation] CancellationToken cancellationToken = default) { // Mark the request as streaming request.Stream = true; @@ -52,7 +53,10 @@ public async IAsyncEnumerable RunCreateAsStream(string threadId, Ru yield break; } - await foreach (var baseResponse in response.AsStream(cancellationToken: cancellationToken)) yield return baseResponse; + await foreach (var baseResponse in response.AsStream(justDataMode: justDataMode,cancellationToken: cancellationToken)) + { + yield return baseResponse; + } } @@ -142,7 +146,7 @@ public async Task RunSubmitToolOutputs(string threadId, string runI return await _httpClient.PostAndReadAsAsync(_endpointProvider.RunSubmitToolOutputs(threadId, runId), request, cancellationToken); } - public async IAsyncEnumerable RunSubmitToolOutputsAsStream(string threadId, string runId, SubmitToolOutputsToRunRequest request, [EnumeratorCancellation] CancellationToken cancellationToken = default) + public async IAsyncEnumerable RunSubmitToolOutputsAsStream(string threadId, string runId, SubmitToolOutputsToRunRequest request, bool justDataMode = true, [EnumeratorCancellation] CancellationToken cancellationToken = default) { // Mark the request as streaming request.Stream = true; @@ -152,11 +156,11 @@ public async IAsyncEnumerable RunSubmitToolOutputsAsStream(string t if (!response.IsSuccessStatusCode) { - yield return await response.HandleResponseContent(cancellationToken); + yield return await response.HandleResponseContent(cancellationToken); yield break; } - await foreach (var baseResponse in response.AsStream(cancellationToken: cancellationToken)) yield return baseResponse; + await foreach (var baseResponse in response.AsStream(justDataMode: justDataMode, cancellationToken: cancellationToken)) yield return baseResponse; } /// @@ -165,7 +169,7 @@ public async Task CreateThreadAndRun(CreateThreadAndRunRequest requ return await _httpClient.PostAndReadAsAsync(_endpointProvider.ThreadAndRunCreate(), requestBody, cancellationToken); } - public async IAsyncEnumerable CreateThreadAndRunAsStream(CreateThreadAndRunRequest createThreadAndRunRequest, string? modelId = null, bool justDataMode = true, + public async IAsyncEnumerable CreateThreadAndRunAsStream(CreateThreadAndRunRequest createThreadAndRunRequest, string? modelId = null, bool justDataMode = true, [EnumeratorCancellation] CancellationToken cancellationToken = default) { // Mark the request as streaming @@ -178,11 +182,11 @@ public async IAsyncEnumerable CreateThreadAndRunAsStream(CreateThre if (!response.IsSuccessStatusCode) { - yield return await response.HandleResponseContent(cancellationToken); + yield return await response.HandleResponseContent(cancellationToken); yield break; } - await foreach (var baseResponse in response.AsStream(cancellationToken: cancellationToken)) yield return baseResponse; + await foreach (var baseResponse in response.AsStream(justDataMode: justDataMode, cancellationToken: cancellationToken)) yield return baseResponse; } /// diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/BaseResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/BaseResponse.cs index 9e5e0f07..3273e0c1 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/BaseResponse.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/BaseResponse.cs @@ -5,11 +5,15 @@ namespace OpenAI.ObjectModels.ResponseModels; -public record BaseResponse +public record ObjectBaseResponse { [JsonPropertyName("object")] public string? ObjectTypeName { get; set; } - +} +public record BaseResponse: ObjectBaseResponse +{ + [JsonPropertyName("StreamEvent")] + public string? StreamEvent { get; set; } public bool Successful => Error == null; [JsonPropertyName("error")] diff --git a/OpenAI.SDK/ObjectModels/SharedModels/MessageResponse.cs b/OpenAI.SDK/ObjectModels/SharedModels/MessageResponse.cs index 1135538f..09bd682f 100644 --- a/OpenAI.SDK/ObjectModels/SharedModels/MessageResponse.cs +++ b/OpenAI.SDK/ObjectModels/SharedModels/MessageResponse.cs @@ -9,6 +9,11 @@ namespace OpenAI.ObjectModels.SharedModels; /// public record MessageResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.ICreatedAt, IOpenAiModels.IMetaData, IOpenAiModels.IAssistantId { + [JsonPropertyName("delta")] + public MessageResponse Delta + { + set => Content = value.Content; + } /// /// The thread ID that this message belongs to. /// From 88c3c1d8c60b8d66bfd1f1a4ff2f0cc85b1787df Mon Sep 17 00:00:00 2001 From: Tolga Kayhan Date: Sat, 15 Jun 2024 18:09:55 +0100 Subject: [PATCH 3/3] version bump --- OpenAI.SDK/OpenAI.csproj | 2 +- Readme.md | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/OpenAI.SDK/OpenAI.csproj b/OpenAI.SDK/OpenAI.csproj index 4c2e1e0f..7b1f68bd 100644 --- a/OpenAI.SDK/OpenAI.csproj +++ b/OpenAI.SDK/OpenAI.csproj @@ -10,7 +10,7 @@ OpenAI-Betalgo.png true OpenAI SDK by Betalgo - 8.4.0 + 8.5.0 Tolga Kayhan, Betalgo Betalgo Up Ltd. OpenAI ChatGPT, Whisper, GPT-4 and DALL·E dotnet SDK diff --git a/Readme.md b/Readme.md index b5fd43dc..6f866aac 100644 --- a/Readme.md +++ b/Readme.md @@ -116,9 +116,9 @@ Due to time constraints, not all methods have been thoroughly tested or fully do Needless to say, I cannot accept responsibility for any damage caused by using the library. ## Changelog -### 8.4.0 -- Added Stream support for submitToolOutputsToRun, createRun, and createThreadAndRun -- 🎉 With this update, we are now in sync with OpenAI's latest API changes. We shouldn't have any missing features as of now. +### 8.5.0 +- Assistant Stream now returns the `BaseResponse` type, but they can be cast to the appropriate types(`RunStepResponse`,`RunResponse`,`MessageResponse`). The reason for this change is that we realized the stream API returns multiple different object types rather than returning a single object type. +- The Base Response now has a `StreamEvent` field, which can be used to determine the type of event while streaming. ### [More Change Logs](https://github.com/betalgo/openai/wiki/Change-Logs) @@ -129,4 +129,4 @@ For any issues, contributions, or feedback, feel free to reach out or submit a p Betalgo X: [Betalgo (@Betalgo) / X (twitter.com)](https://twitter.com/Betalgo) Betalgo Linkedin: [Betalgo | LinkedIn](https://www.linkedin.com/company/betalgo-up ) Tolga X: [Tolga Kayhan (@kayhantolga) / X (twitter.com)](https://twitter.com/kayhantolga) -Tolga Linkedin: [Tolga Kayhan | LinkedIn](https://www.linkedin.com/in/kayhantolga/) +Tolga Linkedin: [Tolga Kayhan | LinkedIn](https://www.linkedin.com/in/kayhantolga/) \ No newline at end of file