From b5ade7885675d04a482773a9291fa96a5ca66b7f Mon Sep 17 00:00:00 2001 From: PeterHu Date: Tue, 2 Jan 2024 14:59:40 +0800 Subject: [PATCH 01/26] [ADD]: Added beta assistants API --- OpenAI.Playground/ConsoleExtensions.cs | 2 +- OpenAI.Playground/OpenAI.Playground.csproj | 6 + OpenAI.Playground/Program.cs | 5 +- .../SampleData/betterway_corp.csv | 2 + .../SampleData/betterway_corp.jsonl | 1 + OpenAI.Playground/StringExtension.cs | 25 ++ .../TestHelpers/AssistantTestHelper.cs | 254 ++++++++++++++++++ .../TestHelpers/MessageTestHelper.cs | 67 +++++ .../TestHelpers/RunTestHelper.cs | 113 ++++++++ .../TestHelpers/ThreadTestHelper.cs | 78 ++++++ .../AzureOpenAiEndpointProvider.cs | 183 +++++++++++++ .../IOpenAiEndpointProvider.cs | 29 ++ .../OpenAiEndpointProvider.cs | 188 ++++++++++++- OpenAI.SDK/Extensions/HttpclientExtensions.cs | 6 + OpenAI.SDK/Interfaces/IAssistantService.cs | 92 +++++++ OpenAI.SDK/Interfaces/IBetaService.cs | 19 ++ OpenAI.SDK/Interfaces/IMessageService.cs | 33 +++ OpenAI.SDK/Interfaces/IOpenAIService.cs | 4 + OpenAI.SDK/Interfaces/IRunService.cs | 54 ++++ OpenAI.SDK/Interfaces/IThreadService.cs | 38 +++ OpenAI.SDK/Managers/OpenAIAssistantService.cs | 95 +++++++ OpenAI.SDK/Managers/OpenAIBetaService.cs | 23 ++ OpenAI.SDK/Managers/OpenAIMessageService.cs | 48 ++++ OpenAI.SDK/Managers/OpenAIRunService.cs | 83 ++++++ OpenAI.SDK/Managers/OpenAIService.cs | 9 +- OpenAI.SDK/Managers/OpenAIThreadService.cs | 56 ++++ .../RequestModels/AssistantCreateRequest.cs | 57 ++++ .../AssistantFileCreateRequest.cs | 20 ++ .../RequestModels/AssistantFileListRequest.cs | 12 + .../RequestModels/AssistantListRequest.cs | 12 + .../RequestModels/AssistantModifyRequest.cs | 56 ++++ .../RequestModels/BaseListRequest.cs | 68 +++++ .../RequestModels/MessageCreateRequest.cs | 46 ++++ .../RequestModels/MessageFileListRequest.cs | 12 + .../RequestModels/MessageListRequest.cs | 12 + .../RequestModels/RunCreateRequest.cs | 51 ++++ .../RequestModels/RunListRequest.cs | 12 + .../RequestModels/RunStepListRequest.cs | 12 + .../SubmitToolOutputsToRunRequest.cs | 40 +++ .../RequestModels/ThreadCreateRequest.cs | 27 ++ .../RequestModels/ToolDefinition.cs | 9 + .../AssistantFileListResponse.cs | 22 ++ .../ResponseModels/AssistantListResponse.cs | 22 ++ .../ResponseModels/MessageListResponse.cs | 22 ++ .../SharedModels/AssistantFileResponse.cs | 31 +++ .../SharedModels/AssistantResponse.cs | 71 +++++ .../SharedModels/AssistatntFileResponse.cs | 31 +++ .../SharedModels/DeletionStatusResponse.cs | 25 ++ .../SharedModels/IOpenAiModels.cs | 15 ++ .../ObjectModels/SharedModels/LastError.cs | 24 ++ .../SharedModels/MessageAnnotation.cs | 44 +++ .../SharedModels/MessageImageFile.cs | 21 ++ .../SharedModels/MessageResponse.cs | 97 +++++++ .../ObjectModels/SharedModels/MessageText.cs | 27 ++ .../SharedModels/RequiredAction.cs | 37 +++ .../ObjectModels/SharedModels/RunResponse.cs | 136 ++++++++++ .../SharedModels/ThreadResponse.cs | 31 +++ OpenAI.SDK/ObjectModels/StaticValueHelper.cs | 52 ++++ OpenAI.SDK/ObjectModels/UploadFilePurposes.cs | 6 +- OpenAI.SDK/OpenAiOptions.cs | 8 +- 60 files changed, 2674 insertions(+), 7 deletions(-) create mode 100644 OpenAI.Playground/SampleData/betterway_corp.csv create mode 100644 OpenAI.Playground/SampleData/betterway_corp.jsonl create mode 100644 OpenAI.Playground/StringExtension.cs create mode 100644 OpenAI.Playground/TestHelpers/AssistantTestHelper.cs create mode 100644 OpenAI.Playground/TestHelpers/MessageTestHelper.cs create mode 100644 OpenAI.Playground/TestHelpers/RunTestHelper.cs create mode 100644 OpenAI.Playground/TestHelpers/ThreadTestHelper.cs create mode 100644 OpenAI.SDK/Interfaces/IAssistantService.cs create mode 100644 OpenAI.SDK/Interfaces/IBetaService.cs create mode 100644 OpenAI.SDK/Interfaces/IMessageService.cs create mode 100644 OpenAI.SDK/Interfaces/IRunService.cs create mode 100644 OpenAI.SDK/Interfaces/IThreadService.cs create mode 100644 OpenAI.SDK/Managers/OpenAIAssistantService.cs create mode 100644 OpenAI.SDK/Managers/OpenAIBetaService.cs create mode 100644 OpenAI.SDK/Managers/OpenAIMessageService.cs create mode 100644 OpenAI.SDK/Managers/OpenAIRunService.cs create mode 100644 OpenAI.SDK/Managers/OpenAIThreadService.cs create mode 100644 OpenAI.SDK/ObjectModels/RequestModels/AssistantCreateRequest.cs create mode 100644 OpenAI.SDK/ObjectModels/RequestModels/AssistantFileCreateRequest.cs create mode 100644 OpenAI.SDK/ObjectModels/RequestModels/AssistantFileListRequest.cs create mode 100644 OpenAI.SDK/ObjectModels/RequestModels/AssistantListRequest.cs create mode 100644 OpenAI.SDK/ObjectModels/RequestModels/AssistantModifyRequest.cs create mode 100644 OpenAI.SDK/ObjectModels/RequestModels/BaseListRequest.cs create mode 100644 OpenAI.SDK/ObjectModels/RequestModels/MessageCreateRequest.cs create mode 100644 OpenAI.SDK/ObjectModels/RequestModels/MessageFileListRequest.cs create mode 100644 OpenAI.SDK/ObjectModels/RequestModels/MessageListRequest.cs create mode 100644 OpenAI.SDK/ObjectModels/RequestModels/RunCreateRequest.cs create mode 100644 OpenAI.SDK/ObjectModels/RequestModels/RunListRequest.cs create mode 100644 OpenAI.SDK/ObjectModels/RequestModels/RunStepListRequest.cs create mode 100644 OpenAI.SDK/ObjectModels/RequestModels/SubmitToolOutputsToRunRequest.cs create mode 100644 OpenAI.SDK/ObjectModels/RequestModels/ThreadCreateRequest.cs create mode 100644 OpenAI.SDK/ObjectModels/ResponseModels/AssistantFileListResponse.cs create mode 100644 OpenAI.SDK/ObjectModels/ResponseModels/AssistantListResponse.cs create mode 100644 OpenAI.SDK/ObjectModels/ResponseModels/MessageListResponse.cs create mode 100644 OpenAI.SDK/ObjectModels/SharedModels/AssistantFileResponse.cs create mode 100644 OpenAI.SDK/ObjectModels/SharedModels/AssistantResponse.cs create mode 100644 OpenAI.SDK/ObjectModels/SharedModels/AssistatntFileResponse.cs create mode 100644 OpenAI.SDK/ObjectModels/SharedModels/DeletionStatusResponse.cs create mode 100644 OpenAI.SDK/ObjectModels/SharedModels/LastError.cs create mode 100644 OpenAI.SDK/ObjectModels/SharedModels/MessageAnnotation.cs create mode 100644 OpenAI.SDK/ObjectModels/SharedModels/MessageImageFile.cs create mode 100644 OpenAI.SDK/ObjectModels/SharedModels/MessageResponse.cs create mode 100644 OpenAI.SDK/ObjectModels/SharedModels/MessageText.cs create mode 100644 OpenAI.SDK/ObjectModels/SharedModels/RequiredAction.cs create mode 100644 OpenAI.SDK/ObjectModels/SharedModels/RunResponse.cs create mode 100644 OpenAI.SDK/ObjectModels/SharedModels/ThreadResponse.cs diff --git a/OpenAI.Playground/ConsoleExtensions.cs b/OpenAI.Playground/ConsoleExtensions.cs index bbf83c8b..83407ab2 100644 --- a/OpenAI.Playground/ConsoleExtensions.cs +++ b/OpenAI.Playground/ConsoleExtensions.cs @@ -2,7 +2,7 @@ public static class ConsoleExtensions { - public static void WriteLine(string value, ConsoleColor color) + public static void WriteLine(string value, ConsoleColor color = ConsoleColor.Cyan) { var defaultColor = Console.ForegroundColor; Console.ForegroundColor = color; diff --git a/OpenAI.Playground/OpenAI.Playground.csproj b/OpenAI.Playground/OpenAI.Playground.csproj index 258aaa00..e10ee85c 100644 --- a/OpenAI.Playground/OpenAI.Playground.csproj +++ b/OpenAI.Playground/OpenAI.Playground.csproj @@ -53,6 +53,12 @@ PreserveNewest + + Always + + + Always + PreserveNewest diff --git a/OpenAI.Playground/Program.cs b/OpenAI.Playground/Program.cs index 2b8f0e8c..af4163af 100644 --- a/OpenAI.Playground/Program.cs +++ b/OpenAI.Playground/Program.cs @@ -42,7 +42,10 @@ // | / \ / \ | \ /) | ( \ /o\ / ) | (\ / | / \ / \ | // |-----------------------------------------------------------------------| -await ChatCompletionTestHelper.RunSimpleChatCompletionTest(sdk); +//Assistants +await AssistantTestHelper.RunHowAssistantsWorkTest(sdk); + +//await ChatCompletionTestHelper.RunSimpleChatCompletionTest(sdk); //await ChatCompletionTestHelper.RunSimpleCompletionStreamTest(sdk); // Vision diff --git a/OpenAI.Playground/SampleData/betterway_corp.csv b/OpenAI.Playground/SampleData/betterway_corp.csv new file mode 100644 index 00000000..e28b8eda --- /dev/null +++ b/OpenAI.Playground/SampleData/betterway_corp.csv @@ -0,0 +1,2 @@ +浙江佳程供应链有限公司具体在哪?,"浙江佳程供应链有限公司,位于浙江省金华市婺城区八一北街615号佳程国际商务中心" +请介绍下浙江佳程供应链公司。,"浙江佳程供应链公司成立于 2011年,是一家专注于跨境物流的创新供应链服务企业,旗下子公司遍布全国和海外,主要涉及金华、义乌、宁波、沈阳、天津、青岛、济南、苏州、成都、新加坡、德国、俄罗斯等地。" diff --git a/OpenAI.Playground/SampleData/betterway_corp.jsonl b/OpenAI.Playground/SampleData/betterway_corp.jsonl new file mode 100644 index 00000000..79ab3294 --- /dev/null +++ b/OpenAI.Playground/SampleData/betterway_corp.jsonl @@ -0,0 +1 @@ +{"messages":[{"role":"system","content":"浣犳槸涓涓彁渚涚墿娴佷緵搴旈摼涓撲笟鍔╂墜"},{"role":"user","content":"娴欐睙浣崇▼渚涘簲閾炬湁闄愬叕鍙稿叿浣撳湪鍝紵"},{"role":"assistant","content":"娴欐睙浣崇▼渚涘簲閾炬湁闄愬叕鍙,浣嶄簬娴欐睙鐪侀噾鍗庡競濠哄煄鍖哄叓涓鍖楄615鍙蜂匠绋嬪浗闄呭晢鍔′腑蹇 "},{"role":"user","content":"璇蜂粙缁嶄笅娴欐睙浣崇▼渚涘簲閾惧叕鍙搞"},{"role":"assistant","content":"娴欐睙浣崇▼渚涘簲閾惧叕鍙告垚绔嬩簬 2011骞,鏄竴瀹朵笓娉ㄤ簬璺ㄥ鐗╂祦鐨勫垱鏂颁緵搴旈摼鏈嶅姟浼佷笟,鏃椾笅瀛愬叕鍙搁亶甯冨叏鍥藉拰娴峰,涓昏娑夊強閲戝崕銆佷箟涔屻佸畞娉€佹矆闃炽佸ぉ娲ャ侀潚宀涖佹祹鍗椼佽嫃宸炪佹垚閮姐佹柊鍔犲潯銆佸痉鍥姐佷縿缃楁柉绛夊湴銆"}]} \ No newline at end of file diff --git a/OpenAI.Playground/StringExtension.cs b/OpenAI.Playground/StringExtension.cs new file mode 100644 index 00000000..a4240df7 --- /dev/null +++ b/OpenAI.Playground/StringExtension.cs @@ -0,0 +1,25 @@ +锘縰sing System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http.Json; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; + +namespace OpenAI.Playground +{ + public static class StringExtension + { + public static string ToJson(this object s) + { + if (s == null) return null; + return JsonSerializer.Serialize(s); + } + + public static T D(this string json) where T : class + { + if (string.IsNullOrWhiteSpace(json)) return null; + return JsonSerializer.Deserialize(json); + } + } +} diff --git a/OpenAI.Playground/TestHelpers/AssistantTestHelper.cs b/OpenAI.Playground/TestHelpers/AssistantTestHelper.cs new file mode 100644 index 00000000..318849db --- /dev/null +++ b/OpenAI.Playground/TestHelpers/AssistantTestHelper.cs @@ -0,0 +1,254 @@ +锘縰sing OpenAI.Builders; +using OpenAI.Interfaces; +using OpenAI.ObjectModels; +using OpenAI.ObjectModels.RequestModels; +using OpenAI.ObjectModels.SharedModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace OpenAI.Playground.TestHelpers +{ + internal static class AssistantTestHelper + { + public static async Task RunAssistantCreateTest(IOpenAIService sdk) + { + ConsoleExtensions.WriteLine("Assistant create Testing is starting:", ConsoleColor.Cyan); + + var func = 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.")) + .Validate() + .Build(); + + try + { + ConsoleExtensions.WriteLine("Assistant Create Test:", ConsoleColor.DarkCyan); + var assistantResult = await sdk.Beta.Assistants.AssistantCreate(new AssistantCreateRequest + { + Instructions = "You are a personal math tutor. When asked a question, write and run Python code to answer the question.", + Name = "Math Tutor", + Tools = new List() { ToolDefinition.DefineCodeInterpreter(), ToolDefinition.DefineRetrieval(), ToolDefinition.DefineFunction(func) }, + Model = Models.Gpt_3_5_Turbo_1106 + }); + + if (assistantResult.Successful) + { + var assistant = assistantResult; + ConsoleExtensions.WriteLine(assistant.ToJson()); + } + else + { + if (assistantResult.Error == null) + { + throw new Exception("Unknown Error"); + } + + ConsoleExtensions.WriteLine($"{assistantResult.Error.Code}: {assistantResult.Error.Message}"); + } + } + catch (Exception e) + { + Console.WriteLine(e); + throw; + } + } + + /// + /// How Assistants work + /// see how-it-works + /// + /// + /// + public static async Task RunHowAssistantsWorkTest(IOpenAIService sdk) + { + ConsoleExtensions.WriteLine("Assistant work Testing is starting:", ConsoleColor.Cyan); + + #region//upload file + const string fileName = "betterway_corp.csv"; + var sampleFile = await FileExtensions.ReadAllBytesAsync($"SampleData/{fileName}"); + var sampleFileAsString = Encoding.UTF8.GetString(sampleFile); + + ConsoleExtensions.WriteLine($"Uploading file: {fileName}", ConsoleColor.DarkCyan); + var uploadFilesResponse = await sdk.Files.FileUpload(UploadFilePurposes.UploadFilePurpose.Assistants, sampleFile, fileName); + if (uploadFilesResponse.Successful) + { + ConsoleExtensions.WriteLine($"{fileName} uploaded", ConsoleColor.DarkGreen); + } + else + { + ConsoleExtensions.WriteLine($"{fileName} failed", ConsoleColor.DarkRed); + return; + } + var uplaodFileId = uploadFilesResponse.Id; + ConsoleExtensions.WriteLine($"uplaodFileId:{uplaodFileId}, purpose:{uploadFilesResponse.Purpose}"); + #endregion + + #region//create assistants + + var func = new FunctionDefinitionBuilder("get_corp_location", "鑾峰彇鍏徃浣嶇疆") + .AddParameter("name", PropertyDefinition.DefineString("鍏徃鍚嶇О锛屼緥濡傦細浣崇▼渚涘簲閾")) + .Validate() + .Build(); + + ConsoleExtensions.WriteLine("Assistant Create Test:", ConsoleColor.DarkCyan); + var assistantResult = await sdk.Beta.Assistants.AssistantCreate(new AssistantCreateRequest + { + Name = "浼佹煡鏌", + Instructions = "浣犳槸涓涓笓涓氭彁渚涘叕鍙镐俊鎭殑鍔╂墜銆傚叕鍙哥浉鍏虫暟鎹潵鑷笂浼犵殑闂锛屼笉鎻愪緵妯$硦涓嶆竻鐨勫洖绛旓紝鍙彁渚涙槑纭殑绛旀", + Model = Models.Gpt_3_5_Turbo_1106, + Tools = new List() { ToolDefinition.DefineCodeInterpreter(), ToolDefinition.DefineRetrieval(), ToolDefinition.DefineFunction(func) }, + FileIds = new List() { uplaodFileId }, + }); + + if (assistantResult.Successful) + { + ConsoleExtensions.WriteLine(assistantResult.ToJson()); + } + else + { + ConsoleExtensions.WriteLine($"{assistantResult.Error?.Code}: {assistantResult.Error?.Message}"); + return; + } + var assistantId = assistantResult.Id; + ConsoleExtensions.WriteLine($"assistantId:{assistantId} "); + #endregion + + #region //create thread + ConsoleExtensions.WriteLine("Thread Create Test:", ConsoleColor.DarkCyan); + var threadResult = await sdk.Beta.Threads.ThreadCreate(); + if (threadResult.Successful) + { + ConsoleExtensions.WriteLine(threadResult.ToJson()); + } + else + { + ConsoleExtensions.WriteLine($"{threadResult.Error?.Code}: {threadResult.Error?.Message}"); + return; + } + var threadId = threadResult.Id; + ConsoleExtensions.WriteLine($"threadId: {threadId}"); + #endregion + + #region//create thread message + ConsoleExtensions.WriteLine("Message Create Test:", ConsoleColor.DarkCyan); + var messageResult = await sdk.Beta.Messages.MessageCreate(threadId, new MessageCreateRequest + { + Role = StaticValues.AssistatntsStatics.MessageStatics.Roles.User, + Content = "娴欐睙浣崇▼渚涘簲閾炬湁闄愬叕鍙稿叿浣撳湪鍝", + FileIds = new List() { uplaodFileId }, + }); + + if (messageResult.Successful) + { + ConsoleExtensions.WriteLine(messageResult.ToJson()); + } + else + { + ConsoleExtensions.WriteLine($"{messageResult.Error?.Code}: {messageResult.Error?.Message}"); + return; + } + var messageId = messageResult.Id; + #endregion + + #region//create run + ConsoleExtensions.WriteLine("Run Create Test:", ConsoleColor.DarkCyan); + var runResult = await sdk.Beta.Runs.RunCreate(threadId, new RunCreateRequest() + { + AssistantId = assistantId, + }); + if (runResult.Successful) + { + ConsoleExtensions.WriteLine(runResult.ToJson()); + } + else + { + ConsoleExtensions.WriteLine($"{runResult.Error?.Code}: {runResult.Error?.Message}"); + return; + } + + var runId = runResult.Id; + ConsoleExtensions.WriteLine($"runId: {runId}"); + #endregion + + #region//waiting for run completed + ConsoleExtensions.WriteLine("waiting for run completed:", ConsoleColor.DarkCyan); + var doneStatusList = new List() { StaticValues.AssistatntsStatics.RunStatus.Cancelled, StaticValues.AssistatntsStatics.RunStatus.Completed, StaticValues.AssistatntsStatics.RunStatus.Failed, StaticValues.AssistatntsStatics.RunStatus.Expired }; + + //鑾峰彇浠诲姟淇℃伅 + var runRetrieveResult = await sdk.Beta.Runs.RunRetrieve(threadId, runId); + var runStatus = runRetrieveResult.Status; + + while (!doneStatusList.Contains(runStatus)) + { + /* + * 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. + * All outputs must be submitted in a single request. + */ + var requireAction = runRetrieveResult.RequiredAction; + if (runStatus == StaticValues.AssistatntsStatics.RunStatus.RequiresAction + && requireAction != null && requireAction.Type == StaticValues.AssistatntsStatics.RequiredActionTypes.SubmitToolOutputs) + { + var myFunc = new List() { "get_corp_location" }; + var toolOutputs = new List(); + foreach (var toolCall in requireAction.SubmitToolOutputs.ToolCalls) + { + ConsoleExtensions.WriteLine($"ToolCall:{toolCall?.ToJson()}"); + if (toolCall?.FunctionCall == null) continue; + + var funcName = toolCall.FunctionCall.Name; + if (myFunc.Contains(funcName)) + { + //do sumbit tool + var toolOutput = new ToolOutput() + { + ToolCallId = toolCall.Id, + Output = "娴欐睙浣崇▼渚涘簲閾炬湁闄愬叕鍙,浣嶄簬娴欐睙鐪侀噾鍗庡競濠哄煄鍖哄叓涓鍖楄615鍙蜂匠绋嬪浗闄呭晢鍔′腑蹇僛from ToolOutput]", + }; + toolOutputs.Add(toolOutput); + } + } + + //All outputs must be submitted in a single request. + if (toolOutputs.Any()) + { + await sdk.Beta.Runs.RunSubmitToolOutputs(threadId, runId, new SubmitToolOutputsToRunRequest() + { + ToolOutputs = toolOutputs, + }); + } + + await Task.Delay(500); + } + + runRetrieveResult = await sdk.Beta.Runs.RunRetrieve(threadId, runId); + runStatus = runRetrieveResult.Status; + if (doneStatusList.Contains(runStatus)) { break; } + + } + + #endregion + + + //鑾峰彇鏈缁堟秷鎭粨鏋 + ConsoleExtensions.WriteLine("Message list:", ConsoleColor.DarkCyan); + var messageListResult = await sdk.Beta.Messages.MessageList(threadId); + if (messageListResult.Successful) + { + ConsoleExtensions.WriteLine(messageListResult.ToJson()); + } + else + { + ConsoleExtensions.WriteLine($"{messageListResult.Error?.Code}: {messageListResult.Error?.Message}"); + return; + } + + } + + + } +} diff --git a/OpenAI.Playground/TestHelpers/MessageTestHelper.cs b/OpenAI.Playground/TestHelpers/MessageTestHelper.cs new file mode 100644 index 00000000..d4491adb --- /dev/null +++ b/OpenAI.Playground/TestHelpers/MessageTestHelper.cs @@ -0,0 +1,67 @@ +锘縰sing OpenAI.Interfaces; +using OpenAI.ObjectModels; +using OpenAI.ObjectModels.RequestModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OpenAI.Playground.TestHelpers +{ + internal static class MessageTestHelper + { + public static async Task RunMessageCreateTest(IOpenAIService sdk) + { + ConsoleExtensions.WriteLine("Message create Testing is starting:", ConsoleColor.Cyan); + + try + { + ConsoleExtensions.WriteLine("Message Create Test:", ConsoleColor.DarkCyan); + + var threadResult = await sdk.Beta.Threads.ThreadCreate(); + if (threadResult.Successful) + { + ConsoleExtensions.WriteLine(threadResult.ToJson()); + } + else + { + if (threadResult.Error == null) + { + throw new Exception("Unknown Error"); + } + ConsoleExtensions.WriteLine($"{threadResult.Error.Code}: {threadResult.Error.Message}"); + } + var threadId = threadResult.Id; + ConsoleExtensions.WriteLine($"threadId :{threadId}"); + + //var threadId = "thread_eG76zeIGn8XoMN8yYOR1VxfG"; + + var messageResult = await sdk.Beta.Messages.MessageCreate(threadId, new MessageCreateRequest + { + Role = StaticValues.AssistatntsStatics.MessageStatics.Roles.User, + Content = "How does AI work? Explain it in simple terms.", + }); + + if (messageResult.Successful) + { + ConsoleExtensions.WriteLine(messageResult.ToJson()); + } + else + { + if (messageResult.Error == null) + { + throw new Exception("Unknown Error"); + } + + ConsoleExtensions.WriteLine($"{messageResult.Error.Code}: {messageResult.Error.Message}"); + } + } + catch (Exception e) + { + Console.WriteLine(e); + throw; + } + } + } +} diff --git a/OpenAI.Playground/TestHelpers/RunTestHelper.cs b/OpenAI.Playground/TestHelpers/RunTestHelper.cs new file mode 100644 index 00000000..a131b7b6 --- /dev/null +++ b/OpenAI.Playground/TestHelpers/RunTestHelper.cs @@ -0,0 +1,113 @@ +锘縰sing OpenAI.Builders; +using OpenAI.Interfaces; +using OpenAI.ObjectModels; +using OpenAI.ObjectModels.RequestModels; +using OpenAI.ObjectModels.SharedModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http.Headers; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace OpenAI.Playground.TestHelpers +{ + internal static class RunTestHelper + { + public static async Task RunRunCreateTest(IOpenAIService sdk) + { + ConsoleExtensions.WriteLine("Run create Testing is starting:", ConsoleColor.Cyan); + + try + { + var threadId = "thread_eG76zeIGn8XoMN8yYOR1VxfG"; + var assistantId = $"asst_wnD0KzUtotn40AtnvLMufh9j"; + ConsoleExtensions.WriteLine("Run Create Test:", ConsoleColor.DarkCyan); + var runResult = await sdk.Beta.Runs.RunCreate(threadId, new RunCreateRequest() + { + AssistantId = assistantId, + }); + if (runResult.Successful) + { + ConsoleExtensions.WriteLine(runResult.ToJson()); + } + else + { + if (runResult.Error == null) + { + throw new Exception("Unknown Error"); + } + + ConsoleExtensions.WriteLine($"{runResult.Error.Code}: {runResult.Error.Message}"); + } + + var runId = runResult.Id; + ConsoleExtensions.WriteLine($"runId: {runId}"); + + var doneStatusList = new List() { StaticValues.AssistatntsStatics.RunStatus.Cancelled, StaticValues.AssistatntsStatics.RunStatus.Completed, StaticValues.AssistatntsStatics.RunStatus.Failed, StaticValues.AssistatntsStatics.RunStatus.Expired }; + var runStatus = StaticValues.AssistatntsStatics.RunStatus.Queued; + do + { + var runRetrieveResult = await sdk.Beta.Runs.RunRetrieve(threadId, runId); + runStatus = runRetrieveResult.Status; + if (doneStatusList.Contains(runStatus)) { break; } + + /* + * 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. + * All outputs must be submitted in a single request. + */ + var requireAction = runRetrieveResult.RequiredAction; + if (runStatus == StaticValues.AssistatntsStatics.RunStatus.RequiresAction && requireAction.Type == StaticValues.AssistatntsStatics.RequiredActionTypes.SubmitToolOutputs) + { + var toolCalls = requireAction.SubmitToolOutputs.ToolCalls; + foreach (var toolCall in toolCalls) + { + ConsoleExtensions.WriteLine($"ToolCall:{toolCall?.ToJson()}"); + if (toolCall.FunctionCall == null) return; + + var funcName = toolCall.FunctionCall.Name; + if (funcName == "get_current_weather") + { + //do sumbit tool + } + } + } + await Task.Delay(1000); + } while (!doneStatusList.Contains(runStatus)); + } + catch (Exception e) + { + Console.WriteLine(e); + throw; + } + } + + + public static async Task RunRunCancelTest(IOpenAIService sdk) + { + ConsoleExtensions.WriteLine("Run cancel Testing is starting:", ConsoleColor.Cyan); + + var threadId = "thread_H43Cyjd8LY8dQNA5N2zbepc0"; + var lastRunId = $"run_0qyHIm4sd9Ugczv0zi5c9BLU"; + ConsoleExtensions.WriteLine("Run Cancel Test:", ConsoleColor.DarkCyan); + var runResult = await sdk.Beta.Runs.RunCancel(threadId, lastRunId); + if (runResult.Successful) + { + ConsoleExtensions.WriteLine(runResult.ToJson()); + } + else + { + if (runResult.Error == null) + { + throw new Exception("Unknown Error"); + } + + ConsoleExtensions.WriteLine($"{runResult.Error.Code}: {runResult.Error.Message}"); + } + + + } + } +} diff --git a/OpenAI.Playground/TestHelpers/ThreadTestHelper.cs b/OpenAI.Playground/TestHelpers/ThreadTestHelper.cs new file mode 100644 index 00000000..2fde9e9a --- /dev/null +++ b/OpenAI.Playground/TestHelpers/ThreadTestHelper.cs @@ -0,0 +1,78 @@ +锘縰sing OpenAI.Builders; +using OpenAI.Interfaces; +using OpenAI.ObjectModels; +using OpenAI.ObjectModels.RequestModels; +using OpenAI.ObjectModels.SharedModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OpenAI.Playground.TestHelpers +{ + internal static class ThreadTestHelper + { + public static async Task RunThreadCreateTest(IOpenAIService sdk) + { + ConsoleExtensions.WriteLine("Thread create Testing is starting:", ConsoleColor.Cyan); + + try + { + ConsoleExtensions.WriteLine("Thread Create Test:", ConsoleColor.DarkCyan); + var threadResult = await sdk.Beta.Threads.ThreadCreate(); + + if (threadResult.Successful) + { + ConsoleExtensions.WriteLine(threadResult.ToJson()); + } + else + { + if (threadResult.Error == null) + { + throw new Exception("Unknown Error"); + } + + ConsoleExtensions.WriteLine($"{threadResult.Error.Code}: {threadResult.Error.Message}"); + } + } + catch (Exception e) + { + Console.WriteLine(e); + throw; + } + } + + public static async Task RunThreadRetrieveTest(IOpenAIService sdk) + { + ConsoleExtensions.WriteLine("Thread retrieve Testing is starting:", ConsoleColor.Cyan); + + try + { + ConsoleExtensions.WriteLine("Thread Retrieve Test:", ConsoleColor.DarkCyan); + + var threadId = "thread_eG76zeIGn8XoMN8yYOR1VxfG"; + var threadResult = await sdk.Beta.Threads.ThreadRetrieve(threadId); + + if (threadResult.Successful) + { + ConsoleExtensions.WriteLine(threadResult.ToJson()); + } + else + { + if (threadResult.Error == null) + { + throw new Exception("Unknown Error"); + } + + ConsoleExtensions.WriteLine($"{threadResult.Error.Code}: {threadResult.Error.Message}"); + } + } + catch (Exception e) + { + Console.WriteLine(e); + throw; + } + } + } +} diff --git a/OpenAI.SDK/EndpointProviders/AzureOpenAiEndpointProvider.cs b/OpenAI.SDK/EndpointProviders/AzureOpenAiEndpointProvider.cs index be65977d..8efb7296 100644 --- a/OpenAI.SDK/EndpointProviders/AzureOpenAiEndpointProvider.cs +++ b/OpenAI.SDK/EndpointProviders/AzureOpenAiEndpointProvider.cs @@ -1,4 +1,5 @@ using System.Net; +using System.Threading; using OpenAI.ObjectModels.RequestModels; namespace OpenAI.EndpointProviders; @@ -192,4 +193,186 @@ private string Files() { return $"{Prefix}/files{QueryString}"; } + + public string AssistantCreate() + { + return $"{Prefix}/assistants{QueryString}"; + } + + public string AssistantRetrieve(string assistantId) + { + return $"{Prefix}/assistants/{assistantId}{QueryString}"; + } + + public string AssistantModify(string assistantId) + { + return $"{Prefix}/assistants/{assistantId}{QueryString}"; + } + + public string AssistantDelete(string assistantId) + { + return $"{Prefix}/assistants/{assistantId}{QueryString}"; + } + + public string AssistantList(AssistantListRequest? assistantListRequest) + { + var url = $"{Prefix}/assistants{QueryString}"; + + var query = assistantListRequest?.GetQueryParameters(); + if (!string.IsNullOrWhiteSpace(query)) + { + url = $"{url}{query}"; + } + return url; + } + + public string AssistantFileCreate(string assistantId) + { + return $"{Prefix}/assistants/{assistantId}/files{QueryString}"; + } + + public string AssistantFileRetrieve(string assistantId, string fileId) + { + return $"{Prefix}/assistants/{assistantId}/files/{fileId}{QueryString}"; + } + + public string AssistantFileDelete(string assistantId, string fileId) + { + return $"{Prefix}/assistants/{assistantId}/files/{fileId}{QueryString}"; + } + + public string AssistantFileList(string assistantId, AssistantFileListRequest? assistantFileListRequest) + { + var url = $"{Prefix}/assistants/files{QueryString}"; + + var query = assistantFileListRequest?.GetQueryParameters(); + if (!string.IsNullOrWhiteSpace(query)) + { + url = $"{url}{query}"; + } + return url; + } + + public string ThreadCreate() + { + return $"{Prefix}/threads{QueryString}"; + } + + public string ThreadRetrieve(string threadId) + { + return $"{Prefix}/threads/{threadId}{QueryString}"; + } + + public string ThreadModify(string threadId) + { + return $"{Prefix}/threads/{threadId}{QueryString}"; + } + + public string ThreadDelete(string threadId) + { + return $"{Prefix}/threads/{threadId}{QueryString}"; + } + + public string MessageCreate(string threadId) + { + return $"{Prefix}/threads/{threadId}/messages{QueryString}"; + } + + public string MessageRetrieve(string threadId, string messageId) + { + return $"{Prefix}/threads/{threadId}/messages/{messageId}{QueryString}"; + } + + public string MessageModify(string threadId, string messageId) + { + return $"{Prefix}/threads/{threadId}/messages/{messageId}{QueryString}"; + } + + public string MessageList(string threadId, MessageListRequest? messageListRequest) + { + var url = $"{Prefix}/threads/{threadId}/messages{QueryString}"; + + var query = messageListRequest?.GetQueryParameters(); + if (!string.IsNullOrWhiteSpace(query)) + { + url = $"{url}{query}"; + } + return url; + } + + public string MessageFileRetrieve(string threadId, string messageId, string fileId) + { + return $"{Prefix}/threads/{threadId}/messages/{messageId}/files/{fileId}{QueryString}"; + } + + public string MessageFileList(string threadId, string messageId, MessageFileListRequest? messageFileListRequest) + { + var url = $"{Prefix}/threads/{threadId}/messages/{messageId}/files{QueryString}"; + + var query = messageFileListRequest?.GetQueryParameters(); + if (!string.IsNullOrWhiteSpace(query)) + { + url = $"{url}{query}"; + } + return url; + } + + public string RunCreate(string threadId) + { + return $"{Prefix}/threads/{threadId}/runs{QueryString}"; + } + + public string RunRetrieve(string threadId, string runId) + { + return $"{Prefix}/threads/{threadId}/runs/{runId}{QueryString}"; + } + + public string RunModify(string threadId, string runId) + { + return $"{Prefix}/threads/{threadId}/runs/{runId}{QueryString}"; + } + + public string RunList(string threadId, RunListRequest? runListRequest) + { + var url = $"{Prefix}/threads/{threadId}/runs{QueryString}"; + + var query = runListRequest?.GetQueryParameters(); + if (!string.IsNullOrWhiteSpace(query)) + { + url = $"{url}{query}"; + } + return url; + } + + public string RunSubmitToolOutputs(string threadId, string runId) + { + return $"{Prefix}/threads/{threadId}/runs/{runId}/submit_tool_outputs{QueryString}"; + } + + public string RunCancel(string threadId, string runId) + { + return $"{Prefix}/threads/{threadId}/runs/{runId}/cancel{QueryString}"; + } + + public string ThreadAndRunCreate() + { + return $"{Prefix}/threads/runs{QueryString}"; + } + + public string RunStepRetrieve(string threadId, string runId, string stepId) + { + return $"{Prefix}/threads/{threadId}/runs/{runId}/steps/{stepId}{QueryString}"; + } + + public string RunStepList(string threadId, string runId, RunStepListRequest? runStepListRequest) + { + var url = $"{Prefix}/threads/{threadId}/runs/{runId}/steps{QueryString}"; + + var query = runStepListRequest?.GetQueryParameters(); + if (!string.IsNullOrWhiteSpace(query)) + { + url = $"{url}{query}"; + } + return url; + } } \ No newline at end of file diff --git a/OpenAI.SDK/EndpointProviders/IOpenAiEndpointProvider.cs b/OpenAI.SDK/EndpointProviders/IOpenAiEndpointProvider.cs index 8429637e..9b69f952 100644 --- a/OpenAI.SDK/EndpointProviders/IOpenAiEndpointProvider.cs +++ b/OpenAI.SDK/EndpointProviders/IOpenAiEndpointProvider.cs @@ -34,4 +34,33 @@ internal interface IOpenAiEndpointProvider string AudioCreateTranscription(); string AudioCreateTranslation(); string AudioCreateSpeech(); + + string AssistantCreate(); + string AssistantRetrieve(string assistantId); + string AssistantModify(string assistantId); + string AssistantDelete(string assistantId); + string AssistantList(AssistantListRequest? assistantListRequest); + string AssistantFileCreate(string assistantId); + string AssistantFileRetrieve(string assistantId, string fileId); + string AssistantFileDelete(string assistantId, string fileId); + string AssistantFileList(string assistantId, AssistantFileListRequest? assistantFileListRequest); + string ThreadCreate(); + string ThreadRetrieve(string threadId); + string ThreadModify(string threadId); + string ThreadDelete(string threadId); + string MessageCreate(string threadId); + string MessageRetrieve(string threadId,string messageId); + string MessageModify(string threadId, string messageId); + string MessageList(string threadId, MessageListRequest? messageListRequest); + string MessageFileRetrieve(string threadId, string messageId, string fileId); + string MessageFileList(string threadId, string messageId, MessageFileListRequest? messageFileListRequest); + string RunCreate(string threadId); + string RunRetrieve(string threadId, string runId); + string RunModify(string threadId, string runId); + string RunList(string threadId, RunListRequest? runListRequest); + string RunSubmitToolOutputs(string threadId, string runId); + string RunCancel(string threadId, string runId); + string ThreadAndRunCreate(); + string RunStepRetrieve(string threadId, string runId,string stepId); + string RunStepList(string threadId, string runId, RunStepListRequest? runStepListRequest); } \ No newline at end of file diff --git a/OpenAI.SDK/EndpointProviders/OpenAiEndpointProvider.cs b/OpenAI.SDK/EndpointProviders/OpenAiEndpointProvider.cs index 61692008..ad8149ca 100644 --- a/OpenAI.SDK/EndpointProviders/OpenAiEndpointProvider.cs +++ b/OpenAI.SDK/EndpointProviders/OpenAiEndpointProvider.cs @@ -1,4 +1,6 @@ -锘縰sing System.Net; +锘縰sing System; +using System.Net; +using System.Text; using OpenAI.ObjectModels.RequestModels; namespace OpenAI.EndpointProviders; @@ -122,7 +124,7 @@ public string FineTuningJobList(FineTuningJobListRequest? fineTuningJobListReque queryParams.Add($"after={WebUtility.UrlEncode(fineTuningJobListRequest.After)}"); if (fineTuningJobListRequest.Limit.HasValue) queryParams.Add($"limit={fineTuningJobListRequest.Limit.Value}"); - + if (queryParams.Any()) url = $"{url}?{string.Join("&", queryParams)}"; } @@ -178,4 +180,186 @@ private string Files() { return $"{_apiVersion}/files"; } + + public string AssistantCreate() + { + return $"{_apiVersion}/assistants"; + } + + public string AssistantRetrieve(string assistantId) + { + return $"{_apiVersion}/assistants/{assistantId}"; + } + + public string AssistantModify(string assistantId) + { + return $"{_apiVersion}/assistants/{assistantId}"; + } + + public string AssistantDelete(string assistantId) + { + return $"{_apiVersion}/assistants/{assistantId}"; + } + + public string AssistantList(AssistantListRequest? assistantListRequest) + { + var url = $"{_apiVersion}/assistants"; + + var query = assistantListRequest?.GetQueryParameters(); + if (!string.IsNullOrWhiteSpace(query)) + { + url = $"{url}?{query}"; + } + return url; + } + + public string AssistantFileCreate(string assistantId) + { + return $"{_apiVersion}/assistants/{assistantId}/files"; + } + + public string AssistantFileRetrieve(string assistantId, string fileId) + { + return $"{_apiVersion}/assistants/{assistantId}/files/{fileId}"; + } + + public string AssistantFileDelete(string assistantId, string fileId) + { + return $"{_apiVersion}/assistants/{assistantId}/files/{fileId}"; + } + + public string AssistantFileList(string assistantId, AssistantFileListRequest? assistantFileListRequest) + { + var url = $"{_apiVersion}/assistants/{assistantId}/files"; + + var query = assistantFileListRequest?.GetQueryParameters(); + if (!string.IsNullOrWhiteSpace(query)) + { + url = $"{url}?{query}"; + } + return url; + } + + public string ThreadCreate() + { + return $"{_apiVersion}/threads"; + } + + public string ThreadRetrieve(string threadId) + { + return $"{_apiVersion}/threads/{threadId}"; + } + + public string ThreadModify(string threadId) + { + return $"{_apiVersion}/threads/{threadId}"; + } + + public string ThreadDelete(string threadId) + { + return $"{_apiVersion}/threads/{threadId}"; + } + + public string MessageCreate(string threadId) + { + return $"{_apiVersion}/threads/{threadId}/messages"; + } + + public string MessageRetrieve(string threadId, string messageId) + { + return $"{_apiVersion}/threads/{threadId}/messages/{messageId}"; + } + + public string MessageModify(string threadId, string messageId) + { + return $"{_apiVersion}/threads/{threadId}/messages/{messageId}"; + } + + public string MessageList(string threadId, MessageListRequest? messageListRequest) + { + var url = $"{_apiVersion}/threads/{threadId}/messages"; + + var query = messageListRequest?.GetQueryParameters(); + if (!string.IsNullOrWhiteSpace(query)) + { + url = $"{url}?{query}"; + } + return url; + } + + public string MessageFileRetrieve(string threadId, string messageId, string fileId) + { + return $"{_apiVersion}/threads/{threadId}/messages/{messageId}/files/{fileId}"; + } + + public string MessageFileList(string threadId, string messageId, MessageFileListRequest? messageFileListRequest) + { + var url = $"{_apiVersion}/threads/{threadId}/messages/{messageId}/files"; + + var query = messageFileListRequest?.GetQueryParameters(); + if (!string.IsNullOrWhiteSpace(query)) + { + url = $"{url}?{query}"; + } + return url; + } + + public string RunCreate(string threadId) + { + return $"{_apiVersion}/threads/{threadId}/runs"; + } + + public string RunRetrieve(string threadId, string runId) + { + return $"{_apiVersion}/threads/{threadId}/runs/{runId}"; + } + + public string RunModify(string threadId, string runId) + { + return $"{_apiVersion}/threads/{threadId}/runs/{runId}"; + } + + public string RunList(string threadId, RunListRequest? runListRequest) + { + var url= $"{_apiVersion}/threads/{threadId}/runs"; + + var query = runListRequest?.GetQueryParameters(); + if (!string.IsNullOrWhiteSpace(query)) + { + url = $"{url}?{query}"; + } + return url; + } + + public string RunSubmitToolOutputs(string threadId, string runId) + { + return $"{_apiVersion}/threads/{threadId}/runs/{runId}/submit_tool_outputs"; + } + + public string RunCancel(string threadId, string runId) + { + return $"{_apiVersion}/threads/{threadId}/runs/{runId}/cancel"; + } + + public string ThreadAndRunCreate() + { + return $"{_apiVersion}/threads/runs"; + } + + public string RunStepRetrieve(string threadId, string runId, string stepId) + { + return $"{_apiVersion}/threads/{threadId}/runs/{runId}/steps/{stepId}"; + } + + public string RunStepList(string threadId, string runId, RunStepListRequest? runStepListRequest) + { + var url= $"{_apiVersion}/threads/{threadId}/runs/{runId}/steps"; + + var query = runStepListRequest?.GetQueryParameters(); + if (!string.IsNullOrWhiteSpace(query)) + { + url = $"{url}?{query}"; + } + return url; + } } \ No newline at end of file diff --git a/OpenAI.SDK/Extensions/HttpclientExtensions.cs b/OpenAI.SDK/Extensions/HttpclientExtensions.cs index 9fbe37ff..6bcc4490 100644 --- a/OpenAI.SDK/Extensions/HttpclientExtensions.cs +++ b/OpenAI.SDK/Extensions/HttpclientExtensions.cs @@ -8,6 +8,12 @@ namespace OpenAI.Extensions; internal static class HttpClientExtensions { + public static async Task GetReadAsAsync(this HttpClient client, string uri, CancellationToken cancellationToken = default) where TResponse : BaseResponse, new() + { + var response = await client.GetAsync(uri, cancellationToken); + return await HandleResponseContent(response, cancellationToken); + } + public static async Task PostAndReadAsAsync(this HttpClient client, string uri, object? requestModel, CancellationToken cancellationToken = default) where TResponse : BaseResponse, new() { var response = await client.PostAsJsonAsync(uri, requestModel, new JsonSerializerOptions diff --git a/OpenAI.SDK/Interfaces/IAssistantService.cs b/OpenAI.SDK/Interfaces/IAssistantService.cs new file mode 100644 index 00000000..2af28d5b --- /dev/null +++ b/OpenAI.SDK/Interfaces/IAssistantService.cs @@ -0,0 +1,92 @@ +锘縰sing OpenAI.ObjectModels.RequestModels; +using OpenAI.ObjectModels.ResponseModels; +using OpenAI.ObjectModels.SharedModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OpenAI.Interfaces +{ + public interface IAssistantService + { + /// + /// Create an assistant with a model and instructions. + /// + /// + /// + /// + /// + Task AssistantCreate(AssistantCreateRequest request, string? modelId = null, CancellationToken cancellationToken = default); + + /// + /// Create an assistant file by attaching a File to an assistant. + /// + /// + /// + /// + /// + Task AssistantFileCreate(string assistantId, AssistantFileCreateRequest request, CancellationToken cancellationToken = default); + + /// + /// Returns a list of assistants. + /// + /// + /// + /// + Task AssistantList(AssistantListRequest? request = null, CancellationToken cancellationToken = default); + + /// + /// Returns a list of assistant files. + /// + /// + /// + /// + /// + Task AssistantFileList(string assistantId, AssistantFileListRequest? request = null, CancellationToken cancellationToken = default); + + /// + /// Retrieves an assistant. + /// + /// + /// + /// + Task AssistantRetrieve(string assistantId, CancellationToken cancellationToken = default); + + /// + /// Retrieves an AssistantFile. + /// + /// + /// + /// + /// + Task AssistantFileRetrieve(string assistantId, string fileId, CancellationToken cancellationToken = default); + + /// + /// Modifies an assistant. + /// + /// + /// + /// + /// + Task AssistantModify(string assistantId, AssistantModifyRequest request, CancellationToken cancellationToken = default); + + /// + /// Delete an assistant. + /// + /// + /// + /// + Task AssistantDelete(string assistantId, CancellationToken cancellationToken = default); + + /// + /// Delete an assistant file. + /// + /// + /// + /// + /// + Task AssistantFileDelete(string assistantId, string fileId, CancellationToken cancellationToken = default); + } +} diff --git a/OpenAI.SDK/Interfaces/IBetaService.cs b/OpenAI.SDK/Interfaces/IBetaService.cs new file mode 100644 index 00000000..b8252fb9 --- /dev/null +++ b/OpenAI.SDK/Interfaces/IBetaService.cs @@ -0,0 +1,19 @@ +锘縰sing System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OpenAI.Interfaces +{ + public interface IBetaService + { + public IAssistantService Assistants { get; } + + public IMessageService Messages { get; } + + public IThreadService Threads { get; } + + public IRunService Runs { get; } + } +} diff --git a/OpenAI.SDK/Interfaces/IMessageService.cs b/OpenAI.SDK/Interfaces/IMessageService.cs new file mode 100644 index 00000000..5c40761f --- /dev/null +++ b/OpenAI.SDK/Interfaces/IMessageService.cs @@ -0,0 +1,33 @@ +锘縰sing OpenAI.ObjectModels.RequestModels; +using OpenAI.ObjectModels.ResponseModels; +using OpenAI.ObjectModels.SharedModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OpenAI.Interfaces +{ + public interface IMessageService + { + /// + /// Create a message. + /// + /// + /// + /// + /// + /// + Task MessageCreate(string threadId, MessageCreateRequest request, string? modelId = null, CancellationToken cancellationToken = default); + + /// + /// Returns a list of messages for a given thread. + /// + /// + /// + /// + /// + Task MessageList(string threadId, MessageListRequest? request = null, CancellationToken cancellationToken = default); + } +} diff --git a/OpenAI.SDK/Interfaces/IOpenAIService.cs b/OpenAI.SDK/Interfaces/IOpenAIService.cs index 671865d4..4987c116 100644 --- a/OpenAI.SDK/Interfaces/IOpenAIService.cs +++ b/OpenAI.SDK/Interfaces/IOpenAIService.cs @@ -55,6 +55,10 @@ public interface IOpenAIService /// public IAudioService Audio { get; } + /// + /// Beta + /// + public IBetaService Beta { get; } /// /// Set default model diff --git a/OpenAI.SDK/Interfaces/IRunService.cs b/OpenAI.SDK/Interfaces/IRunService.cs new file mode 100644 index 00000000..8ec525f9 --- /dev/null +++ b/OpenAI.SDK/Interfaces/IRunService.cs @@ -0,0 +1,54 @@ +锘縰sing OpenAI.ObjectModels.RequestModels; +using OpenAI.ObjectModels.SharedModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OpenAI.Interfaces +{ + public interface IRunService + { + /// + /// Create a run. + /// + /// + /// + /// + /// + /// + Task RunCreate(string threadId, RunCreateRequest request, string? modelId = null, CancellationToken cancellationToken = default); + + /// + /// Retrieves a run. + /// + /// + /// + /// + /// + Task RunRetrieve(string threadId, string runId, CancellationToken cancellationToken = default); + + /// + /// Cancels a run that is in_progress. + /// + /// + /// + /// + /// + Task RunCancel(string threadId, string runId, CancellationToken cancellationToken = default); + + /// + /// 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. + /// All outputs must be submitted in a single request. + /// + /// + /// + /// + /// + /// + Task RunSubmitToolOutputs(string threadId, string runId, SubmitToolOutputsToRunRequest request, CancellationToken cancellationToken = default); + } +} diff --git a/OpenAI.SDK/Interfaces/IThreadService.cs b/OpenAI.SDK/Interfaces/IThreadService.cs new file mode 100644 index 00000000..5d40c018 --- /dev/null +++ b/OpenAI.SDK/Interfaces/IThreadService.cs @@ -0,0 +1,38 @@ +锘縰sing OpenAI.ObjectModels.RequestModels; +using OpenAI.ObjectModels.SharedModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OpenAI.Interfaces +{ + public interface IThreadService + { + /// + /// Create a thread. + /// + /// + /// + /// + /// + Task ThreadCreate(ThreadCreateRequest? request = null, string? modelId = null, CancellationToken cancellationToken = default); + + /// + /// Retrieves a thread. + /// + /// + /// + /// + Task ThreadRetrieve(string threadId, CancellationToken cancellationToken = default); + + /// + /// Delete a thread. + /// + /// + /// + /// + Task ThreadDelete(string threadId, CancellationToken cancellationToken = default); + } +} diff --git a/OpenAI.SDK/Managers/OpenAIAssistantService.cs b/OpenAI.SDK/Managers/OpenAIAssistantService.cs new file mode 100644 index 00000000..d8d90def --- /dev/null +++ b/OpenAI.SDK/Managers/OpenAIAssistantService.cs @@ -0,0 +1,95 @@ +锘縰sing OpenAI.Extensions; +using OpenAI.Interfaces; +using OpenAI.ObjectModels.RequestModels; +using OpenAI.ObjectModels.ResponseModels; +using OpenAI.ObjectModels.SharedModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace OpenAI.Managers +{ + public partial class OpenAIService : IAssistantService + { + /// + public async Task AssistantCreate(AssistantCreateRequest request, string? modelId = null, CancellationToken cancellationToken = default) + { + request.ProcessModelId(modelId, _defaultModelId); + return await _httpClient.PostAndReadAsAsync(_endpointProvider.AssistantCreate(), request, cancellationToken); + } + + /// + public async Task AssistantFileCreate(string assistantId, AssistantFileCreateRequest request, CancellationToken cancellationToken = default) + { + return await _httpClient.PostAndReadAsAsync(_endpointProvider.AssistantFileCreate(assistantId), request, cancellationToken); + } + + /// + public async Task AssistantList(AssistantListRequest? request = null, CancellationToken cancellationToken = default) + { + return await _httpClient.GetReadAsAsync(_endpointProvider.AssistantList(request), cancellationToken); + } + + /// + public async Task AssistantFileList(string assistantId, AssistantFileListRequest? request = null, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(assistantId)) { throw new ArgumentNullException(nameof(assistantId)); } + + return await _httpClient.GetReadAsAsync(_endpointProvider.AssistantFileList(assistantId, request), cancellationToken); + } + + /// + public async Task AssistantRetrieve(string assistantId, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(assistantId)) { throw new ArgumentNullException(nameof(assistantId)); } + + return await _httpClient.GetReadAsAsync(_endpointProvider.AssistantRetrieve(assistantId), cancellationToken); + } + + /// + public async Task AssistantFileRetrieve(string assistantId, string fileId, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(assistantId)) { throw new ArgumentNullException(nameof(assistantId)); } + if (string.IsNullOrWhiteSpace(fileId)) { throw new ArgumentNullException(nameof(fileId)); } + + return await _httpClient.GetReadAsAsync(_endpointProvider.AssistantFileRetrieve(assistantId, fileId), cancellationToken); + } + + /// + public async Task AssistantModify(string assistantId, AssistantModifyRequest request, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(assistantId)) { throw new ArgumentNullException(nameof(assistantId)); } + + return await _httpClient.PostAndReadAsAsync(_endpointProvider.AssistantModify(assistantId), request, cancellationToken); + } + + /// + public async Task AssistantDelete(string assistantId, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(assistantId)) { throw new ArgumentNullException(nameof(assistantId)); } + + return await _httpClient.GetReadAsAsync(_endpointProvider.AssistantDelete(assistantId), cancellationToken); + } + + /// + public async Task AssistantFileDelete(string assistantId, string fileId, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(assistantId)) { throw new ArgumentNullException(nameof(assistantId)); } + if (string.IsNullOrWhiteSpace(fileId)) { throw new ArgumentNullException(nameof(fileId)); } + + return await _httpClient.GetReadAsAsync(_endpointProvider.AssistantFileDelete(assistantId, fileId), cancellationToken); + } + + + + + + + + + + } +} diff --git a/OpenAI.SDK/Managers/OpenAIBetaService.cs b/OpenAI.SDK/Managers/OpenAIBetaService.cs new file mode 100644 index 00000000..711639f0 --- /dev/null +++ b/OpenAI.SDK/Managers/OpenAIBetaService.cs @@ -0,0 +1,23 @@ +锘縰sing OpenAI.Interfaces; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OpenAI.Managers +{ + /// + /// 鎻愪緵beta鐗堟湰鐨勫姛鑳 + /// + public partial class OpenAIService : IBetaService + { + public IAssistantService Assistants => this; + + public IMessageService Messages => this; + + public IThreadService Threads => this; + + public IRunService Runs => this; + } +} diff --git a/OpenAI.SDK/Managers/OpenAIMessageService.cs b/OpenAI.SDK/Managers/OpenAIMessageService.cs new file mode 100644 index 00000000..eab42ea5 --- /dev/null +++ b/OpenAI.SDK/Managers/OpenAIMessageService.cs @@ -0,0 +1,48 @@ +锘縰sing OpenAI.Extensions; +using OpenAI.Interfaces; +using OpenAI.ObjectModels.RequestModels; +using OpenAI.ObjectModels.ResponseModels; +using OpenAI.ObjectModels.SharedModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Text; +using System.Threading.Tasks; + +namespace OpenAI.Managers +{ + public partial class OpenAIService : IMessageService + { + /// + /// Create a message. + /// + /// + /// + /// + /// + /// + /// + public async Task MessageCreate(string threadId, MessageCreateRequest request, string? modelId = null, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(threadId)) { throw new ArgumentNullException(nameof(threadId)); } + + return await _httpClient.PostAndReadAsAsync(_endpointProvider.MessageCreate(threadId), request, cancellationToken); + } + + /// + /// Returns a list of messages for a given thread. + /// + /// + /// + /// + /// + /// + public async Task MessageList(string threadId, MessageListRequest? request = null, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(threadId)) { throw new ArgumentNullException(nameof(threadId)); } + + return await _httpClient.GetReadAsAsync(_endpointProvider.MessageList(threadId, request), cancellationToken); + } + } +} diff --git a/OpenAI.SDK/Managers/OpenAIRunService.cs b/OpenAI.SDK/Managers/OpenAIRunService.cs new file mode 100644 index 00000000..ddd3730a --- /dev/null +++ b/OpenAI.SDK/Managers/OpenAIRunService.cs @@ -0,0 +1,83 @@ +锘縰sing OpenAI.Extensions; +using OpenAI.Interfaces; +using OpenAI.ObjectModels.RequestModels; +using OpenAI.ObjectModels.SharedModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OpenAI.Managers +{ + public partial class OpenAIService : IRunService + { + /// + /// Create a run. + /// + /// + /// + /// + /// + /// + /// + public async Task RunCreate(string threadId, RunCreateRequest request, string? modelId = null, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(threadId)) { throw new ArgumentNullException(nameof(threadId)); } + + //request.ProcessModelId(modelId, _defaultModelId); + return await _httpClient.PostAndReadAsAsync(_endpointProvider.RunCreate(threadId), request, cancellationToken); + } + + /// + /// Retrieves a run. + /// + /// + /// + /// + /// + /// + public async Task RunRetrieve(string threadId, string runId, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(threadId)) { throw new ArgumentNullException(nameof(threadId)); } + if (string.IsNullOrWhiteSpace(runId)) { throw new ArgumentNullException(nameof(runId)); } + + return await _httpClient.GetReadAsAsync(_endpointProvider.RunRetrieve(threadId, runId), cancellationToken); + } + + /// + /// Cancels a run that is in_progress. + /// + /// + /// + /// + /// + /// + public async Task RunCancel(string threadId, string runId, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(threadId)) { throw new ArgumentNullException(nameof(threadId)); } + + return await _httpClient.PostAndReadAsAsync(_endpointProvider.RunCancel(threadId, runId), null,cancellationToken); + } + + /// + /// 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. + /// All outputs must be submitted in a single request. + /// + /// + /// + /// + /// + /// + /// + public async Task RunSubmitToolOutputs(string threadId, string runId, SubmitToolOutputsToRunRequest request, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(threadId)) { throw new ArgumentNullException(nameof(threadId)); } + if (string.IsNullOrWhiteSpace(runId)) { throw new ArgumentNullException(nameof(runId)); } + + return await _httpClient.PostAndReadAsAsync(_endpointProvider.RunSubmitToolOutputs(threadId, runId), request, cancellationToken); + } + } +} diff --git a/OpenAI.SDK/Managers/OpenAIService.cs b/OpenAI.SDK/Managers/OpenAIService.cs index 7ed568ae..349fc116 100644 --- a/OpenAI.SDK/Managers/OpenAIService.cs +++ b/OpenAI.SDK/Managers/OpenAIService.cs @@ -42,10 +42,11 @@ public OpenAIService(OpenAiOptions settings, HttpClient? httpClient = null) case ProviderType.OpenAi: default: _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {settings.ApiKey}"); + _httpClient.DefaultRequestHeaders.Add("OpenAI-Beta", settings.Assistants); break; } - if (!string.IsNullOrEmpty(settings.Organization)) + if (!string.IsNullOrWhiteSpace(settings.Organization)) { _httpClient.DefaultRequestHeaders.Add("OpenAI-Organization", $"{settings.Organization}"); } @@ -102,6 +103,12 @@ public void Dispose() /// public IAudioService Audio => this; + /// + public IBetaService Beta => this; + + + + /// /// Sets default Model Id /// diff --git a/OpenAI.SDK/Managers/OpenAIThreadService.cs b/OpenAI.SDK/Managers/OpenAIThreadService.cs new file mode 100644 index 00000000..e5400edc --- /dev/null +++ b/OpenAI.SDK/Managers/OpenAIThreadService.cs @@ -0,0 +1,56 @@ +锘縰sing OpenAI.Extensions; +using OpenAI.Interfaces; +using OpenAI.ObjectModels.RequestModels; +using OpenAI.ObjectModels.SharedModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OpenAI.Managers +{ + public partial class OpenAIService : IThreadService + { + /// + /// Create a thread. + /// + /// + /// + /// + /// + /// + public async Task ThreadCreate(ThreadCreateRequest? request = null, string? modelId = null, CancellationToken cancellationToken = default) + { + return await _httpClient.PostAndReadAsAsync(_endpointProvider.ThreadCreate(), request, cancellationToken); + } + + /// + /// Retrieves a thread. + /// + /// + /// + /// + /// + public async Task ThreadRetrieve(string threadId, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(threadId)) { throw new ArgumentNullException(nameof(threadId)); } + + return await _httpClient.GetReadAsAsync(_endpointProvider.ThreadRetrieve(threadId), cancellationToken); + } + + /// + /// Delete a thread. + /// + /// + /// + /// + /// + public async Task ThreadDelete(string threadId, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(threadId)) { throw new ArgumentNullException(nameof(threadId)); } + + return await _httpClient.GetReadAsAsync(_endpointProvider.ThreadRetrieve(threadId), cancellationToken); + } + } +} diff --git a/OpenAI.SDK/ObjectModels/RequestModels/AssistantCreateRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/AssistantCreateRequest.cs new file mode 100644 index 00000000..402cce0d --- /dev/null +++ b/OpenAI.SDK/ObjectModels/RequestModels/AssistantCreateRequest.cs @@ -0,0 +1,57 @@ +锘縰sing OpenAI.ObjectModels.SharedModels; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace OpenAI.ObjectModels.RequestModels +{ + public class AssistantCreateRequest : IOpenAiModels.IModel, IOpenAiModels.IFileIds, IOpenAiModels.IMetaData + { + /// + /// ID of the model to use + /// + [Required] + [JsonPropertyName("model")] + public string Model { get; set; } + + /// + /// The name of the assistant. The maximum length is 256 + /// + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// The description of the assistant. + /// + [JsonPropertyName("description")] + public string Description { get; set; } + + /// + /// The system instructions that the assistant uses. + /// + [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. + /// + [JsonPropertyName("file_ids")] + public List FileIds { get; set; } + + /// + /// Set of 16 key-value pairs that can be attached to an object. + /// + [JsonPropertyName("metadata")] + public Dictionary MetaData { get; set; } + } +} diff --git a/OpenAI.SDK/ObjectModels/RequestModels/AssistantFileCreateRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/AssistantFileCreateRequest.cs new file mode 100644 index 00000000..1946fe4e --- /dev/null +++ b/OpenAI.SDK/ObjectModels/RequestModels/AssistantFileCreateRequest.cs @@ -0,0 +1,20 @@ +锘縰sing System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace OpenAI.ObjectModels.RequestModels +{ + public class AssistantFileCreateRequest + { + /// + /// A File ID (with purpose="assistants") that the assistant should use. Useful for tools like retrieval and code_interpreter that can access files. + /// + [JsonPropertyName("file_id")] + [Required] + public string FileId { get; set; } + } +} diff --git a/OpenAI.SDK/ObjectModels/RequestModels/AssistantFileListRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/AssistantFileListRequest.cs new file mode 100644 index 00000000..a966538c --- /dev/null +++ b/OpenAI.SDK/ObjectModels/RequestModels/AssistantFileListRequest.cs @@ -0,0 +1,12 @@ +锘縰sing System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OpenAI.ObjectModels.RequestModels +{ + public class AssistantFileListRequest :BaseListRequest + { + } +} diff --git a/OpenAI.SDK/ObjectModels/RequestModels/AssistantListRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/AssistantListRequest.cs new file mode 100644 index 00000000..eeee89f4 --- /dev/null +++ b/OpenAI.SDK/ObjectModels/RequestModels/AssistantListRequest.cs @@ -0,0 +1,12 @@ +锘縰sing System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OpenAI.ObjectModels.RequestModels +{ + public class AssistantListRequest : BaseListRequest + { + } +} diff --git a/OpenAI.SDK/ObjectModels/RequestModels/AssistantModifyRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/AssistantModifyRequest.cs new file mode 100644 index 00000000..94e456f3 --- /dev/null +++ b/OpenAI.SDK/ObjectModels/RequestModels/AssistantModifyRequest.cs @@ -0,0 +1,56 @@ +锘縰sing OpenAI.ObjectModels.SharedModels; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace OpenAI.ObjectModels.RequestModels +{ + public class AssistantModifyRequest : IOpenAiModels.IModel, IOpenAiModels.IFileIds, IOpenAiModels.IMetaData + { + /// + /// ID of the model to use + /// + [JsonPropertyName("model")] + public string Model { get; set; } + + /// + /// The name of the assistant. The maximum length is 256 + /// + [JsonPropertyName("name")] + public string? Name { get; set; } + + /// + /// The description of the assistant. The maximum length is 512 characters. + /// + [JsonPropertyName("description")] + public string? Description { get; set; } + + /// + /// The system instructions that the assistant uses. The maximum length is 32768 characters. + /// + [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. + /// + [JsonPropertyName("file_ids")] + public List FileIds { get; set; } + + /// + /// Set of 16 key-value pairs that can be attached to an object. + /// + [JsonPropertyName("metadata")] + public Dictionary MetaData { get; set; } + } +} diff --git a/OpenAI.SDK/ObjectModels/RequestModels/BaseListRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/BaseListRequest.cs new file mode 100644 index 00000000..185e91fe --- /dev/null +++ b/OpenAI.SDK/ObjectModels/RequestModels/BaseListRequest.cs @@ -0,0 +1,68 @@ +锘縰sing System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace OpenAI.ObjectModels.RequestModels +{ + public class BaseListRequest + { + /// + /// A limit on the number of objects to be returned. + /// Limit can range between 1 and 100, and the default is 20. + /// + [JsonPropertyName("limit")] + public int? Limit { get; set; } + + /// + /// Sort order by the created_at timestamp of the objects. + /// "asc" for ascending order and "desc" for descending order. + /// + [JsonPropertyName("order")] + public string? Order { get; set; } + + + /// + /// A cursor for use in pagination. after is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with obj_foo, + /// your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// + [JsonPropertyName("after")] + public string? After { get; set; } + + /// + /// A cursor for use in pagination. before is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with obj_foo, your + /// subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// + [JsonPropertyName("before")] + public string? Before { get; set; } + public string? GetQueryParameters() + { + var build = new List(); + if (Limit != null) + { + build.Add($"limit={Limit}"); + } + if (Order != null) + { + build.Add($"order={WebUtility.UrlEncode(Order)}"); + } + if (After != null) + { + build.Add($"after={WebUtility.UrlEncode(After)}"); + } + if (Before != null) + { + build.Add($"before={WebUtility.UrlEncode(Before)}"); + } + + if (build.Count <= 0) return null; + + return string.Join("&", build); + } + } +} diff --git a/OpenAI.SDK/ObjectModels/RequestModels/MessageCreateRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/MessageCreateRequest.cs new file mode 100644 index 00000000..9a0dc862 --- /dev/null +++ b/OpenAI.SDK/ObjectModels/RequestModels/MessageCreateRequest.cs @@ -0,0 +1,46 @@ +锘縰sing OpenAI.ObjectModels.SharedModels; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace OpenAI.ObjectModels.RequestModels +{ + public class MessageCreateRequest : IOpenAiModels.IFileIds, IOpenAiModels.IMetaData + { + /// + /// The role of the entity that is creating the message. + /// Currently only user is supported. + /// + [Required] + [JsonPropertyName("role")] + public string Role { get; set; } = StaticValues.AssistatntsStatics.MessageStatics.Roles.User; + + /// + /// The content of the message. + /// + [Required] + [JsonPropertyName("content")] + public string Content { get; set; } + + /// + /// A list of File IDs that the message should use. + /// There can be a maximum of 10 files attached to a message. + /// Useful for tools like retrieval and code_interpreter that can access and use files. + /// + [JsonPropertyName("file_ids")] + public List FileIds { 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. + /// + [JsonPropertyName("metadata")] + public Dictionary MetaData { get; set; } + + } +} diff --git a/OpenAI.SDK/ObjectModels/RequestModels/MessageFileListRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/MessageFileListRequest.cs new file mode 100644 index 00000000..920b8de8 --- /dev/null +++ b/OpenAI.SDK/ObjectModels/RequestModels/MessageFileListRequest.cs @@ -0,0 +1,12 @@ +锘縰sing System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OpenAI.ObjectModels.RequestModels +{ + public class MessageFileListRequest : BaseListRequest + { + } +} diff --git a/OpenAI.SDK/ObjectModels/RequestModels/MessageListRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/MessageListRequest.cs new file mode 100644 index 00000000..5a19d31a --- /dev/null +++ b/OpenAI.SDK/ObjectModels/RequestModels/MessageListRequest.cs @@ -0,0 +1,12 @@ +锘縰sing System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OpenAI.ObjectModels.RequestModels +{ + public class MessageListRequest : BaseListRequest + { + } +} diff --git a/OpenAI.SDK/ObjectModels/RequestModels/RunCreateRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/RunCreateRequest.cs new file mode 100644 index 00000000..b0d9b9b5 --- /dev/null +++ b/OpenAI.SDK/ObjectModels/RequestModels/RunCreateRequest.cs @@ -0,0 +1,51 @@ +锘縰sing OpenAI.ObjectModels.SharedModels; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace OpenAI.ObjectModels.RequestModels +{ + public class RunCreateRequest : IOpenAiModels.IModel, IOpenAiModels.IMetaData + { + /// + /// The ID of the assistant to use to execute this run. + /// + [Required] + [JsonPropertyName("assistant_id")] + public string AssistantId { get; set; } + + /// + /// The ID of the Model 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. + /// + [JsonPropertyName("instructions")] + public string? Instructions { get; set; } + + /// + /// Override the tools the assistant can use for this run. + /// This is useful for modifying the behavior on a per-run basis. + /// + [JsonPropertyName("tools")] + public List? Tools { 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. + /// + [JsonPropertyName("metadata")] + public Dictionary? MetaData { get; set; } + } +} diff --git a/OpenAI.SDK/ObjectModels/RequestModels/RunListRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/RunListRequest.cs new file mode 100644 index 00000000..876dcfe3 --- /dev/null +++ b/OpenAI.SDK/ObjectModels/RequestModels/RunListRequest.cs @@ -0,0 +1,12 @@ +锘縰sing System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OpenAI.ObjectModels.RequestModels +{ + public class RunListRequest : BaseListRequest + { + } +} diff --git a/OpenAI.SDK/ObjectModels/RequestModels/RunStepListRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/RunStepListRequest.cs new file mode 100644 index 00000000..8b6de04c --- /dev/null +++ b/OpenAI.SDK/ObjectModels/RequestModels/RunStepListRequest.cs @@ -0,0 +1,12 @@ +锘縰sing System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace OpenAI.ObjectModels.RequestModels +{ + public class RunStepListRequest : BaseListRequest + { + } +} diff --git a/OpenAI.SDK/ObjectModels/RequestModels/SubmitToolOutputsToRunRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/SubmitToolOutputsToRunRequest.cs new file mode 100644 index 00000000..b004bcd8 --- /dev/null +++ b/OpenAI.SDK/ObjectModels/RequestModels/SubmitToolOutputsToRunRequest.cs @@ -0,0 +1,40 @@ +锘縰sing System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace OpenAI.ObjectModels.RequestModels +{ + public class SubmitToolOutputsToRunRequest + { + /// + /// A list of tools for which the outputs are being submitted. + /// + [Required] + [JsonPropertyName("tool_outputs")] + public List ToolOutputs { get; set; } + } + + /// + /// A list of tools for which the outputs are being submitted. + /// + public class ToolOutput + { + /// + /// The ID of the tool call in the required_action object + /// within the run object the output is being submitted for. + /// + [JsonPropertyName("tool_call_id")] + public string ToolCallId { get; set; } + + /// + /// The output of the tool call to be submitted to continue the run. + /// + [JsonPropertyName("output")] + public string Output { get; set; } + } + +} diff --git a/OpenAI.SDK/ObjectModels/RequestModels/ThreadCreateRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/ThreadCreateRequest.cs new file mode 100644 index 00000000..ee6a768e --- /dev/null +++ b/OpenAI.SDK/ObjectModels/RequestModels/ThreadCreateRequest.cs @@ -0,0 +1,27 @@ +锘縰sing OpenAI.ObjectModels.SharedModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace OpenAI.ObjectModels.RequestModels +{ + public class ThreadCreateRequest : IOpenAiModels.IMetaData + { + /// + /// A list of messages to start the thread with. + /// + [JsonPropertyName("messages")] + public List Messages { 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. + /// + [JsonPropertyName("metadata")] + public Dictionary MetaData { get; set; } + } +} diff --git a/OpenAI.SDK/ObjectModels/RequestModels/ToolDefinition.cs b/OpenAI.SDK/ObjectModels/RequestModels/ToolDefinition.cs index 5a1cf9b8..f28153d2 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/ToolDefinition.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/ToolDefinition.cs @@ -46,4 +46,13 @@ public object? FunctionCalculated Type = StaticValues.CompletionStatics.ToolType.Function, Function = function }; + + public static ToolDefinition DefineCodeInterpreter() => new() + { + Type = StaticValues.AssistatntsStatics.ToolCallTypes.CodeInterpreter, + }; + public static ToolDefinition DefineRetrieval() => new() + { + Type = StaticValues.AssistatntsStatics.ToolCallTypes.Retrieval, + }; } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/AssistantFileListResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/AssistantFileListResponse.cs new file mode 100644 index 00000000..35ccde9c --- /dev/null +++ b/OpenAI.SDK/ObjectModels/ResponseModels/AssistantFileListResponse.cs @@ -0,0 +1,22 @@ +锘縰sing OpenAI.ObjectModels.SharedModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace OpenAI.ObjectModels.ResponseModels +{ + public record AssistantFileListResponse : DataBaseResponse> + { + [JsonPropertyName("first_id")] + public string FirstId { get; set; } + + [JsonPropertyName("last_id")] + public string LastId { get; set; } + + [JsonPropertyName("has_more")] + public bool IsHasMore { get; set; } + } +} diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/AssistantListResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/AssistantListResponse.cs new file mode 100644 index 00000000..1ecb58aa --- /dev/null +++ b/OpenAI.SDK/ObjectModels/ResponseModels/AssistantListResponse.cs @@ -0,0 +1,22 @@ +锘縰sing OpenAI.ObjectModels.SharedModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace OpenAI.ObjectModels.ResponseModels +{ + public record AssistantListResponse : DataBaseResponse> + { + [JsonPropertyName("first_id")] + public string FirstId { get; set; } + + [JsonPropertyName("last_id")] + public string LastId { get; set; } + + [JsonPropertyName("has_more")] + public bool IsHasMore { get; set; } + } +} diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/MessageListResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/MessageListResponse.cs new file mode 100644 index 00000000..5b56eba0 --- /dev/null +++ b/OpenAI.SDK/ObjectModels/ResponseModels/MessageListResponse.cs @@ -0,0 +1,22 @@ +锘縰sing OpenAI.ObjectModels.SharedModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace OpenAI.ObjectModels.ResponseModels +{ + public record MessageListResponse : DataBaseResponse> + { + [JsonPropertyName("first_id")] + public string FirstId { get; set; } + + [JsonPropertyName("last_id")] + public string LastId { get; set; } + + [JsonPropertyName("has_more")] + public bool IsHasMore { get; set; } + } +} diff --git a/OpenAI.SDK/ObjectModels/SharedModels/AssistantFileResponse.cs b/OpenAI.SDK/ObjectModels/SharedModels/AssistantFileResponse.cs new file mode 100644 index 00000000..f33e4f45 --- /dev/null +++ b/OpenAI.SDK/ObjectModels/SharedModels/AssistantFileResponse.cs @@ -0,0 +1,31 @@ +锘縰sing OpenAI.ObjectModels.ResponseModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace OpenAI.ObjectModels.SharedModels +{ + public record AssistantFileResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.ICreatedAt + { + /// + /// The identifier, which can be referenced in API endpoints. + /// + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// The Unix timestamp (in seconds) for when the assistant file was created. + /// + [JsonPropertyName("created_at")] + public int CreatedAt { get; set; } + + /// + /// The Unix timestamp (in seconds) for when the assistant file was created. + /// + [JsonPropertyName("assistant_id")] + public string AssistantId { get; set; } + } +} diff --git a/OpenAI.SDK/ObjectModels/SharedModels/AssistantResponse.cs b/OpenAI.SDK/ObjectModels/SharedModels/AssistantResponse.cs new file mode 100644 index 00000000..17f2256d --- /dev/null +++ b/OpenAI.SDK/ObjectModels/SharedModels/AssistantResponse.cs @@ -0,0 +1,71 @@ +锘縰sing OpenAI.ObjectModels.RequestModels; +using OpenAI.ObjectModels.ResponseModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace OpenAI.ObjectModels.SharedModels +{ + public record AssistantResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.ICreatedAt, IOpenAiModels.IModel, IOpenAiModels.IMetaData + { + /// + /// The identifier, which can be referenced in API endpoints. + /// + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// The Unix timestamp (in seconds) for when the assistant was created. + /// + [JsonPropertyName("created_at")] + public int CreatedAt { get; set; } + + /// + /// The name of the assistant. The maximum length is 256 characters. + /// + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// The description of the assistant. The maximum length is 512 characters. + /// + [JsonPropertyName("description")] + public string Description { get; set; } + + /// + /// ID of the model to use + /// + [JsonPropertyName("model")] + public string Model { get; set; } + + /// + ///The system instructions that the assistant uses. + ///The maximum length is 32768 characters. + /// + [JsonPropertyName("instructions")] + public string Insturctions { 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. + /// Files are ordered by their creation date in ascending order. + /// + [JsonPropertyName("file_ids")] + public List FileIDs { get; set; } + + /// + /// Set of 16 key-value pairs that can be attached to an object. + /// + [JsonPropertyName("metadata")] + public Dictionary MetaData { get; set; } + } +} diff --git a/OpenAI.SDK/ObjectModels/SharedModels/AssistatntFileResponse.cs b/OpenAI.SDK/ObjectModels/SharedModels/AssistatntFileResponse.cs new file mode 100644 index 00000000..47f8757d --- /dev/null +++ b/OpenAI.SDK/ObjectModels/SharedModels/AssistatntFileResponse.cs @@ -0,0 +1,31 @@ +锘縰sing OpenAI.ObjectModels.ResponseModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace OpenAI.ObjectModels.SharedModels +{ + public record AssistatntFileResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.ICreatedAt + { + /// + /// The identifier, which can be referenced in API endpoints. + /// + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// The Unix timestamp (in seconds) for when the assistant was created. + /// + [JsonPropertyName("created_at")] + public int CreatedAt { get; set; } + + /// + /// The assistant ID that the file is attached to. + /// + [JsonPropertyName("assistant_id")] + public string AssistantId { get; set; } + } +} diff --git a/OpenAI.SDK/ObjectModels/SharedModels/DeletionStatusResponse.cs b/OpenAI.SDK/ObjectModels/SharedModels/DeletionStatusResponse.cs new file mode 100644 index 00000000..86fd5886 --- /dev/null +++ b/OpenAI.SDK/ObjectModels/SharedModels/DeletionStatusResponse.cs @@ -0,0 +1,25 @@ +锘縰sing OpenAI.ObjectModels.ResponseModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace OpenAI.ObjectModels.SharedModels +{ + public record DeletionStatusResponse : BaseResponse, IOpenAiModels.IId + { + /// + /// The identifier, which can be referenced in API endpoints. + /// + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// Deletion state + /// + [JsonPropertyName("deleted")] + public bool IsDeleted { get; set; } + } +} diff --git a/OpenAI.SDK/ObjectModels/SharedModels/IOpenAiModels.cs b/OpenAI.SDK/ObjectModels/SharedModels/IOpenAiModels.cs index 47a5ac05..b5d35c1f 100644 --- a/OpenAI.SDK/ObjectModels/SharedModels/IOpenAiModels.cs +++ b/OpenAI.SDK/ObjectModels/SharedModels/IOpenAiModels.cs @@ -43,4 +43,19 @@ public interface IFile public Stream FileStream { get; set; } public string FileName { get; set; } } + + public interface ISystemFingerPrint + { + public string SystemFingerPrint { get; set; } + } + + public interface IMetaData + { + public Dictionary MetaData { get; set; } + } + + public interface IFileIds + { + public List FileIds { get; set;} + } } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/SharedModels/LastError.cs b/OpenAI.SDK/ObjectModels/SharedModels/LastError.cs new file mode 100644 index 00000000..48985313 --- /dev/null +++ b/OpenAI.SDK/ObjectModels/SharedModels/LastError.cs @@ -0,0 +1,24 @@ +锘縰sing System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace OpenAI.ObjectModels.SharedModels +{ + public record LastError + { + /// + /// One of server_error or rate_limit_exceeded. + /// + [JsonPropertyName("code")] + public string Code { get; set; } + + /// + /// A human-readable description of the error. + /// + [JsonPropertyName("message")] + public string Message { get; set; } + } +} diff --git a/OpenAI.SDK/ObjectModels/SharedModels/MessageAnnotation.cs b/OpenAI.SDK/ObjectModels/SharedModels/MessageAnnotation.cs new file mode 100644 index 00000000..c3b464de --- /dev/null +++ b/OpenAI.SDK/ObjectModels/SharedModels/MessageAnnotation.cs @@ -0,0 +1,44 @@ +锘縰sing System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace OpenAI.ObjectModels.SharedModels +{ + /// + /// File citation |File path + /// + public record MessageAnnotation + { + /// + /// type can be锛歠ile_citation銆乫ile_path + /// + [JsonPropertyName("type")] + public string Type { get; set; } + /// + /// The text in the message content that needs to be replaced. + /// + [JsonPropertyName("text")] + public string Text { get; set; } + + [JsonPropertyName("start_index")] + public int StartIndex { get; set; } + + [JsonPropertyName("end_index")] + public int EndIndex { get; set; } + + /// + /// The ID of the specific File the citation/content is from. + /// + [JsonPropertyName("file_id")] + public string FileId { get; set; } + + /// + /// The specific quote in the file. + /// + [JsonPropertyName("quote")] + public string Quote { get; set; } + } +} diff --git a/OpenAI.SDK/ObjectModels/SharedModels/MessageImageFile.cs b/OpenAI.SDK/ObjectModels/SharedModels/MessageImageFile.cs new file mode 100644 index 00000000..fd052388 --- /dev/null +++ b/OpenAI.SDK/ObjectModels/SharedModels/MessageImageFile.cs @@ -0,0 +1,21 @@ +锘縰sing System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace OpenAI.ObjectModels.SharedModels +{ + /// + /// An image File in the content of a message. + /// + public record MessageImageFile + { + /// + /// The File ID of the image in the message content. + /// + [JsonPropertyName("file_id")] + public string FileId { get; set; } + } +} diff --git a/OpenAI.SDK/ObjectModels/SharedModels/MessageResponse.cs b/OpenAI.SDK/ObjectModels/SharedModels/MessageResponse.cs new file mode 100644 index 00000000..5bc1ecce --- /dev/null +++ b/OpenAI.SDK/ObjectModels/SharedModels/MessageResponse.cs @@ -0,0 +1,97 @@ +锘縰sing OpenAI.ObjectModels.ResponseModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace OpenAI.ObjectModels.SharedModels +{ + /// + /// Represents a message within a thread. + /// + public record MessageResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.ICreatedAt,IOpenAiModels.IMetaData + { + /// + /// The identifier, which can be referenced in API endpoints. + /// + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// The Unix timestamp (in seconds) for when the message was created. + /// + [JsonPropertyName("created_at")] + public int CreatedAt { get; set; } + + /// + /// The thread ID that this message belongs to. + /// + [JsonPropertyName("thread_id")] + public string ThreadId { get; set; } + + /// + /// The entity that produced the message. One of user or assistant. + /// + [JsonPropertyName("role")] + public string Role { get; set; } + + /// + /// The content of the message in array of text and/or images. + /// + [JsonPropertyName("content")] + public List? Content { get; set; } + + /// + /// If applicable, the ID of the assistant that authored this message. + /// + [JsonPropertyName("assistant_id")] + public string? AssistantId { get; set; } + + /// + /// If applicable, the ID of the run associated with the authoring of this message. + /// + [JsonPropertyName("run_id")] + public string? RunId { get; set; } + + /// + /// A list of file IDs that the assistant should use. + /// Useful for tools like retrieval and code_interpreter that can access files. + /// A maximum of 10 files can be attached to a message. + /// + [JsonPropertyName("file_ids")] + public List FileIds { get; set; } + + /// + /// Set of 16 key-value pairs that can be attached to an object. + /// + [JsonPropertyName("metadata")] + public Dictionary MetaData { get; set; } + } + + /// + /// The content of the message: text and/or images. + /// + public record MessageContent + { + /// + /// text and/or images. image_file銆乼ext + /// + [JsonPropertyName("type")] + public string Type { get; set; } + + /// + /// References an image File in the content of a message. + /// + [JsonPropertyName("image_file")] + public MessageImageFile? ImageFile { get; set; } + + /// + /// The text content that is part of a message. + /// + [JsonPropertyName("text")] + public MessageText? Text { get; set; } + } + +} diff --git a/OpenAI.SDK/ObjectModels/SharedModels/MessageText.cs b/OpenAI.SDK/ObjectModels/SharedModels/MessageText.cs new file mode 100644 index 00000000..c324b931 --- /dev/null +++ b/OpenAI.SDK/ObjectModels/SharedModels/MessageText.cs @@ -0,0 +1,27 @@ +锘縰sing System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace OpenAI.ObjectModels.SharedModels +{ + /// + /// The text content that is part of a message. + /// + public record MessageText + { + /// + /// The data that makes up the text. + /// + [JsonPropertyName("value")] + public string Value { get; set; } + + /// + /// annotations + /// + [JsonPropertyName("annotations")] + public List Annotations { get; set; } + } +} diff --git a/OpenAI.SDK/ObjectModels/SharedModels/RequiredAction.cs b/OpenAI.SDK/ObjectModels/SharedModels/RequiredAction.cs new file mode 100644 index 00000000..dd6d6233 --- /dev/null +++ b/OpenAI.SDK/ObjectModels/SharedModels/RequiredAction.cs @@ -0,0 +1,37 @@ +锘縰sing OpenAI.ObjectModels.RequestModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace OpenAI.ObjectModels.SharedModels +{ + /// + /// Details on the action required to continue the run. + /// + public class RequiredAction + { + /// + /// For now, this is always submit_tool_outputs. + /// + [JsonPropertyName("type")] + public string Type { get; set; } + + /// + /// Details on the tool outputs needed for this run to continue. + /// + [JsonPropertyName("submit_tool_outputs")] + public SubmitToolOutputs SubmitToolOutputs { get; set; } + } + + public class SubmitToolOutputs + { + /// + /// A list of the relevant tool calls. + /// + [JsonPropertyName("tool_calls")] + public List ToolCalls { get; set; } + } +} diff --git a/OpenAI.SDK/ObjectModels/SharedModels/RunResponse.cs b/OpenAI.SDK/ObjectModels/SharedModels/RunResponse.cs new file mode 100644 index 00000000..c81e9e90 --- /dev/null +++ b/OpenAI.SDK/ObjectModels/SharedModels/RunResponse.cs @@ -0,0 +1,136 @@ +锘縰sing OpenAI.ObjectModels.RequestModels; +using OpenAI.ObjectModels.ResponseModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace OpenAI.ObjectModels.SharedModels +{ + public record RunResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.IModel, IOpenAiModels.ICreatedAt, IOpenAiModels.IFileIds, IOpenAiModels.IMetaData + { + /// + /// The identifier, which can be referenced in API endpoints. + /// + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// The Unix timestamp (in seconds) for when the run was created. + /// + [JsonPropertyName("created_at")] + public int CreatedAt { get; set; } + + /// + /// The ID of the thread that was executed on as a part of this run. + /// + [JsonPropertyName("thread_id")] + public string ThreadId { get; set; } + + /// + /// The ID of the assistant used for execution of this run. + /// + [JsonPropertyName("assistant_id")] + public string AssistantId { get; set; } + + /// + /// The status of the run, which can be either queued, in_progress, requires_action, cancelling, cancelled, failed, completed, or expired. + /// + [JsonPropertyName("status")] + public string Status { get; set; } + + /// + /// Details on the action required to continue the run. + /// Will be null if no action is required. + /// + [JsonPropertyName("required_action")] + public RequiredAction? RequiredAction { get; set; } + + + private LastError _lastError; + /// + /// The last error associated with this run. Will be null if there are no errors. + /// + [JsonPropertyName("last_error")] + public LastError? LastError + { + get => _lastError; + set + { + _lastError = value; + if (_lastError == null) return; + + this.Error = new Error() + { + Code = _lastError.Code, + MessageObject = _lastError.Message, + }; + } + } + + /// + /// The Unix timestamp (in seconds) for when the run will expire. + /// + [JsonPropertyName("expires_at")] + public int? ExpiresAt { get; set; } + + /// + /// The Unix timestamp (in seconds) for when the run was started. + /// + [JsonPropertyName("started_at")] + public int? StartedAt { get; set; } + + /// + /// The Unix timestamp (in seconds) for when the run was cancelled. + /// + [JsonPropertyName("cancelled_at")] + public int? CancelledAt { get; set; } + + /// + /// The Unix timestamp (in seconds) for when the run failed. + /// + [JsonPropertyName("failed_at")] + public int? FailedAt { get; set; } + + /// + /// The Unix timestamp (in seconds) for when the run was completed. + /// + [JsonPropertyName("completed_at")] + public int? CompletedAt { get; set; } + + /// + /// The model that the assistant used for this run. + /// + [JsonPropertyName("model")] + public string Model { get; set; } + + /// + ///The instructions that the assistant used for this run. + /// + [JsonPropertyName("instructions")] + public string Instructions { get; set; } + + /// + /// The list of tools that the assistant used for this run. + /// + [JsonPropertyName("tools")] + public List? Tools { get; set; } + + /// + /// The list of File IDs the assistant used for this run. + /// + [JsonPropertyName("file_ids")] + public List? FileIds { 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. + /// + [JsonPropertyName("metadata")] + public Dictionary? MetaData { get; set; } + + } +} diff --git a/OpenAI.SDK/ObjectModels/SharedModels/ThreadResponse.cs b/OpenAI.SDK/ObjectModels/SharedModels/ThreadResponse.cs new file mode 100644 index 00000000..636c8393 --- /dev/null +++ b/OpenAI.SDK/ObjectModels/SharedModels/ThreadResponse.cs @@ -0,0 +1,31 @@ +锘縰sing OpenAI.ObjectModels.ResponseModels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json.Serialization; +using System.Threading.Tasks; + +namespace OpenAI.ObjectModels.SharedModels +{ + public record ThreadResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.ICreatedAt, IOpenAiModels.IMetaData + { + /// + /// The identifier, which can be referenced in API endpoints. + /// + [JsonPropertyName("id")] + public string Id { get; set; } + + /// + /// The Unix timestamp (in seconds) for when the assistant was created. + /// + [JsonPropertyName("created_at")] + public int CreatedAt { get; set; } + + /// + /// Set of 16 key-value pairs that can be attached to an object. + /// + [JsonPropertyName("metadata")] + public Dictionary MetaData { get; set; } + } +} diff --git a/OpenAI.SDK/ObjectModels/StaticValueHelper.cs b/OpenAI.SDK/ObjectModels/StaticValueHelper.cs index 4a4d9b8c..66cc5eaf 100644 --- a/OpenAI.SDK/ObjectModels/StaticValueHelper.cs +++ b/OpenAI.SDK/ObjectModels/StaticValueHelper.cs @@ -110,5 +110,57 @@ public static class ChatMessageRoles public static string User => "user"; public static string Assistant => "assistant"; public static string Tool => "tool"; + public static string Function => "function"; + + } + + public static class AssistatntsStatics + { + public static class ToolCallTypes + { + public static string CodeInterpreter => "code_interpreter"; + public static string Retrieval => "retrieval"; + public static string Function => "function"; + } + + public static class MessageStatics + { + public static class Roles + { + public static string User => "user"; + public static string Assistant => "assistant"; + } + + public static class Content + { + public static string ImageFile => "image_file"; + public static string Text => "text"; + + + public static class Annotations + { + public static string FileCitation => "file_citation"; + public static string FilePath => "file_path"; + } + } + } + + public static class RunStatus + { + public static string Queued => "queued"; + public static string InProgress => "in_progress"; + public static string RequiresAction => "requires_action"; + public static string Cancelling => "cancelling"; + public static string Cancelled => "cancelled"; + public static string Failed => "failed"; + public static string Completed => "completed"; + public static string Expired => "expired"; + } + + 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 a6fc76cf..0204e952 100644 --- a/OpenAI.SDK/ObjectModels/UploadFilePurposes.cs +++ b/OpenAI.SDK/ObjectModels/UploadFilePurposes.cs @@ -5,11 +5,13 @@ public static class UploadFilePurposes public enum UploadFilePurpose { FineTune, - FineTuneResults + FineTuneResults, + Assistants, } public const string FineTune = "fine-tune"; public const string FineTuneResults = "fine-tune-results"; + public const string Assistants = "assistants"; public static string EnumToString(this UploadFilePurpose uploadFilePurpose) { @@ -17,6 +19,7 @@ public static string EnumToString(this UploadFilePurpose uploadFilePurpose) { UploadFilePurpose.FineTune => FineTune, UploadFilePurpose.FineTuneResults => FineTuneResults, + UploadFilePurpose.Assistants => Assistants, _ => throw new ArgumentOutOfRangeException(nameof(uploadFilePurpose), uploadFilePurpose, null) }; } @@ -27,6 +30,7 @@ public static UploadFilePurpose ToEnum(string filePurpose) { FineTune => UploadFilePurpose.FineTune, FineTuneResults => UploadFilePurpose.FineTuneResults, + Assistants => UploadFilePurpose.Assistants, _ => throw new ArgumentOutOfRangeException(nameof(filePurpose), filePurpose, null) }; } diff --git a/OpenAI.SDK/OpenAiOptions.cs b/OpenAI.SDK/OpenAiOptions.cs index e268ff59..01166120 100644 --- a/OpenAI.SDK/OpenAiOptions.cs +++ b/OpenAI.SDK/OpenAiOptions.cs @@ -21,7 +21,7 @@ public class OpenAiOptions private const string OpenAiDefaultApiVersion = "v1"; private const string OpenAiDefaultBaseDomain = "https://api.openai.com/"; private const string AzureOpenAiDefaultApiVersion = "2023-12-01-preview"; - + private const string OpenAiDefaultAssistantsApiVersion = "v1"; /// /// Setting key for Json Setting Bindings @@ -37,6 +37,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鈥檙e using OpenAI鈥檚 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. From 03d5ac56568f2d291d61f93f5367bf7469af4404 Mon Sep 17 00:00:00 2001 From: PeterHu Date: Tue, 2 Jan 2024 16:06:37 +0800 Subject: [PATCH 02/26] [BUGFIX] Fixed an issue with assistants API deletion failure --- OpenAI.Playground/Program.cs | 1 + .../TestHelpers/AssistantTestHelper.cs | 157 ++++++++++++------ OpenAI.SDK/Managers/OpenAIAssistantService.cs | 4 +- OpenAI.SDK/Managers/OpenAIThreadService.cs | 2 +- 4 files changed, 113 insertions(+), 51 deletions(-) diff --git a/OpenAI.Playground/Program.cs b/OpenAI.Playground/Program.cs index af4163af..cfdd3363 100644 --- a/OpenAI.Playground/Program.cs +++ b/OpenAI.Playground/Program.cs @@ -43,6 +43,7 @@ // |-----------------------------------------------------------------------| //Assistants +//await AssistantTestHelper.RunAssistantAPITest(sdk); await AssistantTestHelper.RunHowAssistantsWorkTest(sdk); //await ChatCompletionTestHelper.RunSimpleChatCompletionTest(sdk); diff --git a/OpenAI.Playground/TestHelpers/AssistantTestHelper.cs b/OpenAI.Playground/TestHelpers/AssistantTestHelper.cs index 318849db..c23833a5 100644 --- a/OpenAI.Playground/TestHelpers/AssistantTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/AssistantTestHelper.cs @@ -14,47 +14,103 @@ namespace OpenAI.Playground.TestHelpers { internal static class AssistantTestHelper { - public static async Task RunAssistantCreateTest(IOpenAIService sdk) + /// + /// Test Assistant api + /// + /// + /// + public static async Task RunAssistantAPITest(IOpenAIService sdk) { - ConsoleExtensions.WriteLine("Assistant create Testing is starting:", ConsoleColor.Cyan); + ConsoleExtensions.WriteLine("Assistant APT Testing is starting:"); - var func = 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.")) + #region Create assistant + var func = new FunctionDefinitionBuilder("get_corp_location", "get location of corp") + .AddParameter("name", PropertyDefinition.DefineString("compary name, e.g. Betterway")) .Validate() .Build(); - try + ConsoleExtensions.WriteLine("Assistant Create Test:", ConsoleColor.DarkCyan); + var assistantResult = await sdk.Beta.Assistants.AssistantCreate(new AssistantCreateRequest { - ConsoleExtensions.WriteLine("Assistant Create Test:", ConsoleColor.DarkCyan); - var assistantResult = await sdk.Beta.Assistants.AssistantCreate(new AssistantCreateRequest - { - Instructions = "You are a personal math tutor. When asked a question, write and run Python code to answer the question.", - Name = "Math Tutor", - Tools = new List() { ToolDefinition.DefineCodeInterpreter(), ToolDefinition.DefineRetrieval(), ToolDefinition.DefineFunction(func) }, - Model = Models.Gpt_3_5_Turbo_1106 - }); + 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.DefineRetrieval(), ToolDefinition.DefineFunction(func) }, + Model = Models.Gpt_3_5_Turbo_1106 + }); + if (assistantResult.Successful) + { + var assistant = assistantResult; + ConsoleExtensions.WriteLine(assistant.ToJson()); + } + else + { + ConsoleExtensions.WriteLine($"{assistantResult.Error?.Code}: {assistantResult.Error?.Message}"); + return; + } + var assistantId = assistantResult.Id; + ConsoleExtensions.WriteLine($"assistantId:{assistantId} "); + #endregion - if (assistantResult.Successful) - { - var assistant = assistantResult; - ConsoleExtensions.WriteLine(assistant.ToJson()); - } - else - { - if (assistantResult.Error == null) - { - throw new Exception("Unknown Error"); - } - ConsoleExtensions.WriteLine($"{assistantResult.Error.Code}: {assistantResult.Error.Message}"); - } + + #region// Assistant List + ConsoleExtensions.WriteLine("Assistant list:", ConsoleColor.DarkCyan); + var asstListResult = await sdk.Beta.Assistants.AssistantList(); + if (asstListResult.Successful) + { + ConsoleExtensions.WriteLine($"asst list: {asstListResult.Data?.ToJson()}"); + } + else + { + ConsoleExtensions.WriteLine($"{asstListResult.Error?.Code}: {asstListResult.Error?.Message}"); + return; + } + #endregion + + #region// Assistant modify + ConsoleExtensions.WriteLine("Assistant modify:", ConsoleColor.DarkCyan); + var asstResult = await sdk.Beta.Assistants.AssistantModify(assistantId,new AssistantModifyRequest() + { + Name= "Qicha rename" + }); + if (asstResult.Successful) + { + ConsoleExtensions.WriteLine(asstResult.ToJson()); + } + else + { + ConsoleExtensions.WriteLine($"{asstResult.Error?.Code}: {asstResult.Error?.Message}"); + return; } - catch (Exception e) + #endregion + + #region// Assistant retrieve + ConsoleExtensions.WriteLine("Assistant retrieve:", ConsoleColor.DarkCyan); + var asstRetrieveResult = await sdk.Beta.Assistants.AssistantRetrieve(assistantId); + if (asstRetrieveResult.Successful) { - Console.WriteLine(e); - throw; + ConsoleExtensions.WriteLine(asstRetrieveResult.ToJson()); } + else + { + ConsoleExtensions.WriteLine($"{asstRetrieveResult.Error?.Code}: {asstRetrieveResult.Error?.Message}"); + return; + } + #endregion + + #region// Assistant delete + ConsoleExtensions.WriteLine("Assistant delete:", ConsoleColor.DarkCyan); + var deleteResult = await sdk.Beta.Assistants.AssistantDelete(assistantId); + if (deleteResult.Successful) + { + ConsoleExtensions.WriteLine(deleteResult.ToJson()); + } + else + { + ConsoleExtensions.WriteLine($"{deleteResult.Error?.Code}: {deleteResult.Error?.Message}"); + return; + } + #endregion } /// @@ -65,7 +121,7 @@ public static async Task RunAssistantCreateTest(IOpenAIService sdk) /// public static async Task RunHowAssistantsWorkTest(IOpenAIService sdk) { - ConsoleExtensions.WriteLine("Assistant work Testing is starting:", ConsoleColor.Cyan); + ConsoleExtensions.WriteLine("How assistant work Testing is starting:", ConsoleColor.DarkCyan); #region//upload file const string fileName = "betterway_corp.csv"; @@ -88,17 +144,16 @@ public static async Task RunHowAssistantsWorkTest(IOpenAIService sdk) #endregion #region//create assistants - - var func = new FunctionDefinitionBuilder("get_corp_location", "鑾峰彇鍏徃浣嶇疆") - .AddParameter("name", PropertyDefinition.DefineString("鍏徃鍚嶇О锛屼緥濡傦細浣崇▼渚涘簲閾")) + var func = new FunctionDefinitionBuilder("get_corp_location", "get location of corp") + .AddParameter("name", PropertyDefinition.DefineString("compary name, e.g. Betterway")) .Validate() .Build(); ConsoleExtensions.WriteLine("Assistant Create Test:", ConsoleColor.DarkCyan); var assistantResult = await sdk.Beta.Assistants.AssistantCreate(new AssistantCreateRequest { - Name = "浼佹煡鏌", - Instructions = "浣犳槸涓涓笓涓氭彁渚涘叕鍙镐俊鎭殑鍔╂墜銆傚叕鍙哥浉鍏虫暟鎹潵鑷笂浼犵殑闂锛屼笉鎻愪緵妯$硦涓嶆竻鐨勫洖绛旓紝鍙彁渚涙槑纭殑绛旀", + 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.DefineRetrieval(), ToolDefinition.DefineFunction(func) }, FileIds = new List() { uplaodFileId }, @@ -138,7 +193,7 @@ public static async Task RunHowAssistantsWorkTest(IOpenAIService sdk) var messageResult = await sdk.Beta.Messages.MessageCreate(threadId, new MessageCreateRequest { Role = StaticValues.AssistatntsStatics.MessageStatics.Roles.User, - Content = "娴欐睙浣崇▼渚涘簲閾炬湁闄愬叕鍙稿叿浣撳湪鍝", + Content = "Where is Zhejiang Jiacheng Supply Chain Co., LTD.", FileIds = new List() { uplaodFileId }, }); @@ -176,13 +231,16 @@ public static async Task RunHowAssistantsWorkTest(IOpenAIService sdk) #region//waiting for run completed ConsoleExtensions.WriteLine("waiting for run completed:", ConsoleColor.DarkCyan); - var doneStatusList = new List() { StaticValues.AssistatntsStatics.RunStatus.Cancelled, StaticValues.AssistatntsStatics.RunStatus.Completed, StaticValues.AssistatntsStatics.RunStatus.Failed, StaticValues.AssistatntsStatics.RunStatus.Expired }; + var runningStatusList = new List() + { + StaticValues.AssistatntsStatics.RunStatus.Queued, + StaticValues.AssistatntsStatics.RunStatus.InProgress, + StaticValues.AssistatntsStatics.RunStatus.RequiresAction, + }; //鑾峰彇浠诲姟淇℃伅 var runRetrieveResult = await sdk.Beta.Runs.RunRetrieve(threadId, runId); - var runStatus = runRetrieveResult.Status; - - while (!doneStatusList.Contains(runStatus)) + while (runningStatusList.Contains(runRetrieveResult.Status)) { /* * When a run has the status: "requires_action" and required_action.type is submit_tool_outputs, @@ -190,7 +248,7 @@ public static async Task RunHowAssistantsWorkTest(IOpenAIService sdk) * All outputs must be submitted in a single request. */ var requireAction = runRetrieveResult.RequiredAction; - if (runStatus == StaticValues.AssistatntsStatics.RunStatus.RequiresAction + if (runRetrieveResult.Status == StaticValues.AssistatntsStatics.RunStatus.RequiresAction && requireAction != null && requireAction.Type == StaticValues.AssistatntsStatics.RequiredActionTypes.SubmitToolOutputs) { var myFunc = new List() { "get_corp_location" }; @@ -207,7 +265,8 @@ public static async Task RunHowAssistantsWorkTest(IOpenAIService sdk) var toolOutput = new ToolOutput() { ToolCallId = toolCall.Id, - Output = "娴欐睙浣崇▼渚涘簲閾炬湁闄愬叕鍙,浣嶄簬娴欐睙鐪侀噾鍗庡競濠哄煄鍖哄叓涓鍖楄615鍙蜂匠绋嬪浗闄呭晢鍔′腑蹇僛from ToolOutput]", + Output = @"Zhejiang Jiacheng Supply Chain Co., Ltd. is located in Jiacheng International Business Center, +No.615 Bayi North Street, Wucheng District, Jinhua City, Zhejiang Province", }; toolOutputs.Add(toolOutput); } @@ -226,27 +285,29 @@ public static async Task RunHowAssistantsWorkTest(IOpenAIService sdk) } runRetrieveResult = await sdk.Beta.Runs.RunRetrieve(threadId, runId); - runStatus = runRetrieveResult.Status; - if (doneStatusList.Contains(runStatus)) { break; } + if (!runningStatusList.Contains(runRetrieveResult.Status)) { break; } } #endregion - + #region// message list //鑾峰彇鏈缁堟秷鎭粨鏋 ConsoleExtensions.WriteLine("Message list:", ConsoleColor.DarkCyan); var messageListResult = await sdk.Beta.Messages.MessageList(threadId); if (messageListResult.Successful) { - ConsoleExtensions.WriteLine(messageListResult.ToJson()); + var msgRespList = messageListResult.Data; + var ask = msgRespList?.FirstOrDefault(msg => msg.Role == StaticValues.AssistatntsStatics.MessageStatics.Roles.User); + var replys = msgRespList?.Where(msg => msg.CreatedAt > ask?.CreatedAt && msg.Role == StaticValues.AssistatntsStatics.MessageStatics.Roles.Assistant).ToList() ?? new List(); + ConsoleExtensions.WriteLine(replys.ToJson()); } else { ConsoleExtensions.WriteLine($"{messageListResult.Error?.Code}: {messageListResult.Error?.Message}"); return; } - + #endregion } diff --git a/OpenAI.SDK/Managers/OpenAIAssistantService.cs b/OpenAI.SDK/Managers/OpenAIAssistantService.cs index d8d90def..876e4bf2 100644 --- a/OpenAI.SDK/Managers/OpenAIAssistantService.cs +++ b/OpenAI.SDK/Managers/OpenAIAssistantService.cs @@ -71,7 +71,7 @@ public async Task AssistantDelete(string assistantId, Ca { if (string.IsNullOrWhiteSpace(assistantId)) { throw new ArgumentNullException(nameof(assistantId)); } - return await _httpClient.GetReadAsAsync(_endpointProvider.AssistantDelete(assistantId), cancellationToken); + return await _httpClient.DeleteAndReadAsAsync(_endpointProvider.AssistantDelete(assistantId), cancellationToken); } /// @@ -80,7 +80,7 @@ public async Task AssistantFileDelete(string assistantId if (string.IsNullOrWhiteSpace(assistantId)) { throw new ArgumentNullException(nameof(assistantId)); } if (string.IsNullOrWhiteSpace(fileId)) { throw new ArgumentNullException(nameof(fileId)); } - return await _httpClient.GetReadAsAsync(_endpointProvider.AssistantFileDelete(assistantId, fileId), cancellationToken); + return await _httpClient.DeleteAndReadAsAsync(_endpointProvider.AssistantFileDelete(assistantId, fileId), cancellationToken); } diff --git a/OpenAI.SDK/Managers/OpenAIThreadService.cs b/OpenAI.SDK/Managers/OpenAIThreadService.cs index e5400edc..65228f1f 100644 --- a/OpenAI.SDK/Managers/OpenAIThreadService.cs +++ b/OpenAI.SDK/Managers/OpenAIThreadService.cs @@ -50,7 +50,7 @@ public async Task ThreadDelete(string threadId, Cancella { if (string.IsNullOrWhiteSpace(threadId)) { throw new ArgumentNullException(nameof(threadId)); } - return await _httpClient.GetReadAsAsync(_endpointProvider.ThreadRetrieve(threadId), cancellationToken); + return await _httpClient.DeleteAndReadAsAsync(_endpointProvider.ThreadRetrieve(threadId), cancellationToken); } } } From e7e4e303476bbfed52c7a37bea72fde3598409ba Mon Sep 17 00:00:00 2001 From: PeterHu Date: Tue, 2 Jan 2024 17:47:07 +0800 Subject: [PATCH 03/26] [CHG] Resolved namespace conflicts in MessageContent --- .../SharedModels/MessageResponse.cs | 44 +++++++++---------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/OpenAI.SDK/ObjectModels/SharedModels/MessageResponse.cs b/OpenAI.SDK/ObjectModels/SharedModels/MessageResponse.cs index 5bc1ecce..15213cd6 100644 --- a/OpenAI.SDK/ObjectModels/SharedModels/MessageResponse.cs +++ b/OpenAI.SDK/ObjectModels/SharedModels/MessageResponse.cs @@ -11,7 +11,7 @@ namespace OpenAI.ObjectModels.SharedModels /// /// Represents a message within a thread. /// - public record MessageResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.ICreatedAt,IOpenAiModels.IMetaData + public record MessageResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.ICreatedAt, IOpenAiModels.IMetaData { /// /// The identifier, which can be referenced in API endpoints. @@ -41,7 +41,7 @@ public record MessageResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.I /// The content of the message in array of text and/or images. /// [JsonPropertyName("content")] - public List? Content { get; set; } + public List? Content { get; set; } /// /// If applicable, the ID of the assistant that authored this message. @@ -68,30 +68,30 @@ public record MessageResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.I /// [JsonPropertyName("metadata")] public Dictionary MetaData { get; set; } - } - /// - /// The content of the message: text and/or images. - /// - public record MessageContent - { - /// - /// text and/or images. image_file銆乼ext - /// - [JsonPropertyName("type")] - public string Type { get; set; } /// - /// References an image File in the content of a message. + /// The content of the message: text and/or images. /// - [JsonPropertyName("image_file")] - public MessageImageFile? ImageFile { get; set; } + public class MessageContent + { + /// + /// text and/or images. image_file銆乼ext + /// + [JsonPropertyName("type")] + public string Type { get; set; } - /// - /// The text content that is part of a message. - /// - [JsonPropertyName("text")] - public MessageText? Text { get; set; } - } + /// + /// References an image File in the content of a message. + /// + [JsonPropertyName("image_file")] + public MessageImageFile? ImageFile { get; set; } + /// + /// The text content that is part of a message. + /// + [JsonPropertyName("text")] + public MessageText? Text { get; set; } + } + } } From b6bde0d155efbb89e43785e4975ab4135657f7e8 Mon Sep 17 00:00:00 2001 From: PeterHu Date: Thu, 18 Jan 2024 09:13:45 +0800 Subject: [PATCH 04/26] [FIX] Fix naming error of AssistantsStatics --- .../TestHelpers/AssistantTestHelper.cs | 16 ++++++++-------- .../TestHelpers/MessageTestHelper.cs | 2 +- OpenAI.Playground/TestHelpers/RunTestHelper.cs | 6 +++--- .../RequestModels/MessageCreateRequest.cs | 2 +- .../ObjectModels/RequestModels/ToolDefinition.cs | 4 ++-- OpenAI.SDK/ObjectModels/StaticValueHelper.cs | 2 +- 6 files changed, 16 insertions(+), 16 deletions(-) diff --git a/OpenAI.Playground/TestHelpers/AssistantTestHelper.cs b/OpenAI.Playground/TestHelpers/AssistantTestHelper.cs index c23833a5..5fca5ced 100644 --- a/OpenAI.Playground/TestHelpers/AssistantTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/AssistantTestHelper.cs @@ -192,7 +192,7 @@ public static async Task RunHowAssistantsWorkTest(IOpenAIService sdk) ConsoleExtensions.WriteLine("Message Create Test:", ConsoleColor.DarkCyan); var messageResult = await sdk.Beta.Messages.MessageCreate(threadId, new MessageCreateRequest { - Role = StaticValues.AssistatntsStatics.MessageStatics.Roles.User, + Role = StaticValues.AssistantsStatics.MessageStatics.Roles.User, Content = "Where is Zhejiang Jiacheng Supply Chain Co., LTD.", FileIds = new List() { uplaodFileId }, }); @@ -233,9 +233,9 @@ public static async Task RunHowAssistantsWorkTest(IOpenAIService sdk) ConsoleExtensions.WriteLine("waiting for run completed:", ConsoleColor.DarkCyan); var runningStatusList = new List() { - StaticValues.AssistatntsStatics.RunStatus.Queued, - StaticValues.AssistatntsStatics.RunStatus.InProgress, - StaticValues.AssistatntsStatics.RunStatus.RequiresAction, + StaticValues.AssistantsStatics.RunStatus.Queued, + StaticValues.AssistantsStatics.RunStatus.InProgress, + StaticValues.AssistantsStatics.RunStatus.RequiresAction, }; //鑾峰彇浠诲姟淇℃伅 @@ -248,8 +248,8 @@ public static async Task RunHowAssistantsWorkTest(IOpenAIService sdk) * All outputs must be submitted in a single request. */ var requireAction = runRetrieveResult.RequiredAction; - if (runRetrieveResult.Status == StaticValues.AssistatntsStatics.RunStatus.RequiresAction - && requireAction != null && requireAction.Type == StaticValues.AssistatntsStatics.RequiredActionTypes.SubmitToolOutputs) + if (runRetrieveResult.Status == StaticValues.AssistantsStatics.RunStatus.RequiresAction + && requireAction != null && requireAction.Type == StaticValues.AssistantsStatics.RequiredActionTypes.SubmitToolOutputs) { var myFunc = new List() { "get_corp_location" }; var toolOutputs = new List(); @@ -298,8 +298,8 @@ public static async Task RunHowAssistantsWorkTest(IOpenAIService sdk) if (messageListResult.Successful) { var msgRespList = messageListResult.Data; - var ask = msgRespList?.FirstOrDefault(msg => msg.Role == StaticValues.AssistatntsStatics.MessageStatics.Roles.User); - var replys = msgRespList?.Where(msg => msg.CreatedAt > ask?.CreatedAt && msg.Role == StaticValues.AssistatntsStatics.MessageStatics.Roles.Assistant).ToList() ?? new List(); + 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(); ConsoleExtensions.WriteLine(replys.ToJson()); } else diff --git a/OpenAI.Playground/TestHelpers/MessageTestHelper.cs b/OpenAI.Playground/TestHelpers/MessageTestHelper.cs index d4491adb..deb13738 100644 --- a/OpenAI.Playground/TestHelpers/MessageTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/MessageTestHelper.cs @@ -39,7 +39,7 @@ public static async Task RunMessageCreateTest(IOpenAIService sdk) var messageResult = await sdk.Beta.Messages.MessageCreate(threadId, new MessageCreateRequest { - Role = StaticValues.AssistatntsStatics.MessageStatics.Roles.User, + Role = StaticValues.AssistantsStatics.MessageStatics.Roles.User, Content = "How does AI work? Explain it in simple terms.", }); diff --git a/OpenAI.Playground/TestHelpers/RunTestHelper.cs b/OpenAI.Playground/TestHelpers/RunTestHelper.cs index a131b7b6..d3301071 100644 --- a/OpenAI.Playground/TestHelpers/RunTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/RunTestHelper.cs @@ -45,8 +45,8 @@ public static async Task RunRunCreateTest(IOpenAIService sdk) var runId = runResult.Id; ConsoleExtensions.WriteLine($"runId: {runId}"); - var doneStatusList = new List() { StaticValues.AssistatntsStatics.RunStatus.Cancelled, StaticValues.AssistatntsStatics.RunStatus.Completed, StaticValues.AssistatntsStatics.RunStatus.Failed, StaticValues.AssistatntsStatics.RunStatus.Expired }; - var runStatus = StaticValues.AssistatntsStatics.RunStatus.Queued; + var doneStatusList = new List() { StaticValues.AssistantsStatics.RunStatus.Cancelled, StaticValues.AssistantsStatics.RunStatus.Completed, StaticValues.AssistantsStatics.RunStatus.Failed, StaticValues.AssistantsStatics.RunStatus.Expired }; + var runStatus = StaticValues.AssistantsStatics.RunStatus.Queued; do { var runRetrieveResult = await sdk.Beta.Runs.RunRetrieve(threadId, runId); @@ -59,7 +59,7 @@ public static async Task RunRunCreateTest(IOpenAIService sdk) * All outputs must be submitted in a single request. */ var requireAction = runRetrieveResult.RequiredAction; - if (runStatus == StaticValues.AssistatntsStatics.RunStatus.RequiresAction && requireAction.Type == StaticValues.AssistatntsStatics.RequiredActionTypes.SubmitToolOutputs) + if (runStatus == StaticValues.AssistantsStatics.RunStatus.RequiresAction && requireAction.Type == StaticValues.AssistantsStatics.RequiredActionTypes.SubmitToolOutputs) { var toolCalls = requireAction.SubmitToolOutputs.ToolCalls; foreach (var toolCall in toolCalls) diff --git a/OpenAI.SDK/ObjectModels/RequestModels/MessageCreateRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/MessageCreateRequest.cs index 9a0dc862..afa662bf 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/MessageCreateRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/MessageCreateRequest.cs @@ -17,7 +17,7 @@ public class MessageCreateRequest : IOpenAiModels.IFileIds, IOpenAiModels.IMetaD /// [Required] [JsonPropertyName("role")] - public string Role { get; set; } = StaticValues.AssistatntsStatics.MessageStatics.Roles.User; + public string Role { get; set; } = StaticValues.AssistantsStatics.MessageStatics.Roles.User; /// /// The content of the message. diff --git a/OpenAI.SDK/ObjectModels/RequestModels/ToolDefinition.cs b/OpenAI.SDK/ObjectModels/RequestModels/ToolDefinition.cs index f28153d2..36e30641 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/ToolDefinition.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/ToolDefinition.cs @@ -49,10 +49,10 @@ public object? FunctionCalculated public static ToolDefinition DefineCodeInterpreter() => new() { - Type = StaticValues.AssistatntsStatics.ToolCallTypes.CodeInterpreter, + Type = StaticValues.AssistantsStatics.ToolCallTypes.CodeInterpreter, }; public static ToolDefinition DefineRetrieval() => new() { - Type = StaticValues.AssistatntsStatics.ToolCallTypes.Retrieval, + Type = StaticValues.AssistantsStatics.ToolCallTypes.Retrieval, }; } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/StaticValueHelper.cs b/OpenAI.SDK/ObjectModels/StaticValueHelper.cs index 66cc5eaf..c643ca85 100644 --- a/OpenAI.SDK/ObjectModels/StaticValueHelper.cs +++ b/OpenAI.SDK/ObjectModels/StaticValueHelper.cs @@ -114,7 +114,7 @@ public static class ChatMessageRoles } - public static class AssistatntsStatics + public static class AssistantsStatics { public static class ToolCallTypes { From 947a55cdb298a1f8405bb009bff7c41bb3401cee Mon Sep 17 00:00:00 2001 From: Tolga Kayhan Date: Thu, 11 Apr 2024 18:13:21 +0100 Subject: [PATCH 05/26] console color reverted to default --- OpenAI.Playground/ConsoleExtensions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OpenAI.Playground/ConsoleExtensions.cs b/OpenAI.Playground/ConsoleExtensions.cs index 83407ab2..f4212fe3 100644 --- a/OpenAI.Playground/ConsoleExtensions.cs +++ b/OpenAI.Playground/ConsoleExtensions.cs @@ -2,7 +2,7 @@ public static class ConsoleExtensions { - public static void WriteLine(string value, ConsoleColor color = ConsoleColor.Cyan) + public static void WriteLine(string value, ConsoleColor color = ConsoleColor.Gray) { var defaultColor = Console.ForegroundColor; Console.ForegroundColor = color; From d775730b2d767411ca239cd2de7f4a4a476c4766 Mon Sep 17 00:00:00 2001 From: Tolga Kayhan Date: Fri, 12 Apr 2024 17:53:11 +0100 Subject: [PATCH 06/26] jsonl file converted to english --- OpenAI.Playground/SampleData/betterway_corp.jsonl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/OpenAI.Playground/SampleData/betterway_corp.jsonl b/OpenAI.Playground/SampleData/betterway_corp.jsonl index 79ab3294..d93acadf 100644 --- a/OpenAI.Playground/SampleData/betterway_corp.jsonl +++ b/OpenAI.Playground/SampleData/betterway_corp.jsonl @@ -1 +1 @@ -{"messages":[{"role":"system","content":"浣犳槸涓涓彁渚涚墿娴佷緵搴旈摼涓撲笟鍔╂墜"},{"role":"user","content":"娴欐睙浣崇▼渚涘簲閾炬湁闄愬叕鍙稿叿浣撳湪鍝紵"},{"role":"assistant","content":"娴欐睙浣崇▼渚涘簲閾炬湁闄愬叕鍙,浣嶄簬娴欐睙鐪侀噾鍗庡競濠哄煄鍖哄叓涓鍖楄615鍙蜂匠绋嬪浗闄呭晢鍔′腑蹇 "},{"role":"user","content":"璇蜂粙缁嶄笅娴欐睙浣崇▼渚涘簲閾惧叕鍙搞"},{"role":"assistant","content":"娴欐睙浣崇▼渚涘簲閾惧叕鍙告垚绔嬩簬 2011骞,鏄竴瀹朵笓娉ㄤ簬璺ㄥ鐗╂祦鐨勫垱鏂颁緵搴旈摼鏈嶅姟浼佷笟,鏃椾笅瀛愬叕鍙搁亶甯冨叏鍥藉拰娴峰,涓昏娑夊強閲戝崕銆佷箟涔屻佸畞娉€佹矆闃炽佸ぉ娲ャ侀潚宀涖佹祹鍗椼佽嫃宸炪佹垚閮姐佹柊鍔犲潯銆佸痉鍥姐佷縿缃楁柉绛夊湴銆"}]} \ No newline at end of file +{"messages":[{"role":"system","content":"You are a professional assistant providing logistics supply chain services"}, {"role":"user","content":"Where exactly is Zhejiang Jiacheng Supply Chain Co., Ltd. located?"}, {"role":"assistant","content":"Zhejiang Jiacheng Supply Chain Co., Ltd. is located at No. 615, Bayi North Street, Wucheng District, Jinhua City, Zhejiang Province, Jiacheng International Business Center"}, {"role":"user","content":"Please introduce Zhejiang Jiacheng Supply Chain Company."}, {"role":"assistant","content":"Zhejiang Jiacheng Supply Chain Company was founded in 2011 and is an innovative supply chain service enterprise focusing on cross-border logistics. Its subsidiaries are located throughout the country and overseas, mainly involving Jinhua, Yiwu, Ningbo, Shenyang, Tianjin, Qingdao, Jinan, Suzhou, Chengdu, Singapore, Germany, Russia and other places."}]} \ No newline at end of file From d2e4b55c38fc8ad079ed7eb146657609767006bc Mon Sep 17 00:00:00 2001 From: Tolga Kayhan Date: Fri, 12 Apr 2024 19:30:48 +0100 Subject: [PATCH 07/26] Updated Endpoint providers --- .../AzureOpenAiEndpointProvider.cs | 145 +++++++++--------- .../OpenAiEndpointProvider.cs | 24 +-- .../RequestModels/AssistantFileListRequest.cs | 13 +- .../RequestModels/AssistantListRequest.cs | 13 +- .../RequestModels/BaseListRequest.cs | 110 +++++++------ .../RequestModels/MessageFileListRequest.cs | 13 +- .../RequestModels/MessageListRequest.cs | 13 +- .../RequestModels/RunListRequest.cs | 13 +- .../RequestModels/RunStepListRequest.cs | 13 +- 9 files changed, 159 insertions(+), 198 deletions(-) diff --git a/OpenAI.SDK/EndpointProviders/AzureOpenAiEndpointProvider.cs b/OpenAI.SDK/EndpointProviders/AzureOpenAiEndpointProvider.cs index 8efb7296..57b75afe 100644 --- a/OpenAI.SDK/EndpointProviders/AzureOpenAiEndpointProvider.cs +++ b/OpenAI.SDK/EndpointProviders/AzureOpenAiEndpointProvider.cs @@ -1,5 +1,4 @@ using System.Net; -using System.Threading; using OpenAI.ObjectModels.RequestModels; namespace OpenAI.EndpointProviders; @@ -19,32 +18,31 @@ public AzureOpenAiEndpointProvider(string apiVersion, string deploymentId) } private string Prefix => $"{ApiPrefix}/{DeploymentsPrefix}/{WebUtility.UrlEncode(_deploymentId)}"; - private string QueryString => $"?api-version={_apiVersion}"; - + private string AzureVersionQueryString => $"?api-version={_apiVersion}"; public string ModelRetrieve(string model) { - return $"{Prefix}/models/{model}{QueryString}"; + return $"{Prefix}/models/{model}{AzureVersionQueryString}"; } public string FileDelete(string fileId) { - return $"{Prefix}/files/{fileId}{QueryString}"; + return $"{Prefix}/files/{fileId}{AzureVersionQueryString}"; } public string CompletionCreate() { - return $"{Prefix}/completions{QueryString}"; + return $"{Prefix}/completions{AzureVersionQueryString}"; } public string EditCreate() { - return $"{Prefix}/edits{QueryString}"; + return $"{Prefix}/edits{AzureVersionQueryString}"; } public string ModelsList() { - return $"{Prefix}/models{QueryString}"; + return $"{Prefix}/models{AzureVersionQueryString}"; } public string FilesList() @@ -59,47 +57,47 @@ public string FilesUpload() public string FileRetrieve(string fileId) { - return $"{Prefix}/files/{fileId}{QueryString}"; + return $"{Prefix}/files/{fileId}{AzureVersionQueryString}"; } public string FileRetrieveContent(string fileId) { - return $"{Prefix}/files/{fileId}/content{QueryString}"; + return $"{Prefix}/files/{fileId}/content{AzureVersionQueryString}"; } public string FineTuneCreate() { - return $"{Prefix}/fine-tunes{QueryString}"; + return $"{Prefix}/fine-tunes{AzureVersionQueryString}"; } public string FineTuneList() { - return $"{Prefix}/fine-tunes{QueryString}"; + return $"{Prefix}/fine-tunes{AzureVersionQueryString}"; } public string FineTuneRetrieve(string fineTuneId) { - return $"{Prefix}/fine-tunes/{fineTuneId}{QueryString}"; + return $"{Prefix}/fine-tunes/{fineTuneId}{AzureVersionQueryString}"; } public string FineTuneCancel(string fineTuneId) { - return $"{Prefix}/fine-tunes/{fineTuneId}/cancel{QueryString}"; + return $"{Prefix}/fine-tunes/{fineTuneId}/cancel{AzureVersionQueryString}"; } public string FineTuneListEvents(string fineTuneId) { - return $"{Prefix}/fine-tunes/{fineTuneId}/events{QueryString}"; + return $"{Prefix}/fine-tunes/{fineTuneId}/events{AzureVersionQueryString}"; } public string FineTuneDelete(string fineTuneId) { - return $"{Prefix}/models/{fineTuneId}{QueryString}"; + return $"{Prefix}/models/{fineTuneId}{AzureVersionQueryString}"; } public string FineTuningJobCreate() { - return $"{Prefix}/fine_tuning/jobs{QueryString}"; + return $"{Prefix}/fine_tuning/jobs{AzureVersionQueryString}"; } public string FineTuningJobList(FineTuningJobListRequest? fineTuningJobListRequest) @@ -112,267 +110,274 @@ public string FineTuningJobList(FineTuningJobListRequest? fineTuningJobListReque queryParams.Add($"after={WebUtility.UrlEncode(fineTuningJobListRequest.After)}"); if (fineTuningJobListRequest.Limit.HasValue) queryParams.Add($"limit={fineTuningJobListRequest.Limit.Value}"); - + if (queryParams.Any()) - url = $"{url}{QueryString}&{string.Join("&", queryParams)}"; + url = $"{url}{AzureVersionQueryString}&{string.Join("&", queryParams)}"; } - return url; - } - public string FineTuningJobList() - { - return $"{Prefix}/fine_tuning/jobs{QueryString}"; + return url; } public string FineTuningJobRetrieve(string fineTuningJobId) { - return $"{Prefix}/fine_tuning/jobs/{fineTuningJobId}{QueryString}"; + return $"{Prefix}/fine_tuning/jobs/{fineTuningJobId}{AzureVersionQueryString}"; } public string FineTuningJobCancel(string fineTuningJobId) { - return $"{Prefix}/fine_tuning/jobs/{fineTuningJobId}/cancel{QueryString}"; + return $"{Prefix}/fine_tuning/jobs/{fineTuningJobId}/cancel{AzureVersionQueryString}"; } public string FineTuningJobListEvents(string fineTuningJobId) { - return $"{Prefix}/fine_tuning/jobs/{fineTuningJobId}/events{QueryString}"; + return $"{Prefix}/fine_tuning/jobs/{fineTuningJobId}/events{AzureVersionQueryString}"; } public string ModelsDelete(string modelId) { - return $"{Prefix}/models/{modelId}{QueryString}"; + return $"{Prefix}/models/{modelId}{AzureVersionQueryString}"; } public string EmbeddingCreate() { - return $"{Prefix}/embeddings{QueryString}"; + return $"{Prefix}/embeddings{AzureVersionQueryString}"; } public string ModerationCreate() { - return $"{Prefix}/moderations{QueryString}"; + return $"{Prefix}/moderations{AzureVersionQueryString}"; } public string ImageCreate() { - return $"{Prefix}/images/generations{QueryString}"; + return $"{Prefix}/images/generations{AzureVersionQueryString}"; } public string ImageEditCreate() { - return $"{Prefix}/images/edits{QueryString}"; + return $"{Prefix}/images/edits{AzureVersionQueryString}"; } public string ImageVariationCreate() { - return $"{Prefix}/images/variations{QueryString}"; + return $"{Prefix}/images/variations{AzureVersionQueryString}"; } public string ChatCompletionCreate() { - return $"{Prefix}/chat/completions{QueryString}"; + return $"{Prefix}/chat/completions{AzureVersionQueryString}"; } public string AudioCreateTranscription() { - return $"{Prefix}/audio/transcriptions{QueryString}"; + return $"{Prefix}/audio/transcriptions{AzureVersionQueryString}"; } public string AudioCreateTranslation() { - return $"{Prefix}/audio/translation{QueryString}"; + return $"{Prefix}/audio/translation{AzureVersionQueryString}"; } public string AudioCreateSpeech() { - return $"{Prefix}/audio/speech{QueryString}"; - } - - private string Files() - { - return $"{Prefix}/files{QueryString}"; + return $"{Prefix}/audio/speech{AzureVersionQueryString}"; } public string AssistantCreate() { - return $"{Prefix}/assistants{QueryString}"; + return $"{Prefix}/assistants{AzureVersionQueryString}"; } public string AssistantRetrieve(string assistantId) { - return $"{Prefix}/assistants/{assistantId}{QueryString}"; + return $"{Prefix}/assistants/{assistantId}{AzureVersionQueryString}"; } public string AssistantModify(string assistantId) { - return $"{Prefix}/assistants/{assistantId}{QueryString}"; + return $"{Prefix}/assistants/{assistantId}{AzureVersionQueryString}"; } public string AssistantDelete(string assistantId) { - return $"{Prefix}/assistants/{assistantId}{QueryString}"; + return $"{Prefix}/assistants/{assistantId}{AzureVersionQueryString}"; } public string AssistantList(AssistantListRequest? assistantListRequest) { - var url = $"{Prefix}/assistants{QueryString}"; + var url = $"{Prefix}/assistants{AzureVersionQueryString}"; var query = assistantListRequest?.GetQueryParameters(); if (!string.IsNullOrWhiteSpace(query)) { url = $"{url}{query}"; } + return url; } public string AssistantFileCreate(string assistantId) { - return $"{Prefix}/assistants/{assistantId}/files{QueryString}"; + return $"{Prefix}/assistants/{assistantId}/files{AzureVersionQueryString}"; } public string AssistantFileRetrieve(string assistantId, string fileId) { - return $"{Prefix}/assistants/{assistantId}/files/{fileId}{QueryString}"; + return $"{Prefix}/assistants/{assistantId}/files/{fileId}{AzureVersionQueryString}"; } public string AssistantFileDelete(string assistantId, string fileId) { - return $"{Prefix}/assistants/{assistantId}/files/{fileId}{QueryString}"; + return $"{Prefix}/assistants/{assistantId}/files/{fileId}{AzureVersionQueryString}"; } public string AssistantFileList(string assistantId, AssistantFileListRequest? assistantFileListRequest) { - var url = $"{Prefix}/assistants/files{QueryString}"; + var url = $"{Prefix}/assistants/files{AzureVersionQueryString}"; var query = assistantFileListRequest?.GetQueryParameters(); if (!string.IsNullOrWhiteSpace(query)) { url = $"{url}{query}"; } + return url; } public string ThreadCreate() { - return $"{Prefix}/threads{QueryString}"; + return $"{Prefix}/threads{AzureVersionQueryString}"; } public string ThreadRetrieve(string threadId) { - return $"{Prefix}/threads/{threadId}{QueryString}"; + return $"{Prefix}/threads/{threadId}{AzureVersionQueryString}"; } public string ThreadModify(string threadId) { - return $"{Prefix}/threads/{threadId}{QueryString}"; + return $"{Prefix}/threads/{threadId}{AzureVersionQueryString}"; } public string ThreadDelete(string threadId) { - return $"{Prefix}/threads/{threadId}{QueryString}"; + return $"{Prefix}/threads/{threadId}{AzureVersionQueryString}"; } public string MessageCreate(string threadId) { - return $"{Prefix}/threads/{threadId}/messages{QueryString}"; + return $"{Prefix}/threads/{threadId}/messages{AzureVersionQueryString}"; } public string MessageRetrieve(string threadId, string messageId) { - return $"{Prefix}/threads/{threadId}/messages/{messageId}{QueryString}"; + return $"{Prefix}/threads/{threadId}/messages/{messageId}{AzureVersionQueryString}"; } public string MessageModify(string threadId, string messageId) { - return $"{Prefix}/threads/{threadId}/messages/{messageId}{QueryString}"; + return $"{Prefix}/threads/{threadId}/messages/{messageId}{AzureVersionQueryString}"; } public string MessageList(string threadId, MessageListRequest? messageListRequest) { - var url = $"{Prefix}/threads/{threadId}/messages{QueryString}"; + var url = $"{Prefix}/threads/{threadId}/messages{AzureVersionQueryString}"; var query = messageListRequest?.GetQueryParameters(); if (!string.IsNullOrWhiteSpace(query)) { url = $"{url}{query}"; } + return url; } public string MessageFileRetrieve(string threadId, string messageId, string fileId) { - return $"{Prefix}/threads/{threadId}/messages/{messageId}/files/{fileId}{QueryString}"; + return $"{Prefix}/threads/{threadId}/messages/{messageId}/files/{fileId}{AzureVersionQueryString}"; } public string MessageFileList(string threadId, string messageId, MessageFileListRequest? messageFileListRequest) { - var url = $"{Prefix}/threads/{threadId}/messages/{messageId}/files{QueryString}"; + var url = $"{Prefix}/threads/{threadId}/messages/{messageId}/files{AzureVersionQueryString}"; var query = messageFileListRequest?.GetQueryParameters(); if (!string.IsNullOrWhiteSpace(query)) { url = $"{url}{query}"; } + return url; } public string RunCreate(string threadId) { - return $"{Prefix}/threads/{threadId}/runs{QueryString}"; + return $"{Prefix}/threads/{threadId}/runs{AzureVersionQueryString}"; } public string RunRetrieve(string threadId, string runId) { - return $"{Prefix}/threads/{threadId}/runs/{runId}{QueryString}"; + return $"{Prefix}/threads/{threadId}/runs/{runId}{AzureVersionQueryString}"; } public string RunModify(string threadId, string runId) { - return $"{Prefix}/threads/{threadId}/runs/{runId}{QueryString}"; + return $"{Prefix}/threads/{threadId}/runs/{runId}{AzureVersionQueryString}"; } public string RunList(string threadId, RunListRequest? runListRequest) { - var url = $"{Prefix}/threads/{threadId}/runs{QueryString}"; + var url = $"{Prefix}/threads/{threadId}/runs{AzureVersionQueryString}"; var query = runListRequest?.GetQueryParameters(); if (!string.IsNullOrWhiteSpace(query)) { url = $"{url}{query}"; } + return url; } public string RunSubmitToolOutputs(string threadId, string runId) { - return $"{Prefix}/threads/{threadId}/runs/{runId}/submit_tool_outputs{QueryString}"; + return $"{Prefix}/threads/{threadId}/runs/{runId}/submit_tool_outputs{AzureVersionQueryString}"; } public string RunCancel(string threadId, string runId) { - return $"{Prefix}/threads/{threadId}/runs/{runId}/cancel{QueryString}"; + return $"{Prefix}/threads/{threadId}/runs/{runId}/cancel{AzureVersionQueryString}"; } public string ThreadAndRunCreate() { - return $"{Prefix}/threads/runs{QueryString}"; + return $"{Prefix}/threads/runs{AzureVersionQueryString}"; } public string RunStepRetrieve(string threadId, string runId, string stepId) { - return $"{Prefix}/threads/{threadId}/runs/{runId}/steps/{stepId}{QueryString}"; + return $"{Prefix}/threads/{threadId}/runs/{runId}/steps/{stepId}{AzureVersionQueryString}"; } public string RunStepList(string threadId, string runId, RunStepListRequest? runStepListRequest) { - var url = $"{Prefix}/threads/{threadId}/runs/{runId}/steps{QueryString}"; + var url = $"{Prefix}/threads/{threadId}/runs/{runId}/steps{AzureVersionQueryString}"; var query = runStepListRequest?.GetQueryParameters(); if (!string.IsNullOrWhiteSpace(query)) { url = $"{url}{query}"; } + return url; } + + 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/OpenAiEndpointProvider.cs b/OpenAI.SDK/EndpointProviders/OpenAiEndpointProvider.cs index ad8149ca..936c4745 100644 --- a/OpenAI.SDK/EndpointProviders/OpenAiEndpointProvider.cs +++ b/OpenAI.SDK/EndpointProviders/OpenAiEndpointProvider.cs @@ -1,6 +1,4 @@ -锘縰sing System; -using System.Net; -using System.Text; +锘縰sing System.Net; using OpenAI.ObjectModels.RequestModels; namespace OpenAI.EndpointProviders; @@ -61,12 +59,12 @@ public string ModelsList() public string FilesList() { - return Files(); + return $"{_apiVersion}/files"; } public string FilesUpload() { - return Files(); + return $"{_apiVersion}/files"; } public string FileRetrieve(string fileId) @@ -128,6 +126,7 @@ public string FineTuningJobList(FineTuningJobListRequest? fineTuningJobListReque if (queryParams.Any()) url = $"{url}?{string.Join("&", queryParams)}"; } + return url; } @@ -176,11 +175,6 @@ public string ImageVariationCreate() return $"{_apiVersion}/images/variations"; } - private string Files() - { - return $"{_apiVersion}/files"; - } - public string AssistantCreate() { return $"{_apiVersion}/assistants"; @@ -210,6 +204,7 @@ public string AssistantList(AssistantListRequest? assistantListRequest) { url = $"{url}?{query}"; } + return url; } @@ -237,6 +232,7 @@ public string AssistantFileList(string assistantId, AssistantFileListRequest? as { url = $"{url}?{query}"; } + return url; } @@ -284,6 +280,7 @@ public string MessageList(string threadId, MessageListRequest? messageListReques { url = $"{url}?{query}"; } + return url; } @@ -301,6 +298,7 @@ public string MessageFileList(string threadId, string messageId, MessageFileList { url = $"{url}?{query}"; } + return url; } @@ -321,13 +319,14 @@ public string RunModify(string threadId, string runId) public string RunList(string threadId, RunListRequest? runListRequest) { - var url= $"{_apiVersion}/threads/{threadId}/runs"; + var url = $"{_apiVersion}/threads/{threadId}/runs"; var query = runListRequest?.GetQueryParameters(); if (!string.IsNullOrWhiteSpace(query)) { url = $"{url}?{query}"; } + return url; } @@ -353,13 +352,14 @@ public string RunStepRetrieve(string threadId, string runId, string stepId) public string RunStepList(string threadId, string runId, RunStepListRequest? runStepListRequest) { - var url= $"{_apiVersion}/threads/{threadId}/runs/{runId}/steps"; + var url = $"{_apiVersion}/threads/{threadId}/runs/{runId}/steps"; var query = runStepListRequest?.GetQueryParameters(); if (!string.IsNullOrWhiteSpace(query)) { url = $"{url}?{query}"; } + return url; } } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/RequestModels/AssistantFileListRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/AssistantFileListRequest.cs index a966538c..2c9601a4 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/AssistantFileListRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/AssistantFileListRequest.cs @@ -1,12 +1,5 @@ -锘縰sing System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +锘縩amespace OpenAI.ObjectModels.RequestModels; -namespace OpenAI.ObjectModels.RequestModels +public class AssistantFileListRequest : BaseListRequest { - public class AssistantFileListRequest :BaseListRequest - { - } -} +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/RequestModels/AssistantListRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/AssistantListRequest.cs index eeee89f4..92197071 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/AssistantListRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/AssistantListRequest.cs @@ -1,12 +1,5 @@ -锘縰sing System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +锘縩amespace OpenAI.ObjectModels.RequestModels; -namespace OpenAI.ObjectModels.RequestModels +public class AssistantListRequest : BaseListRequest { - public class AssistantListRequest : BaseListRequest - { - } -} +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/RequestModels/BaseListRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/BaseListRequest.cs index 185e91fe..1307dfd6 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/BaseListRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/BaseListRequest.cs @@ -1,68 +1,66 @@ -锘縰sing System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Text; +锘縰sing System.Net; using System.Text.Json.Serialization; -using System.Threading.Tasks; -namespace OpenAI.ObjectModels.RequestModels +namespace OpenAI.ObjectModels.RequestModels; + +public class BaseListRequest { - public class BaseListRequest - { - /// - /// A limit on the number of objects to be returned. - /// Limit can range between 1 and 100, and the default is 20. - /// - [JsonPropertyName("limit")] - public int? Limit { get; set; } + /// + /// A limit on the number of objects to be returned. + /// Limit can range between 1 and 100, and the default is 20. + /// + [JsonPropertyName("limit")] + public int? Limit { get; set; } - /// - /// Sort order by the created_at timestamp of the objects. - /// "asc" for ascending order and "desc" for descending order. - /// - [JsonPropertyName("order")] - public string? Order { get; set; } + /// + /// Sort order by the created_at timestamp of the objects. + /// "asc" for ascending order and "desc" for descending order. + /// + [JsonPropertyName("order")] + public string? Order { get; set; } - /// - /// A cursor for use in pagination. after is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with obj_foo, - /// your subsequent call can include after=obj_foo in order to fetch the next page of the list. - /// - [JsonPropertyName("after")] - public string? After { get; set; } + /// + /// A cursor for use in pagination. after is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with obj_foo, + /// your subsequent call can include after=obj_foo in order to fetch the next page of the list. + /// + [JsonPropertyName("after")] + public string? After { get; set; } - /// - /// A cursor for use in pagination. before is an object ID that defines your place in the list. - /// For instance, if you make a list request and receive 100 objects, ending with obj_foo, your - /// subsequent call can include before=obj_foo in order to fetch the previous page of the list. - /// - [JsonPropertyName("before")] - public string? Before { get; set; } - public string? GetQueryParameters() + /// + /// A cursor for use in pagination. before is an object ID that defines your place in the list. + /// For instance, if you make a list request and receive 100 objects, ending with obj_foo, your + /// subsequent call can include before=obj_foo in order to fetch the previous page of the list. + /// + [JsonPropertyName("before")] + public string? Before { get; set; } + + public string? GetQueryParameters() + { + var build = new List(); + if (Limit != null) { - var build = new List(); - if (Limit != null) - { - build.Add($"limit={Limit}"); - } - if (Order != null) - { - build.Add($"order={WebUtility.UrlEncode(Order)}"); - } - if (After != null) - { - build.Add($"after={WebUtility.UrlEncode(After)}"); - } - if (Before != null) - { - build.Add($"before={WebUtility.UrlEncode(Before)}"); - } + build.Add($"limit={Limit}"); + } - if (build.Count <= 0) return null; + if (Order != null) + { + build.Add($"order={WebUtility.UrlEncode(Order)}"); + } - return string.Join("&", build); + if (After != null) + { + build.Add($"after={WebUtility.UrlEncode(After)}"); + } + + if (Before != null) + { + build.Add($"before={WebUtility.UrlEncode(Before)}"); } + + if (build.Count <= 0) return null; + + return string.Join("&", build); } -} +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/RequestModels/MessageFileListRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/MessageFileListRequest.cs index 920b8de8..98b26af9 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/MessageFileListRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/MessageFileListRequest.cs @@ -1,12 +1,5 @@ -锘縰sing System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +锘縩amespace OpenAI.ObjectModels.RequestModels; -namespace OpenAI.ObjectModels.RequestModels +public class MessageFileListRequest : BaseListRequest { - public class MessageFileListRequest : BaseListRequest - { - } -} +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/RequestModels/MessageListRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/MessageListRequest.cs index 5a19d31a..a2ef4b36 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/MessageListRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/MessageListRequest.cs @@ -1,12 +1,5 @@ -锘縰sing System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +锘縩amespace OpenAI.ObjectModels.RequestModels; -namespace OpenAI.ObjectModels.RequestModels +public class MessageListRequest : BaseListRequest { - public class MessageListRequest : BaseListRequest - { - } -} +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/RequestModels/RunListRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/RunListRequest.cs index 876dcfe3..f81db89c 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/RunListRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/RunListRequest.cs @@ -1,12 +1,5 @@ -锘縰sing System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +锘縩amespace OpenAI.ObjectModels.RequestModels; -namespace OpenAI.ObjectModels.RequestModels +public class RunListRequest : BaseListRequest { - public class RunListRequest : BaseListRequest - { - } -} +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/RequestModels/RunStepListRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/RunStepListRequest.cs index 8b6de04c..f4c690c6 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/RunStepListRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/RunStepListRequest.cs @@ -1,12 +1,5 @@ -锘縰sing System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +锘縩amespace OpenAI.ObjectModels.RequestModels; -namespace OpenAI.ObjectModels.RequestModels +public class RunStepListRequest : BaseListRequest { - public class RunStepListRequest : BaseListRequest - { - } -} +} \ No newline at end of file From 52e1c6144aece739d39cc54d196624c0245e4472 Mon Sep 17 00:00:00 2001 From: Tolga Kayhan Date: Sun, 14 Apr 2024 22:44:22 +0100 Subject: [PATCH 08/26] Code cleanup and some fixes. --- OpenAI.SDK/Interfaces/IAssistantService.cs | 152 +++++++++-------- OpenAI.SDK/Interfaces/IBetaService.cs | 21 +-- OpenAI.SDK/Interfaces/IMessageService.cs | 47 +++--- OpenAI.SDK/Interfaces/IRunService.cs | 90 +++++----- OpenAI.SDK/Interfaces/IThreadService.cs | 57 +++---- OpenAI.SDK/Managers/OpenAIAssistantService.cs | 134 ++++++++------- OpenAI.SDK/Managers/OpenAIBetaService.cs | 28 ++-- OpenAI.SDK/Managers/OpenAIMessageService.cs | 66 ++++---- OpenAI.SDK/Managers/OpenAIRunService.cs | 140 +++++++++------- OpenAI.SDK/Managers/OpenAIService.cs | 10 +- OpenAI.SDK/Managers/OpenAIThreadService.cs | 83 +++++----- .../RequestModels/AssistantCreateRequest.cs | 104 ++++++------ .../RequestModels/MessageCreateRequest.cs | 73 ++++----- .../RequestModels/RunCreateRequest.cs | 154 ++++++++++++------ .../SubmitToolOutputsToRunRequest.cs | 59 +++---- .../RequestModels/ThreadCreateRequest.cs | 42 ++--- .../SharedModels/TruncationStrategy.cs | 22 +++ OpenAI.SDK/OpenAiOptions.cs | 2 + 18 files changed, 662 insertions(+), 622 deletions(-) create mode 100644 OpenAI.SDK/ObjectModels/SharedModels/TruncationStrategy.cs diff --git a/OpenAI.SDK/Interfaces/IAssistantService.cs b/OpenAI.SDK/Interfaces/IAssistantService.cs index 2af28d5b..4b88d19a 100644 --- a/OpenAI.SDK/Interfaces/IAssistantService.cs +++ b/OpenAI.SDK/Interfaces/IAssistantService.cs @@ -1,92 +1,86 @@ 锘縰sing OpenAI.ObjectModels.RequestModels; using OpenAI.ObjectModels.ResponseModels; using OpenAI.ObjectModels.SharedModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace OpenAI.Interfaces +namespace OpenAI.Interfaces; + +public interface IAssistantService { - public interface IAssistantService - { - /// - /// Create an assistant with a model and instructions. - /// - /// - /// - /// - /// - Task AssistantCreate(AssistantCreateRequest request, string? modelId = null, CancellationToken cancellationToken = default); + /// + /// Create an assistant with a model and instructions. + /// + /// + /// + /// + /// + Task AssistantCreate(AssistantCreateRequest request, string? modelId = null, CancellationToken cancellationToken = default); - /// - /// Create an assistant file by attaching a File to an assistant. - /// - /// - /// - /// - /// - Task AssistantFileCreate(string assistantId, AssistantFileCreateRequest request, CancellationToken cancellationToken = default); + /// + /// Create an assistant file by attaching a File to an assistant. + /// + /// + /// + /// + /// + Task AssistantFileCreate(string assistantId, AssistantFileCreateRequest request, CancellationToken cancellationToken = default); - /// - /// Returns a list of assistants. - /// - /// - /// - /// - Task AssistantList(AssistantListRequest? request = null, CancellationToken cancellationToken = default); + /// + /// Returns a list of assistants. + /// + /// + /// + /// + Task AssistantList(AssistantListRequest? request = null, CancellationToken cancellationToken = default); - /// - /// Returns a list of assistant files. - /// - /// - /// - /// - /// - Task AssistantFileList(string assistantId, AssistantFileListRequest? request = null, CancellationToken cancellationToken = default); + /// + /// Returns a list of assistant files. + /// + /// + /// + /// + /// + Task AssistantFileList(string assistantId, AssistantFileListRequest? request = null, CancellationToken cancellationToken = default); - /// - /// Retrieves an assistant. - /// - /// - /// - /// - Task AssistantRetrieve(string assistantId, CancellationToken cancellationToken = default); + /// + /// Retrieves an assistant. + /// + /// + /// + /// + Task AssistantRetrieve(string assistantId, CancellationToken cancellationToken = default); - /// - /// Retrieves an AssistantFile. - /// - /// - /// - /// - /// - Task AssistantFileRetrieve(string assistantId, string fileId, CancellationToken cancellationToken = default); + /// + /// Retrieves an AssistantFile. + /// + /// + /// + /// + /// + Task AssistantFileRetrieve(string assistantId, string fileId, CancellationToken cancellationToken = default); - /// - /// Modifies an assistant. - /// - /// - /// - /// - /// - Task AssistantModify(string assistantId, AssistantModifyRequest request, CancellationToken cancellationToken = default); + /// + /// Modifies an assistant. + /// + /// + /// + /// + /// + Task AssistantModify(string assistantId, AssistantModifyRequest request, CancellationToken cancellationToken = default); - /// - /// Delete an assistant. - /// - /// - /// - /// - Task AssistantDelete(string assistantId, CancellationToken cancellationToken = default); + /// + /// Delete an assistant. + /// + /// + /// + /// + Task AssistantDelete(string assistantId, CancellationToken cancellationToken = default); - /// - /// Delete an assistant file. - /// - /// - /// - /// - /// - Task AssistantFileDelete(string assistantId, string fileId, CancellationToken cancellationToken = default); - } -} + /// + /// Delete an assistant file. + /// + /// + /// + /// + /// + Task AssistantFileDelete(string assistantId, string fileId, CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/OpenAI.SDK/Interfaces/IBetaService.cs b/OpenAI.SDK/Interfaces/IBetaService.cs index b8252fb9..3972503c 100644 --- a/OpenAI.SDK/Interfaces/IBetaService.cs +++ b/OpenAI.SDK/Interfaces/IBetaService.cs @@ -1,19 +1,12 @@ -锘縰sing System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +锘縩amespace OpenAI.Interfaces; -namespace OpenAI.Interfaces +public interface IBetaService { - public interface IBetaService - { - public IAssistantService Assistants { get; } + public IAssistantService Assistants { get; } - public IMessageService Messages { get; } + public IMessageService Messages { get; } - public IThreadService Threads { get; } + public IThreadService Threads { get; } - public IRunService Runs { get; } - } -} + public IRunService Runs { get; } +} \ No newline at end of file diff --git a/OpenAI.SDK/Interfaces/IMessageService.cs b/OpenAI.SDK/Interfaces/IMessageService.cs index 5c40761f..d9335c93 100644 --- a/OpenAI.SDK/Interfaces/IMessageService.cs +++ b/OpenAI.SDK/Interfaces/IMessageService.cs @@ -1,33 +1,26 @@ 锘縰sing OpenAI.ObjectModels.RequestModels; using OpenAI.ObjectModels.ResponseModels; using OpenAI.ObjectModels.SharedModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace OpenAI.Interfaces +namespace OpenAI.Interfaces; + +public interface IMessageService { - public interface IMessageService - { - /// - /// Create a message. - /// - /// - /// - /// - /// - /// - Task MessageCreate(string threadId, MessageCreateRequest request, string? modelId = null, CancellationToken cancellationToken = default); + /// + /// Create a message. + /// + /// + /// + /// + /// + Task MessageCreate(string threadId, MessageCreateRequest request, CancellationToken cancellationToken = default); - /// - /// Returns a list of messages for a given thread. - /// - /// - /// - /// - /// - Task MessageList(string threadId, MessageListRequest? request = null, CancellationToken cancellationToken = default); - } -} + /// + /// Returns a list of messages for a given thread. + /// + /// + /// + /// + /// + Task MessageList(string threadId, MessageListRequest? request = null, CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/OpenAI.SDK/Interfaces/IRunService.cs b/OpenAI.SDK/Interfaces/IRunService.cs index 8ec525f9..221deed8 100644 --- a/OpenAI.SDK/Interfaces/IRunService.cs +++ b/OpenAI.SDK/Interfaces/IRunService.cs @@ -1,54 +1,50 @@ 锘縰sing OpenAI.ObjectModels.RequestModels; using OpenAI.ObjectModels.SharedModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace OpenAI.Interfaces +namespace OpenAI.Interfaces; + +public interface IRunService { - public interface IRunService - { - /// - /// Create a run. - /// - /// - /// - /// - /// - /// - Task RunCreate(string threadId, RunCreateRequest request, string? modelId = null, CancellationToken cancellationToken = default); + /// + /// Create a run. + /// + /// + /// + /// + /// + /// + Task RunCreate(string threadId, RunCreateRequest request, string? modelId = null, CancellationToken cancellationToken = default); - /// - /// Retrieves a run. - /// - /// - /// - /// - /// - Task RunRetrieve(string threadId, string runId, CancellationToken cancellationToken = default); + /// + /// Retrieves a run. + /// + /// + /// + /// + /// + Task RunRetrieve(string threadId, string runId, CancellationToken cancellationToken = default); - /// - /// Cancels a run that is in_progress. - /// - /// - /// - /// - /// - Task RunCancel(string threadId, string runId, CancellationToken cancellationToken = default); + /// + /// Cancels a run that is in_progress. + /// + /// + /// + /// + /// + Task RunCancel(string threadId, string runId, CancellationToken cancellationToken = default); - /// - /// 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. - /// All outputs must be submitted in a single request. - /// - /// - /// - /// - /// - /// - Task RunSubmitToolOutputs(string threadId, string runId, SubmitToolOutputsToRunRequest request, CancellationToken cancellationToken = default); - } -} + /// + /// 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. + /// All outputs must be submitted in a single request. + /// + /// + /// + /// + /// + /// + /// + Task RunSubmitToolOutputs(string threadId, string runId, SubmitToolOutputsToRunRequest request, CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/OpenAI.SDK/Interfaces/IThreadService.cs b/OpenAI.SDK/Interfaces/IThreadService.cs index 5d40c018..f489ac33 100644 --- a/OpenAI.SDK/Interfaces/IThreadService.cs +++ b/OpenAI.SDK/Interfaces/IThreadService.cs @@ -1,38 +1,31 @@ 锘縰sing OpenAI.ObjectModels.RequestModels; using OpenAI.ObjectModels.SharedModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace OpenAI.Interfaces +namespace OpenAI.Interfaces; + +public interface IThreadService { - public interface IThreadService - { - /// - /// Create a thread. - /// - /// - /// - /// - /// - Task ThreadCreate(ThreadCreateRequest? request = null, string? modelId = null, CancellationToken cancellationToken = default); + /// + /// Create a thread. + /// + /// + /// + /// + Task ThreadCreate(ThreadCreateRequest? request = null, CancellationToken cancellationToken = default); - /// - /// Retrieves a thread. - /// - /// - /// - /// - Task ThreadRetrieve(string threadId, CancellationToken cancellationToken = default); + /// + /// Retrieves a thread. + /// + /// + /// + /// + Task ThreadRetrieve(string threadId, CancellationToken cancellationToken = default); - /// - /// Delete a thread. - /// - /// - /// - /// - Task ThreadDelete(string threadId, CancellationToken cancellationToken = default); - } -} + /// + /// Delete a thread. + /// + /// + /// + /// + Task ThreadDelete(string threadId, CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/OpenAI.SDK/Managers/OpenAIAssistantService.cs b/OpenAI.SDK/Managers/OpenAIAssistantService.cs index 876e4bf2..f9145185 100644 --- a/OpenAI.SDK/Managers/OpenAIAssistantService.cs +++ b/OpenAI.SDK/Managers/OpenAIAssistantService.cs @@ -3,93 +3,103 @@ using OpenAI.ObjectModels.RequestModels; using OpenAI.ObjectModels.ResponseModels; using OpenAI.ObjectModels.SharedModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace OpenAI.Managers + +namespace OpenAI.Managers; + +public partial class OpenAIService : IAssistantService { - public partial class OpenAIService : IAssistantService + /// + public async Task AssistantCreate(AssistantCreateRequest request, string? modelId = null, CancellationToken cancellationToken = default) { - /// - public async Task AssistantCreate(AssistantCreateRequest request, string? modelId = null, CancellationToken cancellationToken = default) - { - request.ProcessModelId(modelId, _defaultModelId); - return await _httpClient.PostAndReadAsAsync(_endpointProvider.AssistantCreate(), request, cancellationToken); - } + request.ProcessModelId(modelId, _defaultModelId); + return await _httpClient.PostAndReadAsAsync(_endpointProvider.AssistantCreate(), request, cancellationToken); + } + + /// + public async Task AssistantFileCreate(string assistantId, AssistantFileCreateRequest request, CancellationToken cancellationToken = default) + { + return await _httpClient.PostAndReadAsAsync(_endpointProvider.AssistantFileCreate(assistantId), request, cancellationToken); + } + + /// + public async Task AssistantList(AssistantListRequest? request = null, CancellationToken cancellationToken = default) + { + return await _httpClient.GetReadAsAsync(_endpointProvider.AssistantList(request), cancellationToken); + } - /// - public async Task AssistantFileCreate(string assistantId, AssistantFileCreateRequest request, CancellationToken cancellationToken = default) + /// + public async Task AssistantFileList(string assistantId, AssistantFileListRequest? request = null, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(assistantId)) { - return await _httpClient.PostAndReadAsAsync(_endpointProvider.AssistantFileCreate(assistantId), request, cancellationToken); + throw new ArgumentNullException(nameof(assistantId)); } - /// - public async Task AssistantList(AssistantListRequest? request = null, CancellationToken cancellationToken = default) + return await _httpClient.GetReadAsAsync(_endpointProvider.AssistantFileList(assistantId, request), cancellationToken); + } + + /// + public async Task AssistantRetrieve(string assistantId, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(assistantId)) { - return await _httpClient.GetReadAsAsync(_endpointProvider.AssistantList(request), cancellationToken); + throw new ArgumentNullException(nameof(assistantId)); } - /// - public async Task AssistantFileList(string assistantId, AssistantFileListRequest? request = null, CancellationToken cancellationToken = default) - { - if (string.IsNullOrWhiteSpace(assistantId)) { throw new ArgumentNullException(nameof(assistantId)); } + return await _httpClient.GetReadAsAsync(_endpointProvider.AssistantRetrieve(assistantId), cancellationToken); + } - return await _httpClient.GetReadAsAsync(_endpointProvider.AssistantFileList(assistantId, request), cancellationToken); + /// + public async Task AssistantFileRetrieve(string assistantId, string fileId, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(assistantId)) + { + throw new ArgumentNullException(nameof(assistantId)); } - /// - public async Task AssistantRetrieve(string assistantId, CancellationToken cancellationToken = default) + if (string.IsNullOrWhiteSpace(fileId)) { - if (string.IsNullOrWhiteSpace(assistantId)) { throw new ArgumentNullException(nameof(assistantId)); } - - return await _httpClient.GetReadAsAsync(_endpointProvider.AssistantRetrieve(assistantId), cancellationToken); + throw new ArgumentNullException(nameof(fileId)); } - /// - public async Task AssistantFileRetrieve(string assistantId, string fileId, CancellationToken cancellationToken = default) - { - if (string.IsNullOrWhiteSpace(assistantId)) { throw new ArgumentNullException(nameof(assistantId)); } - if (string.IsNullOrWhiteSpace(fileId)) { throw new ArgumentNullException(nameof(fileId)); } + return await _httpClient.GetReadAsAsync(_endpointProvider.AssistantFileRetrieve(assistantId, fileId), cancellationToken); + } - return await _httpClient.GetReadAsAsync(_endpointProvider.AssistantFileRetrieve(assistantId, fileId), cancellationToken); + /// + public async Task AssistantModify(string assistantId, AssistantModifyRequest request, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(assistantId)) + { + throw new ArgumentNullException(nameof(assistantId)); } - /// - public async Task AssistantModify(string assistantId, AssistantModifyRequest request, CancellationToken cancellationToken = default) - { - if (string.IsNullOrWhiteSpace(assistantId)) { throw new ArgumentNullException(nameof(assistantId)); } + return await _httpClient.PostAndReadAsAsync(_endpointProvider.AssistantModify(assistantId), request, cancellationToken); + } - return await _httpClient.PostAndReadAsAsync(_endpointProvider.AssistantModify(assistantId), request, cancellationToken); + /// + public async Task AssistantDelete(string assistantId, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(assistantId)) + { + throw new ArgumentNullException(nameof(assistantId)); } - /// - public async Task AssistantDelete(string assistantId, CancellationToken cancellationToken = default) - { - if (string.IsNullOrWhiteSpace(assistantId)) { throw new ArgumentNullException(nameof(assistantId)); } + return await _httpClient.DeleteAndReadAsAsync(_endpointProvider.AssistantDelete(assistantId), cancellationToken); + } - return await _httpClient.DeleteAndReadAsAsync(_endpointProvider.AssistantDelete(assistantId), cancellationToken); + /// + public async Task AssistantFileDelete(string assistantId, string fileId, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(assistantId)) + { + throw new ArgumentNullException(nameof(assistantId)); } - /// - public async Task AssistantFileDelete(string assistantId, string fileId, CancellationToken cancellationToken = default) + if (string.IsNullOrWhiteSpace(fileId)) { - if (string.IsNullOrWhiteSpace(assistantId)) { throw new ArgumentNullException(nameof(assistantId)); } - if (string.IsNullOrWhiteSpace(fileId)) { throw new ArgumentNullException(nameof(fileId)); } - - return await _httpClient.DeleteAndReadAsAsync(_endpointProvider.AssistantFileDelete(assistantId, fileId), cancellationToken); + throw new ArgumentNullException(nameof(fileId)); } - - - - - - - - + return await _httpClient.DeleteAndReadAsAsync(_endpointProvider.AssistantFileDelete(assistantId, fileId), cancellationToken); } -} +} \ No newline at end of file diff --git a/OpenAI.SDK/Managers/OpenAIBetaService.cs b/OpenAI.SDK/Managers/OpenAIBetaService.cs index 711639f0..e5ef5876 100644 --- a/OpenAI.SDK/Managers/OpenAIBetaService.cs +++ b/OpenAI.SDK/Managers/OpenAIBetaService.cs @@ -1,23 +1,17 @@ 锘縰sing OpenAI.Interfaces; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace OpenAI.Managers +namespace OpenAI.Managers; + +/// +/// Beta service for OpenAI. +/// +public partial class OpenAIService : IBetaService { - /// - /// 鎻愪緵beta鐗堟湰鐨勫姛鑳 - /// - public partial class OpenAIService : IBetaService - { - public IAssistantService Assistants => this; + public IAssistantService Assistants => this; - public IMessageService Messages => this; + public IMessageService Messages => this; - public IThreadService Threads => this; + public IThreadService Threads => this; - public IRunService Runs => this; - } -} + public IRunService Runs => this; +} \ No newline at end of file diff --git a/OpenAI.SDK/Managers/OpenAIMessageService.cs b/OpenAI.SDK/Managers/OpenAIMessageService.cs index eab42ea5..b12458cd 100644 --- a/OpenAI.SDK/Managers/OpenAIMessageService.cs +++ b/OpenAI.SDK/Managers/OpenAIMessageService.cs @@ -3,46 +3,44 @@ using OpenAI.ObjectModels.RequestModels; using OpenAI.ObjectModels.ResponseModels; using OpenAI.ObjectModels.SharedModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; -using System.Text; -using System.Threading.Tasks; -namespace OpenAI.Managers +namespace OpenAI.Managers; + +public partial class OpenAIService : IMessageService { - public partial class OpenAIService : IMessageService + /// + /// Create a message. + /// + /// + /// + /// + /// + /// + public async Task MessageCreate(string threadId, MessageCreateRequest request, CancellationToken cancellationToken = default) { - /// - /// Create a message. - /// - /// - /// - /// - /// - /// - /// - public async Task MessageCreate(string threadId, MessageCreateRequest request, string? modelId = null, CancellationToken cancellationToken = default) + if (string.IsNullOrWhiteSpace(threadId)) { - if (string.IsNullOrWhiteSpace(threadId)) { throw new ArgumentNullException(nameof(threadId)); } - - return await _httpClient.PostAndReadAsAsync(_endpointProvider.MessageCreate(threadId), request, cancellationToken); + throw new ArgumentNullException(nameof(threadId)); } - /// - /// Returns a list of messages for a given thread. - /// - /// - /// - /// - /// - /// - public async Task MessageList(string threadId, MessageListRequest? request = null, CancellationToken cancellationToken = default) - { - if (string.IsNullOrWhiteSpace(threadId)) { throw new ArgumentNullException(nameof(threadId)); } + return await _httpClient.PostAndReadAsAsync(_endpointProvider.MessageCreate(threadId), request, cancellationToken); + } - return await _httpClient.GetReadAsAsync(_endpointProvider.MessageList(threadId, request), cancellationToken); + /// + /// Returns a list of messages for a given thread. + /// + /// + /// + /// + /// + /// + public async Task MessageList(string threadId, MessageListRequest? request = null, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(threadId)) + { + throw new ArgumentNullException(nameof(threadId)); } + + return await _httpClient.GetReadAsAsync(_endpointProvider.MessageList(threadId, request), cancellationToken); } -} +} \ No newline at end of file diff --git a/OpenAI.SDK/Managers/OpenAIRunService.cs b/OpenAI.SDK/Managers/OpenAIRunService.cs index ddd3730a..64d39a92 100644 --- a/OpenAI.SDK/Managers/OpenAIRunService.cs +++ b/OpenAI.SDK/Managers/OpenAIRunService.cs @@ -2,82 +2,98 @@ using OpenAI.Interfaces; using OpenAI.ObjectModels.RequestModels; using OpenAI.ObjectModels.SharedModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace OpenAI.Managers +namespace OpenAI.Managers; + +public partial class OpenAIService : IRunService { - public partial class OpenAIService : IRunService + /// + /// Create a run. + /// + /// + /// + /// + /// + /// + /// + public async Task RunCreate(string threadId, RunCreateRequest request, string? modelId = null, CancellationToken cancellationToken = default) { - /// - /// Create a run. - /// - /// - /// - /// - /// - /// - /// - public async Task RunCreate(string threadId, RunCreateRequest request, string? modelId = null, CancellationToken cancellationToken = default) + if (string.IsNullOrWhiteSpace(threadId)) { - if (string.IsNullOrWhiteSpace(threadId)) { throw new ArgumentNullException(nameof(threadId)); } - - //request.ProcessModelId(modelId, _defaultModelId); - return await _httpClient.PostAndReadAsAsync(_endpointProvider.RunCreate(threadId), request, cancellationToken); + throw new ArgumentNullException(nameof(threadId)); } - /// - /// Retrieves a run. - /// - /// - /// - /// - /// - /// - public async Task RunRetrieve(string threadId, string runId, CancellationToken cancellationToken = default) - { - if (string.IsNullOrWhiteSpace(threadId)) { throw new ArgumentNullException(nameof(threadId)); } - if (string.IsNullOrWhiteSpace(runId)) { throw new ArgumentNullException(nameof(runId)); } + request.ProcessModelId(modelId, _defaultModelId); + return await _httpClient.PostAndReadAsAsync(_endpointProvider.RunCreate(threadId), request, cancellationToken); + } - return await _httpClient.GetReadAsAsync(_endpointProvider.RunRetrieve(threadId, runId), cancellationToken); + /// + /// Retrieves a run. + /// + /// + /// + /// + /// + /// + public async Task RunRetrieve(string threadId, string runId, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(threadId)) + { + throw new ArgumentNullException(nameof(threadId)); } - /// - /// Cancels a run that is in_progress. - /// - /// - /// - /// - /// - /// - public async Task RunCancel(string threadId, string runId, CancellationToken cancellationToken = default) + if (string.IsNullOrWhiteSpace(runId)) { - if (string.IsNullOrWhiteSpace(threadId)) { throw new ArgumentNullException(nameof(threadId)); } + throw new ArgumentNullException(nameof(runId)); + } + + return await _httpClient.GetReadAsAsync(_endpointProvider.RunRetrieve(threadId, runId), cancellationToken); + } - return await _httpClient.PostAndReadAsAsync(_endpointProvider.RunCancel(threadId, runId), null,cancellationToken); + /// + /// Cancels a run that is in_progress. + /// + /// + /// + /// + /// + /// + public async Task RunCancel(string threadId, string runId, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(threadId)) + { + throw new ArgumentNullException(nameof(threadId)); } - /// - /// 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. - /// All outputs must be submitted in a single request. - /// - /// - /// - /// - /// - /// - /// - public async Task RunSubmitToolOutputs(string threadId, string runId, SubmitToolOutputsToRunRequest request, CancellationToken cancellationToken = default) + return await _httpClient.PostAndReadAsAsync(_endpointProvider.RunCancel(threadId, runId), null, cancellationToken); + } + + /// + /// 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. + /// All outputs must be submitted in a single request. + /// + /// + /// + /// + /// + /// + /// + /// + public async Task RunSubmitToolOutputs(string threadId, string runId, SubmitToolOutputsToRunRequest request, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(threadId)) { - if (string.IsNullOrWhiteSpace(threadId)) { throw new ArgumentNullException(nameof(threadId)); } - if (string.IsNullOrWhiteSpace(runId)) { throw new ArgumentNullException(nameof(runId)); } + throw new ArgumentNullException(nameof(threadId)); + } - return await _httpClient.PostAndReadAsAsync(_endpointProvider.RunSubmitToolOutputs(threadId, runId), request, cancellationToken); + if (string.IsNullOrWhiteSpace(runId)) + { + throw new ArgumentNullException(nameof(runId)); } + + return await _httpClient.PostAndReadAsAsync(_endpointProvider.RunSubmitToolOutputs(threadId, runId), request, cancellationToken); } -} +} \ No newline at end of file diff --git a/OpenAI.SDK/Managers/OpenAIService.cs b/OpenAI.SDK/Managers/OpenAIService.cs index 349fc116..dca33a6a 100644 --- a/OpenAI.SDK/Managers/OpenAIService.cs +++ b/OpenAI.SDK/Managers/OpenAIService.cs @@ -42,11 +42,14 @@ public OpenAIService(OpenAiOptions settings, HttpClient? httpClient = null) case ProviderType.OpenAi: default: _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {settings.ApiKey}"); - _httpClient.DefaultRequestHeaders.Add("OpenAI-Beta", settings.Assistants); + if (settings.UseBeta) + { + _httpClient.DefaultRequestHeaders.Add("OpenAI-Beta", settings.Assistants); + } break; } - if (!string.IsNullOrWhiteSpace(settings.Organization)) + if (!string.IsNullOrEmpty(settings.Organization)) { _httpClient.DefaultRequestHeaders.Add("OpenAI-Organization", $"{settings.Organization}"); } @@ -106,9 +109,6 @@ public void Dispose() /// public IBetaService Beta => this; - - - /// /// Sets default Model Id /// diff --git a/OpenAI.SDK/Managers/OpenAIThreadService.cs b/OpenAI.SDK/Managers/OpenAIThreadService.cs index 65228f1f..3f869417 100644 --- a/OpenAI.SDK/Managers/OpenAIThreadService.cs +++ b/OpenAI.SDK/Managers/OpenAIThreadService.cs @@ -2,55 +2,54 @@ using OpenAI.Interfaces; using OpenAI.ObjectModels.RequestModels; using OpenAI.ObjectModels.SharedModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace OpenAI.Managers +namespace OpenAI.Managers; + +public partial class OpenAIService : IThreadService { - public partial class OpenAIService : IThreadService + /// + /// Create a thread. + /// + /// + /// + /// + /// + public async Task ThreadCreate(ThreadCreateRequest? request = null, CancellationToken cancellationToken = default) { - /// - /// Create a thread. - /// - /// - /// - /// - /// - /// - public async Task ThreadCreate(ThreadCreateRequest? request = null, string? modelId = null, CancellationToken cancellationToken = default) - { - return await _httpClient.PostAndReadAsAsync(_endpointProvider.ThreadCreate(), request, cancellationToken); - } + return await _httpClient.PostAndReadAsAsync(_endpointProvider.ThreadCreate(), request, cancellationToken); + } - /// - /// Retrieves a thread. - /// - /// - /// - /// - /// - public async Task ThreadRetrieve(string threadId, CancellationToken cancellationToken = default) + /// + /// Retrieves a thread. + /// + /// + /// + /// + /// + public async Task ThreadRetrieve(string threadId, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(threadId)) { - if (string.IsNullOrWhiteSpace(threadId)) { throw new ArgumentNullException(nameof(threadId)); } - - return await _httpClient.GetReadAsAsync(_endpointProvider.ThreadRetrieve(threadId), cancellationToken); + throw new ArgumentNullException(nameof(threadId)); } - /// - /// Delete a thread. - /// - /// - /// - /// - /// - public async Task ThreadDelete(string threadId, CancellationToken cancellationToken = default) - { - if (string.IsNullOrWhiteSpace(threadId)) { throw new ArgumentNullException(nameof(threadId)); } + return await _httpClient.GetReadAsAsync(_endpointProvider.ThreadRetrieve(threadId), cancellationToken); + } - return await _httpClient.DeleteAndReadAsAsync(_endpointProvider.ThreadRetrieve(threadId), cancellationToken); + /// + /// Delete a thread. + /// + /// + /// + /// + /// + public async Task ThreadDelete(string threadId, CancellationToken cancellationToken = default) + { + if (string.IsNullOrWhiteSpace(threadId)) + { + throw new ArgumentNullException(nameof(threadId)); } + + return await _httpClient.DeleteAndReadAsAsync(_endpointProvider.ThreadRetrieve(threadId), cancellationToken); } -} +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/RequestModels/AssistantCreateRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/AssistantCreateRequest.cs index 402cce0d..355c7ea5 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/AssistantCreateRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/AssistantCreateRequest.cs @@ -1,57 +1,49 @@ -锘縰sing OpenAI.ObjectModels.SharedModels; -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Text; -using System.Text.Json.Serialization; -using System.Threading.Tasks; - -namespace OpenAI.ObjectModels.RequestModels +锘縰sing System.Text.Json.Serialization; +using OpenAI.ObjectModels.SharedModels; + +namespace OpenAI.ObjectModels.RequestModels; + +public class AssistantCreateRequest : IOpenAiModels.IModel, IOpenAiModels.IFileIds, IOpenAiModels.IMetaData { - public class AssistantCreateRequest : IOpenAiModels.IModel, IOpenAiModels.IFileIds, IOpenAiModels.IMetaData - { - /// - /// ID of the model to use - /// - [Required] - [JsonPropertyName("model")] - public string Model { get; set; } - - /// - /// The name of the assistant. The maximum length is 256 - /// - [JsonPropertyName("name")] - public string Name { get; set; } - - /// - /// The description of the assistant. - /// - [JsonPropertyName("description")] - public string Description { get; set; } - - /// - /// The system instructions that the assistant uses. - /// - [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. - /// - [JsonPropertyName("file_ids")] - public List FileIds { get; set; } - - /// - /// Set of 16 key-value pairs that can be attached to an object. - /// - [JsonPropertyName("metadata")] - public Dictionary MetaData { get; set; } - } -} + /// + /// The name of the assistant. The maximum length is 256 + /// + [JsonPropertyName("name")] + public string? Name { get; set; } + + /// + /// The description of the assistant. + /// + [JsonPropertyName("description")] + public string? Description { get; set; } + + /// + /// The system instructions that the assistant uses. + /// + [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. + /// + [JsonPropertyName("file_ids")] + public List? FileIds { 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; } +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/RequestModels/MessageCreateRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/MessageCreateRequest.cs index afa662bf..b44c12f0 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/MessageCreateRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/MessageCreateRequest.cs @@ -1,46 +1,39 @@ -锘縰sing OpenAI.ObjectModels.SharedModels; -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Text; +锘縰sing System.ComponentModel.DataAnnotations; using System.Text.Json.Serialization; -using System.Threading.Tasks; +using OpenAI.ObjectModels.SharedModels; -namespace OpenAI.ObjectModels.RequestModels -{ - public class MessageCreateRequest : IOpenAiModels.IFileIds, IOpenAiModels.IMetaData - { - /// - /// The role of the entity that is creating the message. - /// Currently only user is supported. - /// - [Required] - [JsonPropertyName("role")] - public string Role { get; set; } = StaticValues.AssistantsStatics.MessageStatics.Roles.User; +namespace OpenAI.ObjectModels.RequestModels; - /// - /// The content of the message. - /// - [Required] - [JsonPropertyName("content")] - public string Content { get; set; } +public class MessageCreateRequest : IOpenAiModels.IFileIds, IOpenAiModels.IMetaData +{ + /// + /// The role of the entity that is creating the message. + /// Currently only user is supported. + /// + [Required] + [JsonPropertyName("role")] + public string Role { get; set; } = StaticValues.AssistantsStatics.MessageStatics.Roles.User; - /// - /// A list of File IDs that the message should use. - /// There can be a maximum of 10 files attached to a message. - /// Useful for tools like retrieval and code_interpreter that can access and use files. - /// - [JsonPropertyName("file_ids")] - public List FileIds { get; set; } + /// + /// The content of the message. + /// + [Required] + [JsonPropertyName("content")] + public string Content { 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. - /// - [JsonPropertyName("metadata")] - public Dictionary MetaData { get; set; } + /// + /// A list of File IDs that the message should use. + /// There can be a maximum of 10 files attached to a message. + /// Useful for tools like retrieval and code_interpreter that can access and use files. + /// + [JsonPropertyName("file_ids")] + public List FileIds { 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. + /// + [JsonPropertyName("metadata")] + public Dictionary MetaData { get; set; } +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/RequestModels/RunCreateRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/RunCreateRequest.cs index b0d9b9b5..f787ad20 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/RunCreateRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/RunCreateRequest.cs @@ -1,51 +1,109 @@ -锘縰sing OpenAI.ObjectModels.SharedModels; -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Text; +锘縰sing System.ComponentModel.DataAnnotations; using System.Text.Json.Serialization; -using System.Threading.Tasks; +using OpenAI.ObjectModels.SharedModels; -namespace OpenAI.ObjectModels.RequestModels +namespace OpenAI.ObjectModels.RequestModels; + +public class RunCreateRequest : IOpenAiModels.IModel, IOpenAiModels.IMetaData,IOpenAiModels.ITemperature { - public class RunCreateRequest : IOpenAiModels.IModel, IOpenAiModels.IMetaData - { - /// - /// The ID of the assistant to use to execute this run. - /// - [Required] - [JsonPropertyName("assistant_id")] - public string AssistantId { get; set; } - - /// - /// The ID of the Model 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. - /// - [JsonPropertyName("instructions")] - public string? Instructions { get; set; } - - /// - /// Override the tools the assistant can use for this run. - /// This is useful for modifying the behavior on a per-run basis. - /// - [JsonPropertyName("tools")] - public List? Tools { 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. - /// - [JsonPropertyName("metadata")] - public Dictionary? MetaData { get; set; } - } -} + /// + /// The ID of the assistant to use to execute this run. + /// + [Required] + [JsonPropertyName("assistant_id")] + public string AssistantId { get; set; } + + /// + /// The ID of the Model 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; } + + /// + /// Overrides the instructions of the assistant. + /// This is useful for modifying the behavior on a per-run basis. + /// + [JsonPropertyName("instructions")] + public string? Instructions { get; set; } + + /// + /// Appends additional instructions at the end of the instructions for the run. + /// This is useful for modifying the behavior on a per-run basis without overriding other instructions. + /// + [JsonPropertyName("additional_instructions")] + public string? AdditionalInstructions { get; set; } + + /// + /// Adds additional messages to the thread before creating the run. + /// + [JsonPropertyName("additional_messages")] + public List? AdditionalMessages { get; set; } + + /// + /// Override the tools the assistant can use for this run. + /// This is useful for modifying the behavior on a per-run basis. + /// + [JsonPropertyName("tools")] + public List? Tools { 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. + /// + [JsonPropertyName("metadata")] + public Dictionary? MetaData { 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. Defaults to 1. + /// + [JsonPropertyName("temperature")] + public float? Temperature { 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. + /// + [JsonPropertyName("stream")] + public bool? Stream { get; set; } + + /// + /// The maximum number of prompt tokens that may be used over the course of the run. + /// The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. + /// If the run exceeds the number of prompt tokens specified, the run will end with status complete. + /// See incomplete_details for more info. + /// + [JsonPropertyName("max_prompt_tokens")] + public int? MaxPromptTokens { get; set; } + + /// + /// The maximum number of completion tokens that may be used over the course of the run. + /// The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. + /// If the run exceeds the number of completion tokens specified, the run will end with status complete. + /// See incomplete_details for more info. + /// + [JsonPropertyName("max_completion_tokens")] + public int? MaxCompletionTokens { get; set; } + + /// + /// The truncation strategy to use for the thread. + /// + [JsonPropertyName("truncation_strategy")] + public TruncationStrategy? TruncationStrategy { get; set; } + + /// + /// Controls which (if any) tool is called by the model. + /// + [JsonPropertyName("tool_choice")] + public ToolChoice? ToolChoice { get; set; } + + /// + /// Specifies the format that the model must output. + /// + [JsonPropertyName("response_format")] + public ResponseFormat? ResponseFormat { 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 b004bcd8..6e5be108 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/SubmitToolOutputsToRunRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/SubmitToolOutputsToRunRequest.cs @@ -1,40 +1,33 @@ -锘縰sing System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Text; +锘縰sing System.ComponentModel.DataAnnotations; using System.Text.Json.Serialization; -using System.Threading.Tasks; -namespace OpenAI.ObjectModels.RequestModels -{ - public class SubmitToolOutputsToRunRequest - { - /// - /// A list of tools for which the outputs are being submitted. - /// - [Required] - [JsonPropertyName("tool_outputs")] - public List ToolOutputs { get; set; } - } +namespace OpenAI.ObjectModels.RequestModels; +public class SubmitToolOutputsToRunRequest +{ /// - /// A list of tools for which the outputs are being submitted. + /// A list of tools for which the outputs are being submitted. /// - public class ToolOutput - { - /// - /// The ID of the tool call in the required_action object - /// within the run object the output is being submitted for. - /// - [JsonPropertyName("tool_call_id")] - public string ToolCallId { get; set; } + [Required] + [JsonPropertyName("tool_outputs")] + public List ToolOutputs { get; set; } +} - /// - /// The output of the tool call to be submitted to continue the run. - /// - [JsonPropertyName("output")] - public string Output { get; set; } - } +/// +/// A list of tools for which the outputs are being submitted. +/// +public class ToolOutput +{ + /// + /// The ID of the tool call in the required_action object + /// within the run object the output is being submitted for. + /// + [JsonPropertyName("tool_call_id")] + public string? ToolCallId { get; set; } -} + /// + /// The output of the tool call to be submitted to continue the run. + /// + [JsonPropertyName("output")] + public string? Output { get; set; } +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/RequestModels/ThreadCreateRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/ThreadCreateRequest.cs index ee6a768e..e36ea935 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/ThreadCreateRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/ThreadCreateRequest.cs @@ -1,27 +1,21 @@ -锘縰sing OpenAI.ObjectModels.SharedModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json.Serialization; -using System.Threading.Tasks; +锘縰sing System.Text.Json.Serialization; +using OpenAI.ObjectModels.SharedModels; -namespace OpenAI.ObjectModels.RequestModels +namespace OpenAI.ObjectModels.RequestModels; + +public class ThreadCreateRequest : IOpenAiModels.IMetaData { - public class ThreadCreateRequest : IOpenAiModels.IMetaData - { - /// - /// A list of messages to start the thread with. - /// - [JsonPropertyName("messages")] - public List Messages { get; set; } + /// + /// A list of messages to start the thread with. + /// + [JsonPropertyName("messages")] + public List? Messages { 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. - /// - [JsonPropertyName("metadata")] - public Dictionary MetaData { 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 lon + /// + [JsonPropertyName("metadata")] + public Dictionary? MetaData { get; set; } +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/SharedModels/TruncationStrategy.cs b/OpenAI.SDK/ObjectModels/SharedModels/TruncationStrategy.cs new file mode 100644 index 00000000..b7447961 --- /dev/null +++ b/OpenAI.SDK/ObjectModels/SharedModels/TruncationStrategy.cs @@ -0,0 +1,22 @@ +锘縰sing System.Text.Json.Serialization; + +namespace OpenAI.ObjectModels.SharedModels; + +public class TruncationStrategy +{ + /// + /// The truncation strategy to use for the thread. + /// The default is "auto". If set to "last_messages", the thread will be truncated to the n most recent messages in the + /// thread. + /// When set to "auto", messages in the middle of the thread will be dropped to fit the context length of the model, + /// max_prompt_tokens. + /// + [JsonPropertyName("type")] + public string? Type { get; set; } + + /// + /// The number of most recent messages from the thread when constructing the context for the run. + /// + [JsonPropertyName("last_messages")] + public int? LastMessages { get; set; } +} \ No newline at end of file diff --git a/OpenAI.SDK/OpenAiOptions.cs b/OpenAI.SDK/OpenAiOptions.cs index 01166120..cda2d5a5 100644 --- a/OpenAI.SDK/OpenAiOptions.cs +++ b/OpenAI.SDK/OpenAiOptions.cs @@ -126,6 +126,8 @@ public string? DefaultEngineId /// public string? DefaultModelId { get; set; } + public bool UseBeta { get; set; } = false; + /// /// Create an instance of this class with the necessary information to connect to the azure open ai api /// From 2c61fbf0ac7730630c7b6d16ffafc1d06337e39c Mon Sep 17 00:00:00 2001 From: Tolga Kayhan Date: Sun, 14 Apr 2024 22:59:02 +0100 Subject: [PATCH 09/26] model updates --- .../AssistantFileCreateRequest.cs | 29 ++--- .../RequestModels/AssistantModifyRequest.cs | 103 ++++++++---------- .../RequestModels/MessageCreateRequest.cs | 9 +- .../RequestModels/RunCreateRequest.cs | 95 ++++++++-------- .../AssistantFileListResponse.cs | 30 ++--- 5 files changed, 121 insertions(+), 145 deletions(-) diff --git a/OpenAI.SDK/ObjectModels/RequestModels/AssistantFileCreateRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/AssistantFileCreateRequest.cs index 1946fe4e..0c90874e 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/AssistantFileCreateRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/AssistantFileCreateRequest.cs @@ -1,20 +1,13 @@ -锘縰sing System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Text; -using System.Text.Json.Serialization; -using System.Threading.Tasks; +锘縰sing System.Text.Json.Serialization; -namespace OpenAI.ObjectModels.RequestModels +namespace OpenAI.ObjectModels.RequestModels; + +public class AssistantFileCreateRequest { - public class AssistantFileCreateRequest - { - /// - /// A File ID (with purpose="assistants") that the assistant should use. Useful for tools like retrieval and code_interpreter that can access files. - /// - [JsonPropertyName("file_id")] - [Required] - public string FileId { get; set; } - } -} + /// + /// A File ID (with purpose="assistants") that the assistant should use. Useful for tools like retrieval and + /// code_interpreter that can access files. + /// + [JsonPropertyName("file_id")] + public string FileId { get; set; } +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/RequestModels/AssistantModifyRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/AssistantModifyRequest.cs index 94e456f3..ba3be9e5 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/AssistantModifyRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/AssistantModifyRequest.cs @@ -1,56 +1,49 @@ -锘縰sing OpenAI.ObjectModels.SharedModels; -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Text; -using System.Text.Json.Serialization; -using System.Threading.Tasks; - -namespace OpenAI.ObjectModels.RequestModels +锘縰sing System.Text.Json.Serialization; +using OpenAI.ObjectModels.SharedModels; + +namespace OpenAI.ObjectModels.RequestModels; + +public class AssistantModifyRequest : IOpenAiModels.IModel, IOpenAiModels.IFileIds, IOpenAiModels.IMetaData { - public class AssistantModifyRequest : IOpenAiModels.IModel, IOpenAiModels.IFileIds, IOpenAiModels.IMetaData - { - /// - /// ID of the model to use - /// - [JsonPropertyName("model")] - public string Model { get; set; } - - /// - /// The name of the assistant. The maximum length is 256 - /// - [JsonPropertyName("name")] - public string? Name { get; set; } - - /// - /// The description of the assistant. The maximum length is 512 characters. - /// - [JsonPropertyName("description")] - public string? Description { get; set; } - - /// - /// The system instructions that the assistant uses. The maximum length is 32768 characters. - /// - [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. - /// - [JsonPropertyName("file_ids")] - public List FileIds { get; set; } - - /// - /// Set of 16 key-value pairs that can be attached to an object. - /// - [JsonPropertyName("metadata")] - public Dictionary MetaData { get; set; } - } -} + /// + /// The name of the assistant. The maximum length is 256 + /// + [JsonPropertyName("name")] + public string? Name { get; set; } + + /// + /// The description of the assistant. The maximum length is 512 characters. + /// + [JsonPropertyName("description")] + public string? Description { get; set; } + + /// + /// The system instructions that the assistant uses. The maximum length is 32768 characters. + /// + [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. + /// + [JsonPropertyName("file_ids")] + public List? FileIds { 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; } +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/RequestModels/MessageCreateRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/MessageCreateRequest.cs index b44c12f0..37be5e22 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/MessageCreateRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/MessageCreateRequest.cs @@ -1,5 +1,4 @@ -锘縰sing System.ComponentModel.DataAnnotations; -using System.Text.Json.Serialization; +锘縰sing System.Text.Json.Serialization; using OpenAI.ObjectModels.SharedModels; namespace OpenAI.ObjectModels.RequestModels; @@ -10,14 +9,12 @@ public class MessageCreateRequest : IOpenAiModels.IFileIds, IOpenAiModels.IMetaD /// The role of the entity that is creating the message. /// Currently only user is supported. /// - [Required] [JsonPropertyName("role")] public string Role { get; set; } = StaticValues.AssistantsStatics.MessageStatics.Roles.User; /// /// The content of the message. /// - [Required] [JsonPropertyName("content")] public string Content { get; set; } @@ -27,7 +24,7 @@ public class MessageCreateRequest : IOpenAiModels.IFileIds, IOpenAiModels.IMetaD /// Useful for tools like retrieval and code_interpreter that can access and use files. /// [JsonPropertyName("file_ids")] - public List FileIds { get; set; } + public List? FileIds { get; set; } /// /// Set of 16 key-value pairs that can be attached to an object. @@ -35,5 +32,5 @@ public class MessageCreateRequest : IOpenAiModels.IFileIds, IOpenAiModels.IMetaD /// 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 Dictionary? MetaData { get; set; } } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/RequestModels/RunCreateRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/RunCreateRequest.cs index f787ad20..a6b7f974 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/RunCreateRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/RunCreateRequest.cs @@ -1,109 +1,108 @@ -锘縰sing System.ComponentModel.DataAnnotations; -using System.Text.Json.Serialization; +锘縰sing System.Text.Json.Serialization; using OpenAI.ObjectModels.SharedModels; namespace OpenAI.ObjectModels.RequestModels; -public class RunCreateRequest : IOpenAiModels.IModel, IOpenAiModels.IMetaData,IOpenAiModels.ITemperature +public class RunCreateRequest : IOpenAiModels.IModel, IOpenAiModels.IMetaData, IOpenAiModels.ITemperature { /// - /// The ID of the assistant to use to execute this run. + /// The ID of the assistant to use to execute this run. /// - [Required] [JsonPropertyName("assistant_id")] public string AssistantId { get; set; } /// - /// The ID of the Model 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; } - - /// - /// Overrides the instructions of the assistant. - /// This is useful for modifying the behavior on a per-run basis. + /// Overrides the instructions of the assistant. + /// This is useful for modifying the behavior on a per-run basis. /// [JsonPropertyName("instructions")] public string? Instructions { get; set; } /// - /// Appends additional instructions at the end of the instructions for the run. - /// This is useful for modifying the behavior on a per-run basis without overriding other instructions. + /// Appends additional instructions at the end of the instructions for the run. + /// This is useful for modifying the behavior on a per-run basis without overriding other instructions. /// [JsonPropertyName("additional_instructions")] public string? AdditionalInstructions { get; set; } /// - /// Adds additional messages to the thread before creating the run. + /// Adds additional messages to the thread before creating the run. /// [JsonPropertyName("additional_messages")] public List? AdditionalMessages { get; set; } /// - /// Override the tools the assistant can use for this run. - /// This is useful for modifying the behavior on a per-run basis. + /// Override the tools the assistant can use for this run. + /// This is useful for modifying the behavior on a per-run basis. /// [JsonPropertyName("tools")] public List? Tools { 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. - /// - [JsonPropertyName("metadata")] - public Dictionary? MetaData { 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. Defaults to 1. - /// - [JsonPropertyName("temperature")] - public float? Temperature { 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; } /// - /// The maximum number of prompt tokens that may be used over the course of the run. - /// The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. - /// If the run exceeds the number of prompt tokens specified, the run will end with status complete. - /// See incomplete_details for more info. + /// The maximum number of prompt tokens that may be used over the course of the run. + /// The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the + /// run. + /// If the run exceeds the number of prompt tokens specified, the run will end with status complete. + /// See incomplete_details for more info. /// [JsonPropertyName("max_prompt_tokens")] public int? MaxPromptTokens { get; set; } /// - /// The maximum number of completion tokens that may be used over the course of the run. - /// The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. - /// If the run exceeds the number of completion tokens specified, the run will end with status complete. - /// See incomplete_details for more info. + /// The maximum number of completion tokens that may be used over the course of the run. + /// The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the + /// run. + /// If the run exceeds the number of completion tokens specified, the run will end with status complete. + /// See incomplete_details for more info. /// [JsonPropertyName("max_completion_tokens")] public int? MaxCompletionTokens { get; set; } /// - /// The truncation strategy to use for the thread. + /// The truncation strategy to use for the thread. /// [JsonPropertyName("truncation_strategy")] public TruncationStrategy? TruncationStrategy { get; set; } /// - /// Controls which (if any) tool is called by the model. + /// Controls which (if any) tool is called by the model. /// [JsonPropertyName("tool_choice")] public ToolChoice? ToolChoice { get; set; } /// - /// Specifies the format that the model must output. + /// Specifies the format that the model must output. /// [JsonPropertyName("response_format")] public ResponseFormat? ResponseFormat { 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. + /// + [JsonPropertyName("metadata")] + public Dictionary? MetaData { get; set; } + + /// + /// The ID of the Model 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; } + + /// + /// 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. Defaults to 1. + /// + [JsonPropertyName("temperature")] + public float? Temperature { get; set; } } \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/AssistantFileListResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/AssistantFileListResponse.cs index 35ccde9c..ee098c81 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/AssistantFileListResponse.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/AssistantFileListResponse.cs @@ -1,22 +1,16 @@ -锘縰sing OpenAI.ObjectModels.SharedModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json.Serialization; -using System.Threading.Tasks; +锘縰sing System.Text.Json.Serialization; +using OpenAI.ObjectModels.SharedModels; -namespace OpenAI.ObjectModels.ResponseModels +namespace OpenAI.ObjectModels.ResponseModels; + +public record AssistantFileListResponse : DataBaseResponse> { - public record AssistantFileListResponse : DataBaseResponse> - { - [JsonPropertyName("first_id")] - public string FirstId { get; set; } + [JsonPropertyName("first_id")] + public string FirstId { get; set; } - [JsonPropertyName("last_id")] - public string LastId { get; set; } + [JsonPropertyName("last_id")] + public string LastId { get; set; } - [JsonPropertyName("has_more")] - public bool IsHasMore { get; set; } - } -} + [JsonPropertyName("has_more")] + public bool IsHasMore { get; set; } +} \ No newline at end of file From 9f52ba4e7b6924d3d439b208d7703ca47417d57d Mon Sep 17 00:00:00 2001 From: Tolga Kayhan Date: Sun, 14 Apr 2024 23:48:12 +0100 Subject: [PATCH 10/26] Response Models updated --- .../ResponseModels/AssistantListResponse.cs | 30 +- .../SharedModels/AssistantResponse.cs | 115 ++++--- .../SharedModels/DeletionStatusResponse.cs | 38 +-- .../ObjectModels/SharedModels/RunResponse.cs | 306 ++++++++++-------- .../SharedModels/ThreadResponse.cs | 48 ++- 5 files changed, 277 insertions(+), 260 deletions(-) diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/AssistantListResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/AssistantListResponse.cs index 1ecb58aa..3e24019d 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/AssistantListResponse.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/AssistantListResponse.cs @@ -1,22 +1,16 @@ -锘縰sing OpenAI.ObjectModels.SharedModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json.Serialization; -using System.Threading.Tasks; +锘縰sing System.Text.Json.Serialization; +using OpenAI.ObjectModels.SharedModels; -namespace OpenAI.ObjectModels.ResponseModels +namespace OpenAI.ObjectModels.ResponseModels; + +public record AssistantListResponse : DataBaseResponse> { - public record AssistantListResponse : DataBaseResponse> - { - [JsonPropertyName("first_id")] - public string FirstId { get; set; } + [JsonPropertyName("first_id")] + public string FirstId { get; set; } - [JsonPropertyName("last_id")] - public string LastId { get; set; } + [JsonPropertyName("last_id")] + public string LastId { get; set; } - [JsonPropertyName("has_more")] - public bool IsHasMore { get; set; } - } -} + [JsonPropertyName("has_more")] + public bool IsHasMore { 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 17f2256d..3a90c15c 100644 --- a/OpenAI.SDK/ObjectModels/SharedModels/AssistantResponse.cs +++ b/OpenAI.SDK/ObjectModels/SharedModels/AssistantResponse.cs @@ -1,71 +1,66 @@ -锘縰sing OpenAI.ObjectModels.RequestModels; +锘縰sing System.Text.Json.Serialization; +using OpenAI.ObjectModels.RequestModels; using OpenAI.ObjectModels.ResponseModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json.Serialization; -using System.Threading.Tasks; -namespace OpenAI.ObjectModels.SharedModels +namespace OpenAI.ObjectModels.SharedModels; + +public record AssistantResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.ICreatedAt, IOpenAiModels.IModel, IOpenAiModels.IMetaData { - public record AssistantResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.ICreatedAt, IOpenAiModels.IModel, IOpenAiModels.IMetaData - { - /// - /// The identifier, which can be referenced in API endpoints. - /// - [JsonPropertyName("id")] - public string Id { get; set; } + /// + /// The name of the assistant. The maximum length is 256 characters. + /// + [JsonPropertyName("name")] + public string? Name { get; set; } + + /// + /// The description of the assistant. The maximum length is 512 characters. + /// + [JsonPropertyName("description")] + public string? Description { get; set; } - /// - /// The Unix timestamp (in seconds) for when the assistant was created. - /// - [JsonPropertyName("created_at")] - public int CreatedAt { get; set; } + /// + /// The system instructions that the assistant uses. + /// The maximum length is 32768 characters. + /// + [JsonPropertyName("instructions")] + public string? Instructions { get; set; } - /// - /// The name of the assistant. The maximum length is 256 characters. - /// - [JsonPropertyName("name")] - public string Name { get; set; } + /// + /// A list of tools enabled on the assistant. + /// + [JsonPropertyName("tools")] + public List Tools { get; set; } - /// - /// The description of the assistant. The maximum length is 512 characters. - /// - [JsonPropertyName("description")] - public string Description { get; set; } + /// + /// A list of file IDs attached to this assistant. + /// There can be a maximum of 20 files attached to the assistant. + /// Files are ordered by their creation date in ascending order. + /// + [JsonPropertyName("file_ids")] + public List FileIDs { get; set; } - /// - /// ID of the model to use - /// - [JsonPropertyName("model")] - public string Model { get; set; } + /// + /// The Unix timestamp (in seconds) for when the assistant was created. + /// + [JsonPropertyName("created_at")] + public int CreatedAt { get; set; } - /// - ///The system instructions that the assistant uses. - ///The maximum length is 32768 characters. - /// - [JsonPropertyName("instructions")] - public string Insturctions { get; set; } + /// + /// The identifier, which can be referenced in API endpoints. + /// + [JsonPropertyName("id")] + public string Id { 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. - /// Files are ordered by their creation date in ascending order. - /// - [JsonPropertyName("file_ids")] - public List FileIDs { get; set; } + /// + /// Set of 16 key-value pairs that can be attached to an object. + /// + [JsonPropertyName("metadata")] + public Dictionary MetaData { 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; } +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/SharedModels/DeletionStatusResponse.cs b/OpenAI.SDK/ObjectModels/SharedModels/DeletionStatusResponse.cs index 86fd5886..366309b0 100644 --- a/OpenAI.SDK/ObjectModels/SharedModels/DeletionStatusResponse.cs +++ b/OpenAI.SDK/ObjectModels/SharedModels/DeletionStatusResponse.cs @@ -1,25 +1,19 @@ -锘縰sing OpenAI.ObjectModels.ResponseModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json.Serialization; -using System.Threading.Tasks; +锘縰sing System.Text.Json.Serialization; +using OpenAI.ObjectModels.ResponseModels; -namespace OpenAI.ObjectModels.SharedModels +namespace OpenAI.ObjectModels.SharedModels; + +public record DeletionStatusResponse : BaseResponse, IOpenAiModels.IId { - public record DeletionStatusResponse : BaseResponse, IOpenAiModels.IId - { - /// - /// The identifier, which can be referenced in API endpoints. - /// - [JsonPropertyName("id")] - public string Id { get; set; } + /// + /// Deletion state + /// + [JsonPropertyName("deleted")] + public bool IsDeleted { get; set; } - /// - /// Deletion state - /// - [JsonPropertyName("deleted")] - public bool IsDeleted { get; set; } - } -} + /// + /// The identifier, which can be referenced in API endpoints. + /// + [JsonPropertyName("id")] + public string Id { get; set; } +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/SharedModels/RunResponse.cs b/OpenAI.SDK/ObjectModels/SharedModels/RunResponse.cs index c81e9e90..88a1ebef 100644 --- a/OpenAI.SDK/ObjectModels/SharedModels/RunResponse.cs +++ b/OpenAI.SDK/ObjectModels/SharedModels/RunResponse.cs @@ -1,136 +1,176 @@ -锘縰sing OpenAI.ObjectModels.RequestModels; +锘縰sing System.Text.Json.Serialization; +using OpenAI.ObjectModels.RequestModels; using OpenAI.ObjectModels.ResponseModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json.Serialization; -using System.Threading.Tasks; - -namespace OpenAI.ObjectModels.SharedModels + +namespace OpenAI.ObjectModels.SharedModels; + +public record RunResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.IModel, IOpenAiModels.ICreatedAt, IOpenAiModels.IFileIds, IOpenAiModels.IMetaData { - public record RunResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.IModel, IOpenAiModels.ICreatedAt, IOpenAiModels.IFileIds, IOpenAiModels.IMetaData - { - /// - /// The identifier, which can be referenced in API endpoints. - /// - [JsonPropertyName("id")] - public string Id { get; set; } - - /// - /// The Unix timestamp (in seconds) for when the run was created. - /// - [JsonPropertyName("created_at")] - public int CreatedAt { get; set; } - - /// - /// The ID of the thread that was executed on as a part of this run. - /// - [JsonPropertyName("thread_id")] - public string ThreadId { get; set; } - - /// - /// The ID of the assistant used for execution of this run. - /// - [JsonPropertyName("assistant_id")] - public string AssistantId { get; set; } - - /// - /// The status of the run, which can be either queued, in_progress, requires_action, cancelling, cancelled, failed, completed, or expired. - /// - [JsonPropertyName("status")] - public string Status { get; set; } - - /// - /// Details on the action required to continue the run. - /// Will be null if no action is required. - /// - [JsonPropertyName("required_action")] - public RequiredAction? RequiredAction { get; set; } - - - private LastError _lastError; - /// - /// The last error associated with this run. Will be null if there are no errors. - /// - [JsonPropertyName("last_error")] - public LastError? LastError - { - get => _lastError; - set - { - _lastError = value; - if (_lastError == null) return; - - this.Error = new Error() - { - Code = _lastError.Code, - MessageObject = _lastError.Message, - }; - } - } - - /// - /// The Unix timestamp (in seconds) for when the run will expire. - /// - [JsonPropertyName("expires_at")] - public int? ExpiresAt { get; set; } - - /// - /// The Unix timestamp (in seconds) for when the run was started. - /// - [JsonPropertyName("started_at")] - public int? StartedAt { get; set; } - - /// - /// The Unix timestamp (in seconds) for when the run was cancelled. - /// - [JsonPropertyName("cancelled_at")] - public int? CancelledAt { get; set; } - - /// - /// The Unix timestamp (in seconds) for when the run failed. - /// - [JsonPropertyName("failed_at")] - public int? FailedAt { get; set; } - - /// - /// The Unix timestamp (in seconds) for when the run was completed. - /// - [JsonPropertyName("completed_at")] - public int? CompletedAt { get; set; } - - /// - /// The model that the assistant used for this run. - /// - [JsonPropertyName("model")] - public string Model { get; set; } - - /// - ///The instructions that the assistant used for this run. - /// - [JsonPropertyName("instructions")] - public string Instructions { get; set; } - - /// - /// The list of tools that the assistant used for this run. - /// - [JsonPropertyName("tools")] - public List? Tools { get; set; } - - /// - /// The list of File IDs the assistant used for this run. - /// - [JsonPropertyName("file_ids")] - public List? FileIds { 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. - /// - [JsonPropertyName("metadata")] - public Dictionary? MetaData { get; set; } - - } + + /// + /// The ID of the thread that was executed on as a part of this run. + /// + [JsonPropertyName("thread_id")] + public string ThreadId { get; set; } + + /// + /// The ID of the assistant used for execution of this run. + /// + [JsonPropertyName("assistant_id")] + public string AssistantId { get; set; } + + /// + /// The status of the run, which can be either queued, in_progress, requires_action, cancelling, cancelled, failed, + /// completed, or expired. + /// + [JsonPropertyName("status")] + public string Status { get; set; } + + /// + /// Details on the action required to continue the run. + /// Will be null if no action is required. + /// + [JsonPropertyName("required_action")] + public RequiredAction? RequiredAction { get; set; } + + /// + /// The last error associated with this run. Will be null if there are no errors. + /// + [JsonPropertyName("last_error")] + public Error? LastError { get; set; } + + + /// + /// Details on why the run is incomplete. Will be null if the run is not incomplete. + /// + [JsonPropertyName("incomplete_details")] + public IncompleteDetails? IncompleteDetails { get; set; } + + /// + /// The Unix timestamp (in seconds) for when the run will expire. + /// + [JsonPropertyName("expires_at")] + public int? ExpiresAt { get; set; } + + /// + /// The Unix timestamp (in seconds) for when the run was started. + /// + [JsonPropertyName("started_at")] + public int? StartedAt { get; set; } + + /// + /// The Unix timestamp (in seconds) for when the run was cancelled. + /// + [JsonPropertyName("cancelled_at")] + public int? CancelledAt { get; set; } + + /// + /// The Unix timestamp (in seconds) for when the run failed. + /// + [JsonPropertyName("failed_at")] + public int? FailedAt { get; set; } + + /// + /// The Unix timestamp (in seconds) for when the run was completed. + /// + [JsonPropertyName("completed_at")] + public int? CompletedAt { get; set; } + + /// + /// The instructions that the assistant used for this run. + /// + [JsonPropertyName("instructions")] + public string Instructions { get; set; } + + /// + /// The list of tools that the assistant used for this run. + /// + [JsonPropertyName("tools")] + 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.). + /// + [JsonPropertyName("usage")] + public UsageResponse? Usage { get; set; } + + /// + /// The sampling temperature used for this run. If not set, defaults to 1. + /// + [JsonPropertyName("temperature")] + public double? Temperature { get; set; } + + /// + /// The maximum number of prompt tokens specified to have been used over the course of the run. + /// + [JsonPropertyName("max_prompt_tokens")] + public int? MaxPromptTokens { get; set; } + + /// + /// The maximum number of completion tokens specified to have been used over the course of the run. + /// + [JsonPropertyName("max_completion_tokens")] + public int? MaxCompletionTokens { get; set; } + + /// + /// The truncation strategy to use for the thread. The default is auto. + /// + [JsonPropertyName("truncation_strategy")] + 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. + /// 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. + /// + [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. + /// + [JsonPropertyName("response_format")] + public object? ResponseFormat { get; set; } + + /// + /// The Unix timestamp (in seconds) for when the run was created. + /// + [JsonPropertyName("created_at")] + public int CreatedAt { get; set; } + + /// + /// The list of File IDs the assistant used for this run. + /// + [JsonPropertyName("file_ids")] + public List? FileIds { get; set; } + + /// + /// The identifier, which can be referenced in API endpoints. + /// + [JsonPropertyName("id")] + public string Id { 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. + /// + [JsonPropertyName("metadata")] + public Dictionary? MetaData { get; set; } + + /// + /// The model that the assistant used for this run. + /// + [JsonPropertyName("model")] + public string Model { get; set; } } + +public class IncompleteDetails +{ + /// + /// The reason why the run is incomplete. + /// This will point to which specific token limit was reached over the course of the run. + /// + [JsonPropertyName("reason")] + public string Reason { get; set; } +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/SharedModels/ThreadResponse.cs b/OpenAI.SDK/ObjectModels/SharedModels/ThreadResponse.cs index 636c8393..0ea5d06f 100644 --- a/OpenAI.SDK/ObjectModels/SharedModels/ThreadResponse.cs +++ b/OpenAI.SDK/ObjectModels/SharedModels/ThreadResponse.cs @@ -1,31 +1,25 @@ -锘縰sing OpenAI.ObjectModels.ResponseModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json.Serialization; -using System.Threading.Tasks; +锘縰sing System.Text.Json.Serialization; +using OpenAI.ObjectModels.ResponseModels; -namespace OpenAI.ObjectModels.SharedModels +namespace OpenAI.ObjectModels.SharedModels; + +public record ThreadResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.ICreatedAt, IOpenAiModels.IMetaData { - public record ThreadResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.ICreatedAt, IOpenAiModels.IMetaData - { - /// - /// The identifier, which can be referenced in API endpoints. - /// - [JsonPropertyName("id")] - public string Id { get; set; } + /// + /// The Unix timestamp (in seconds) for when the assistant was created. + /// + [JsonPropertyName("created_at")] + public int CreatedAt { get; set; } - /// - /// The Unix timestamp (in seconds) for when the assistant was created. - /// - [JsonPropertyName("created_at")] - public int CreatedAt { get; set; } + /// + /// The identifier, which can be referenced in API endpoints. + /// + [JsonPropertyName("id")] + public string Id { get; set; } - /// - /// Set of 16 key-value pairs that can be attached to an object. - /// - [JsonPropertyName("metadata")] - public Dictionary MetaData { get; set; } - } -} + /// + /// Set of 16 key-value pairs that can be attached to an object. + /// + [JsonPropertyName("metadata")] + public Dictionary? MetaData { get; set; } +} \ No newline at end of file From 8cbb340387dd78ced16c463280fc09bb2d17a6f7 Mon Sep 17 00:00:00 2001 From: Tolga Kayhan Date: Mon, 15 Apr 2024 21:54:07 +0100 Subject: [PATCH 11/26] documentation typo fixes --- .../ObjectModels/RequestModels/ThreadCreateRequest.cs | 6 +++--- OpenAI.SDK/ObjectModels/SharedModels/ThreadResponse.cs | 2 ++ 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/OpenAI.SDK/ObjectModels/RequestModels/ThreadCreateRequest.cs b/OpenAI.SDK/ObjectModels/RequestModels/ThreadCreateRequest.cs index e36ea935..6a81cd1c 100644 --- a/OpenAI.SDK/ObjectModels/RequestModels/ThreadCreateRequest.cs +++ b/OpenAI.SDK/ObjectModels/RequestModels/ThreadCreateRequest.cs @@ -12,9 +12,9 @@ public class ThreadCreateRequest : IOpenAiModels.IMetaData public List? Messages { 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 lon + /// 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 maximum of 512 characters long. /// [JsonPropertyName("metadata")] public Dictionary? MetaData { get; set; } diff --git a/OpenAI.SDK/ObjectModels/SharedModels/ThreadResponse.cs b/OpenAI.SDK/ObjectModels/SharedModels/ThreadResponse.cs index 0ea5d06f..ec75e845 100644 --- a/OpenAI.SDK/ObjectModels/SharedModels/ThreadResponse.cs +++ b/OpenAI.SDK/ObjectModels/SharedModels/ThreadResponse.cs @@ -19,6 +19,8 @@ public record ThreadResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.IC /// /// 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 maximum of 512 characters long. /// [JsonPropertyName("metadata")] public Dictionary? MetaData { get; set; } From 85beb149b4f06d5e30a6c73cb36e4515def8f865 Mon Sep 17 00:00:00 2001 From: Tolga Kayhan Date: Mon, 15 Apr 2024 22:05:36 +0100 Subject: [PATCH 12/26] RequiredAction Cleanup --- .../SharedModels/RequiredAction.cs | 56 +++++++++---------- 1 file changed, 25 insertions(+), 31 deletions(-) diff --git a/OpenAI.SDK/ObjectModels/SharedModels/RequiredAction.cs b/OpenAI.SDK/ObjectModels/SharedModels/RequiredAction.cs index dd6d6233..a17409b2 100644 --- a/OpenAI.SDK/ObjectModels/SharedModels/RequiredAction.cs +++ b/OpenAI.SDK/ObjectModels/SharedModels/RequiredAction.cs @@ -1,37 +1,31 @@ -锘縰sing OpenAI.ObjectModels.RequestModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json.Serialization; -using System.Threading.Tasks; +锘縰sing System.Text.Json.Serialization; +using OpenAI.ObjectModels.RequestModels; -namespace OpenAI.ObjectModels.SharedModels +namespace OpenAI.ObjectModels.SharedModels; + +/// +/// Details on the action required to continue the run. +/// +public class RequiredAction { /// - /// Details on the action required to continue the run. + /// For now, this is always submit_tool_outputs. /// - public class RequiredAction - { - /// - /// For now, this is always submit_tool_outputs. - /// - [JsonPropertyName("type")] - public string Type { get; set; } - - /// - /// Details on the tool outputs needed for this run to continue. - /// - [JsonPropertyName("submit_tool_outputs")] - public SubmitToolOutputs SubmitToolOutputs { get; set; } - } + [JsonPropertyName("type")] + public string Type { get; set; } - public class SubmitToolOutputs - { - /// - /// A list of the relevant tool calls. - /// - [JsonPropertyName("tool_calls")] - public List ToolCalls { get; set; } - } + /// + /// Details on the tool outputs needed for this run to continue. + /// + [JsonPropertyName("submit_tool_outputs")] + public SubmitToolOutputs SubmitToolOutputs { get; set; } } + +public class SubmitToolOutputs +{ + /// + /// A list of the relevant tool calls. + /// + [JsonPropertyName("tool_calls")] + public List ToolCalls { get; set; } +} \ No newline at end of file From 5ad4f61c656b1afbf8776973d79cca3580d91ee5 Mon Sep 17 00:00:00 2001 From: Tolga Kayhan Date: Mon, 15 Apr 2024 22:14:27 +0100 Subject: [PATCH 13/26] Message response objects updated --- .../SharedModels/MessageAnnotation.cs | 81 +++++----- .../SharedModels/MessageImageFile.cs | 28 ++-- .../SharedModels/MessageResponse.cs | 148 +++++++++--------- .../ObjectModels/SharedModels/MessageText.cs | 38 ++--- 4 files changed, 139 insertions(+), 156 deletions(-) diff --git a/OpenAI.SDK/ObjectModels/SharedModels/MessageAnnotation.cs b/OpenAI.SDK/ObjectModels/SharedModels/MessageAnnotation.cs index c3b464de..d2454b1b 100644 --- a/OpenAI.SDK/ObjectModels/SharedModels/MessageAnnotation.cs +++ b/OpenAI.SDK/ObjectModels/SharedModels/MessageAnnotation.cs @@ -1,44 +1,45 @@ -锘縰sing System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json.Serialization; -using System.Threading.Tasks; - -namespace OpenAI.ObjectModels.SharedModels +锘縰sing System.Text.Json.Serialization; + +namespace OpenAI.ObjectModels.SharedModels; + +/// +/// File citation |File path +/// +public record MessageAnnotation { /// - /// File citation |File path + /// type can be锛歠ile_citation銆乫ile_path + /// + [JsonPropertyName("type")] + public string Type { get; set; } + + /// + /// The text in the message content that needs to be replaced. /// - public record MessageAnnotation - { - /// - /// type can be锛歠ile_citation銆乫ile_path - /// - [JsonPropertyName("type")] - public string Type { get; set; } - /// - /// The text in the message content that needs to be replaced. - /// - [JsonPropertyName("text")] - public string Text { get; set; } - - [JsonPropertyName("start_index")] - public int StartIndex { get; set; } - - [JsonPropertyName("end_index")] - public int EndIndex { get; set; } - - /// - /// The ID of the specific File the citation/content is from. - /// - [JsonPropertyName("file_id")] - public string FileId { get; set; } - - /// - /// The specific quote in the file. - /// - [JsonPropertyName("quote")] - public string Quote { get; set; } - } + [JsonPropertyName("text")] + public string Text { get; set; } + + [JsonPropertyName("start_index")] + public int StartIndex { get; set; } + + [JsonPropertyName("end_index")] + public int EndIndex { get; set; } + + [JsonPropertyName("file_citation")] + public FileCitation FileCitation { get; set; } } + +public record FileCitation +{ + /// + /// The ID of the specific File the citation/content is from. + /// + [JsonPropertyName("file_id")] + public string FileId { get; set; } + + /// + /// The specific quote in the file. + /// + [JsonPropertyName("quote")] + public string Quote { get; set; } +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/SharedModels/MessageImageFile.cs b/OpenAI.SDK/ObjectModels/SharedModels/MessageImageFile.cs index fd052388..96db974c 100644 --- a/OpenAI.SDK/ObjectModels/SharedModels/MessageImageFile.cs +++ b/OpenAI.SDK/ObjectModels/SharedModels/MessageImageFile.cs @@ -1,21 +1,15 @@ -锘縰sing System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json.Serialization; -using System.Threading.Tasks; +锘縰sing System.Text.Json.Serialization; -namespace OpenAI.ObjectModels.SharedModels +namespace OpenAI.ObjectModels.SharedModels; + +/// +/// An image File in the content of a message. +/// +public record MessageImageFile { /// - /// An image File in the content of a message. + /// The File ID of the image in the message content. /// - public record MessageImageFile - { - /// - /// The File ID of the image in the message content. - /// - [JsonPropertyName("file_id")] - public string FileId { get; set; } - } -} + [JsonPropertyName("file_id")] + public string FileId { get; set; } +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/SharedModels/MessageResponse.cs b/OpenAI.SDK/ObjectModels/SharedModels/MessageResponse.cs index 15213cd6..564bc1d0 100644 --- a/OpenAI.SDK/ObjectModels/SharedModels/MessageResponse.cs +++ b/OpenAI.SDK/ObjectModels/SharedModels/MessageResponse.cs @@ -1,97 +1,91 @@ -锘縰sing OpenAI.ObjectModels.ResponseModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json.Serialization; -using System.Threading.Tasks; +锘縰sing System.Text.Json.Serialization; +using OpenAI.ObjectModels.ResponseModels; -namespace OpenAI.ObjectModels.SharedModels +namespace OpenAI.ObjectModels.SharedModels; + +/// +/// Represents a message within a thread. +/// +public record MessageResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.ICreatedAt, IOpenAiModels.IMetaData { /// - /// Represents a message within a thread. + /// The thread ID that this message belongs to. /// - public record MessageResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.ICreatedAt, IOpenAiModels.IMetaData - { - /// - /// The identifier, which can be referenced in API endpoints. - /// - [JsonPropertyName("id")] - public string Id { get; set; } + [JsonPropertyName("thread_id")] + public string ThreadId { get; set; } - /// - /// The Unix timestamp (in seconds) for when the message was created. - /// - [JsonPropertyName("created_at")] - public int CreatedAt { get; set; } + /// + /// The entity that produced the message. One of user or assistant. + /// + [JsonPropertyName("role")] + public string Role { get; set; } - /// - /// The thread ID that this message belongs to. - /// - [JsonPropertyName("thread_id")] - public string ThreadId { get; set; } + /// + /// The content of the message in array of text and/or images. + /// + [JsonPropertyName("content")] + public List? Content { get; set; } - /// - /// The entity that produced the message. One of user or assistant. - /// - [JsonPropertyName("role")] - public string Role { get; set; } + /// + /// If applicable, the ID of the assistant that authored this message. + /// + [JsonPropertyName("assistant_id")] + public string? AssistantId { get; set; } - /// - /// The content of the message in array of text and/or images. - /// - [JsonPropertyName("content")] - public List? Content { get; set; } + /// + /// If applicable, the ID of the run associated with the authoring of this message. + /// + [JsonPropertyName("run_id")] + public string? RunId { get; set; } - /// - /// If applicable, the ID of the assistant that authored this message. - /// - [JsonPropertyName("assistant_id")] - public string? AssistantId { get; set; } + /// + /// A list of file IDs that the assistant should use. + /// Useful for tools like retrieval and code_interpreter that can access files. + /// A maximum of 10 files can be attached to a message. + /// + [JsonPropertyName("file_ids")] + public List FileIds { get; set; } - /// - /// If applicable, the ID of the run associated with the authoring of this message. - /// - [JsonPropertyName("run_id")] - public string? RunId { get; set; } + /// + /// The Unix timestamp (in seconds) for when the message was created. + /// + [JsonPropertyName("created_at")] + public int CreatedAt { get; set; } + + /// + /// The identifier, which can be referenced in API endpoints. + /// + [JsonPropertyName("id")] + public string Id { get; set; } + /// + /// Set of 16 key-value pairs that can be attached to an object. + /// + [JsonPropertyName("metadata")] + public Dictionary MetaData { get; set; } + + + /// + /// The content of the message: text and/or images. + /// + public class MessageContent + { /// - /// A list of file IDs that the assistant should use. - /// Useful for tools like retrieval and code_interpreter that can access files. - /// A maximum of 10 files can be attached to a message. + /// text and/or images. image_file銆乼ext /// - [JsonPropertyName("file_ids")] - public List FileIds { get; set; } + [JsonPropertyName("type")] + public string Type { get; set; } /// - /// Set of 16 key-value pairs that can be attached to an object. + /// References an image File in the content of a message. /// - [JsonPropertyName("metadata")] - public Dictionary MetaData { get; set; } - + [JsonPropertyName("image_file")] + public MessageImageFile? ImageFile { get; set; } /// - /// The content of the message: text and/or images. + /// The text content that is part of a message. /// - public class MessageContent - { - /// - /// text and/or images. image_file銆乼ext - /// - [JsonPropertyName("type")] - public string Type { get; set; } - - /// - /// References an image File in the content of a message. - /// - [JsonPropertyName("image_file")] - public MessageImageFile? ImageFile { get; set; } - - /// - /// The text content that is part of a message. - /// - [JsonPropertyName("text")] - public MessageText? Text { get; set; } - } + [JsonPropertyName("text")] + public MessageText? Text { get; set; } } -} +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/SharedModels/MessageText.cs b/OpenAI.SDK/ObjectModels/SharedModels/MessageText.cs index c324b931..8f0b17d9 100644 --- a/OpenAI.SDK/ObjectModels/SharedModels/MessageText.cs +++ b/OpenAI.SDK/ObjectModels/SharedModels/MessageText.cs @@ -1,27 +1,21 @@ -锘縰sing System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json.Serialization; -using System.Threading.Tasks; +锘縰sing System.Text.Json.Serialization; -namespace OpenAI.ObjectModels.SharedModels +namespace OpenAI.ObjectModels.SharedModels; + +/// +/// The text content that is part of a message. +/// +public record MessageText { /// - /// The text content that is part of a message. + /// The data that makes up the text. /// - public record MessageText - { - /// - /// The data that makes up the text. - /// - [JsonPropertyName("value")] - public string Value { get; set; } + [JsonPropertyName("value")] + public string Value { get; set; } - /// - /// annotations - /// - [JsonPropertyName("annotations")] - public List Annotations { get; set; } - } -} + /// + /// annotations + /// + [JsonPropertyName("annotations")] + public List Annotations { get; set; } +} \ No newline at end of file From 47e335dea338b6c93815d2744bb24715bb8fb268 Mon Sep 17 00:00:00 2001 From: Tolga Kayhan Date: Mon, 15 Apr 2024 22:15:40 +0100 Subject: [PATCH 14/26] removed last error --- .../ObjectModels/SharedModels/LastError.cs | 24 ------------------- 1 file changed, 24 deletions(-) delete mode 100644 OpenAI.SDK/ObjectModels/SharedModels/LastError.cs diff --git a/OpenAI.SDK/ObjectModels/SharedModels/LastError.cs b/OpenAI.SDK/ObjectModels/SharedModels/LastError.cs deleted file mode 100644 index 48985313..00000000 --- a/OpenAI.SDK/ObjectModels/SharedModels/LastError.cs +++ /dev/null @@ -1,24 +0,0 @@ -锘縰sing System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json.Serialization; -using System.Threading.Tasks; - -namespace OpenAI.ObjectModels.SharedModels -{ - public record LastError - { - /// - /// One of server_error or rate_limit_exceeded. - /// - [JsonPropertyName("code")] - public string Code { get; set; } - - /// - /// A human-readable description of the error. - /// - [JsonPropertyName("message")] - public string Message { get; set; } - } -} From 74a93faea377633e9c4c35436ef09db26de6dc97 Mon Sep 17 00:00:00 2001 From: Tolga Kayhan Date: Mon, 15 Apr 2024 22:16:35 +0100 Subject: [PATCH 15/26] removed unused ISystemFingerPrint --- OpenAI.SDK/ObjectModels/SharedModels/IOpenAiModels.cs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/OpenAI.SDK/ObjectModels/SharedModels/IOpenAiModels.cs b/OpenAI.SDK/ObjectModels/SharedModels/IOpenAiModels.cs index b5d35c1f..6218eb65 100644 --- a/OpenAI.SDK/ObjectModels/SharedModels/IOpenAiModels.cs +++ b/OpenAI.SDK/ObjectModels/SharedModels/IOpenAiModels.cs @@ -44,11 +44,6 @@ public interface IFile public string FileName { get; set; } } - public interface ISystemFingerPrint - { - public string SystemFingerPrint { get; set; } - } - public interface IMetaData { public Dictionary MetaData { get; set; } From 65534553deef4082f23d53cb9e4ba9a33c7a8edb Mon Sep 17 00:00:00 2001 From: Tolga Kayhan Date: Mon, 15 Apr 2024 22:18:33 +0100 Subject: [PATCH 16/26] removed duplicated AssistantFileResponse --- .../SharedModels/AssistantFileResponse.cs | 48 ++++++++----------- .../SharedModels/AssistatntFileResponse.cs | 31 ------------ 2 files changed, 21 insertions(+), 58 deletions(-) delete mode 100644 OpenAI.SDK/ObjectModels/SharedModels/AssistatntFileResponse.cs diff --git a/OpenAI.SDK/ObjectModels/SharedModels/AssistantFileResponse.cs b/OpenAI.SDK/ObjectModels/SharedModels/AssistantFileResponse.cs index f33e4f45..66ba40ac 100644 --- a/OpenAI.SDK/ObjectModels/SharedModels/AssistantFileResponse.cs +++ b/OpenAI.SDK/ObjectModels/SharedModels/AssistantFileResponse.cs @@ -1,31 +1,25 @@ -锘縰sing OpenAI.ObjectModels.ResponseModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json.Serialization; -using System.Threading.Tasks; +锘縰sing System.Text.Json.Serialization; +using OpenAI.ObjectModels.ResponseModels; -namespace OpenAI.ObjectModels.SharedModels +namespace OpenAI.ObjectModels.SharedModels; + +public record AssistantFileResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.ICreatedAt { - public record AssistantFileResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.ICreatedAt - { - /// - /// The identifier, which can be referenced in API endpoints. - /// - [JsonPropertyName("id")] - public string Id { get; set; } + /// + /// The Unix timestamp (in seconds) for when the assistant file was created. + /// + [JsonPropertyName("assistant_id")] + public string AssistantId { get; set; } - /// - /// The Unix timestamp (in seconds) for when the assistant file was created. - /// - [JsonPropertyName("created_at")] - public int CreatedAt { get; set; } + /// + /// The Unix timestamp (in seconds) for when the assistant file was created. + /// + [JsonPropertyName("created_at")] + public int CreatedAt { get; set; } - /// - /// The Unix timestamp (in seconds) for when the assistant file was created. - /// - [JsonPropertyName("assistant_id")] - public string AssistantId { get; set; } - } -} + /// + /// The identifier, which can be referenced in API endpoints. + /// + [JsonPropertyName("id")] + public string Id { get; set; } +} \ No newline at end of file diff --git a/OpenAI.SDK/ObjectModels/SharedModels/AssistatntFileResponse.cs b/OpenAI.SDK/ObjectModels/SharedModels/AssistatntFileResponse.cs deleted file mode 100644 index 47f8757d..00000000 --- a/OpenAI.SDK/ObjectModels/SharedModels/AssistatntFileResponse.cs +++ /dev/null @@ -1,31 +0,0 @@ -锘縰sing OpenAI.ObjectModels.ResponseModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json.Serialization; -using System.Threading.Tasks; - -namespace OpenAI.ObjectModels.SharedModels -{ - public record AssistatntFileResponse : BaseResponse, IOpenAiModels.IId, IOpenAiModels.ICreatedAt - { - /// - /// The identifier, which can be referenced in API endpoints. - /// - [JsonPropertyName("id")] - public string Id { get; set; } - - /// - /// The Unix timestamp (in seconds) for when the assistant was created. - /// - [JsonPropertyName("created_at")] - public int CreatedAt { get; set; } - - /// - /// The assistant ID that the file is attached to. - /// - [JsonPropertyName("assistant_id")] - public string AssistantId { get; set; } - } -} From 88f4be9f1ef4de0a7f34d39cc6c36f0b6db13d6e Mon Sep 17 00:00:00 2001 From: Tolga Kayhan Date: Mon, 15 Apr 2024 22:24:48 +0100 Subject: [PATCH 17/26] code cleanup --- .../ResponseModels/MessageListResponse.cs | 30 ++++++++----------- 1 file changed, 12 insertions(+), 18 deletions(-) diff --git a/OpenAI.SDK/ObjectModels/ResponseModels/MessageListResponse.cs b/OpenAI.SDK/ObjectModels/ResponseModels/MessageListResponse.cs index 5b56eba0..1ae14ea8 100644 --- a/OpenAI.SDK/ObjectModels/ResponseModels/MessageListResponse.cs +++ b/OpenAI.SDK/ObjectModels/ResponseModels/MessageListResponse.cs @@ -1,22 +1,16 @@ -锘縰sing OpenAI.ObjectModels.SharedModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.Json.Serialization; -using System.Threading.Tasks; +锘縰sing System.Text.Json.Serialization; +using OpenAI.ObjectModels.SharedModels; -namespace OpenAI.ObjectModels.ResponseModels +namespace OpenAI.ObjectModels.ResponseModels; + +public record MessageListResponse : DataBaseResponse> { - public record MessageListResponse : DataBaseResponse> - { - [JsonPropertyName("first_id")] - public string FirstId { get; set; } + [JsonPropertyName("first_id")] + public string FirstId { get; set; } - [JsonPropertyName("last_id")] - public string LastId { get; set; } + [JsonPropertyName("last_id")] + public string LastId { get; set; } - [JsonPropertyName("has_more")] - public bool IsHasMore { get; set; } - } -} + [JsonPropertyName("has_more")] + public bool IsHasMore { get; set; } +} \ No newline at end of file From 6963769fc8e69e1e9d70e1971c9faf6b86450011 Mon Sep 17 00:00:00 2001 From: Tolga Kayhan Date: Mon, 15 Apr 2024 22:51:25 +0100 Subject: [PATCH 18/26] bug fixes and some cleanups --- OpenAI.Playground/Program.cs | 12 +- .../SampleData/betterway_corp.csv | 4 +- .../TestHelpers/AssistantTestHelper.cs | 565 +++++++++--------- OpenAI.SDK/Extensions/ModelExtension.cs | 11 +- OpenAI.SDK/Managers/OpenAIRunService.cs | 2 +- OpenAI.sln.DotSettings | 1 + 6 files changed, 311 insertions(+), 284 deletions(-) diff --git a/OpenAI.Playground/Program.cs b/OpenAI.Playground/Program.cs index ba0dec8c..8f6678ae 100644 --- a/OpenAI.Playground/Program.cs +++ b/OpenAI.Playground/Program.cs @@ -39,12 +39,14 @@ // | / \ / \ | \ /) | ( \ /o\ / ) | (\ / | / \ / \ | // |-----------------------------------------------------------------------| +await ChatCompletionTestHelper.RunSimpleChatCompletionTest(sdk); +//await ChatCompletionTestHelper.RunSimpleCompletionStreamTest(sdk); + + //Assistants -//await AssistantTestHelper.RunAssistantAPITest(sdk); -await AssistantTestHelper.RunHowAssistantsWorkTest(sdk); +//await AssistantTestHelper.RunAssistantApiTest(sdk); +//await AssistantTestHelper.RunHowAssistantsWorkTest(sdk); -//await ChatCompletionTestHelper.RunSimpleChatCompletionTest(sdk); -//await ChatCompletionTestHelper.RunSimpleCompletionStreamTest(sdk); // Vision //await VisionTestHelper.RunSimpleVisionTest(sdk); @@ -53,7 +55,7 @@ // Tools //await ChatCompletionTestHelper.RunChatFunctionCallTest(sdk); -await ChatCompletionTestHelper.RunChatFunctionCallTestAsStream(sdk); +//await ChatCompletionTestHelper.RunChatFunctionCallTestAsStream(sdk); // Whisper //await AudioTestHelper.RunSimpleAudioCreateTranscriptionTest(sdk); diff --git a/OpenAI.Playground/SampleData/betterway_corp.csv b/OpenAI.Playground/SampleData/betterway_corp.csv index e28b8eda..f10398e0 100644 --- a/OpenAI.Playground/SampleData/betterway_corp.csv +++ b/OpenAI.Playground/SampleData/betterway_corp.csv @@ -1,2 +1,2 @@ -浙江佳程供应链有限公司具体在哪?,"浙江佳程供应链有限公司,位于浙江省金华市婺城区八一北街615号佳程国际商务中心" -请介绍下浙江佳程供应链公司。,"浙江佳程供应链公司成立于 2011年,是一家专注于跨境物流的创新供应链服务企业,旗下子公司遍布全国和海外,主要涉及金华、义乌、宁波、沈阳、天津、青岛、济南、苏州、成都、新加坡、德国、俄罗斯等地。" +Company Overview,Company Address +"Please refer to Betterway Supply Chain Co., Ltd. for details.","Betterway Supply Chain Co., Ltd. is located in Jiangsu Province, Nanjing City, Xianlin District, No. 615 on the Eighth Street. Established in 2011, it is a company specializing in the provision of innovative supply chain services, covering the whole country and overseas, mainly in finance, insurance, telecommunications, technology, health, education, agriculture, tourism, automotive, new materials, Australia, Brazil, etc." diff --git a/OpenAI.Playground/TestHelpers/AssistantTestHelper.cs b/OpenAI.Playground/TestHelpers/AssistantTestHelper.cs index 5fca5ced..75753ec1 100644 --- a/OpenAI.Playground/TestHelpers/AssistantTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/AssistantTestHelper.cs @@ -1,315 +1,332 @@ -锘縰sing OpenAI.Builders; +锘縰sing System.Text; +using OpenAI.Builders; using OpenAI.Interfaces; using OpenAI.ObjectModels; using OpenAI.ObjectModels.RequestModels; using OpenAI.ObjectModels.SharedModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace OpenAI.Playground.TestHelpers + +namespace OpenAI.Playground.TestHelpers; + +internal static class AssistantTestHelper { - internal static class AssistantTestHelper + /// + /// Test Assistant api + /// + /// + /// + public static async Task RunAssistantApiTest(IOpenAIService sdk) { - /// - /// Test Assistant api - /// - /// - /// - public static async Task RunAssistantAPITest(IOpenAIService sdk) + ConsoleExtensions.WriteLine("Assistant APT Testing is starting:"); + + #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(); + + ConsoleExtensions.WriteLine("Assistant Create Test:", ConsoleColor.DarkCyan); + var assistantResult = await sdk.Beta.Assistants.AssistantCreate(new AssistantCreateRequest { - ConsoleExtensions.WriteLine("Assistant APT Testing is starting:"); + 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.DefineRetrieval(), ToolDefinition.DefineFunction(func) }, + Model = Models.Gpt_3_5_Turbo_1106 + }); + if (assistantResult.Successful) + { + var assistant = assistantResult; + ConsoleExtensions.WriteLine(assistant.ToJson()); + } + else + { + ConsoleExtensions.WriteLine($"{assistantResult.Error?.Code}: {assistantResult.Error?.Message}"); + return; + } - #region Create assistant - var func = new FunctionDefinitionBuilder("get_corp_location", "get location of corp") - .AddParameter("name", PropertyDefinition.DefineString("compary name, e.g. Betterway")) - .Validate() - .Build(); + var assistantId = assistantResult.Id; + ConsoleExtensions.WriteLine($"assistantId:{assistantId} "); - ConsoleExtensions.WriteLine("Assistant Create Test:", ConsoleColor.DarkCyan); - 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.DefineRetrieval(), ToolDefinition.DefineFunction(func) }, - Model = Models.Gpt_3_5_Turbo_1106 - }); - if (assistantResult.Successful) - { - var assistant = assistantResult; - ConsoleExtensions.WriteLine(assistant.ToJson()); - } - else - { - ConsoleExtensions.WriteLine($"{assistantResult.Error?.Code}: {assistantResult.Error?.Message}"); - return; - } - var assistantId = assistantResult.Id; - ConsoleExtensions.WriteLine($"assistantId:{assistantId} "); - #endregion + #endregion + #region // Assistant List - #region// Assistant List - ConsoleExtensions.WriteLine("Assistant list:", ConsoleColor.DarkCyan); - var asstListResult = await sdk.Beta.Assistants.AssistantList(); - if (asstListResult.Successful) - { - ConsoleExtensions.WriteLine($"asst list: {asstListResult.Data?.ToJson()}"); - } - else - { - ConsoleExtensions.WriteLine($"{asstListResult.Error?.Code}: {asstListResult.Error?.Message}"); - return; - } - #endregion + ConsoleExtensions.WriteLine("Assistant list:", ConsoleColor.DarkCyan); + var asstListResult = await sdk.Beta.Assistants.AssistantList(); + if (asstListResult.Successful) + { + ConsoleExtensions.WriteLine($"asst list: {asstListResult.Data?.ToJson()}"); + } + else + { + ConsoleExtensions.WriteLine($"{asstListResult.Error?.Code}: {asstListResult.Error?.Message}"); + return; + } - #region// Assistant modify - ConsoleExtensions.WriteLine("Assistant modify:", ConsoleColor.DarkCyan); - var asstResult = await sdk.Beta.Assistants.AssistantModify(assistantId,new AssistantModifyRequest() - { - Name= "Qicha rename" - }); - if (asstResult.Successful) - { - ConsoleExtensions.WriteLine(asstResult.ToJson()); - } - else - { - ConsoleExtensions.WriteLine($"{asstResult.Error?.Code}: {asstResult.Error?.Message}"); - return; - } - #endregion + #endregion - #region// Assistant retrieve - ConsoleExtensions.WriteLine("Assistant retrieve:", ConsoleColor.DarkCyan); - var asstRetrieveResult = await sdk.Beta.Assistants.AssistantRetrieve(assistantId); - if (asstRetrieveResult.Successful) - { - ConsoleExtensions.WriteLine(asstRetrieveResult.ToJson()); - } - else - { - ConsoleExtensions.WriteLine($"{asstRetrieveResult.Error?.Code}: {asstRetrieveResult.Error?.Message}"); - return; - } - #endregion + #region // Assistant modify - #region// Assistant delete - ConsoleExtensions.WriteLine("Assistant delete:", ConsoleColor.DarkCyan); - var deleteResult = await sdk.Beta.Assistants.AssistantDelete(assistantId); - if (deleteResult.Successful) - { - ConsoleExtensions.WriteLine(deleteResult.ToJson()); - } - else - { - ConsoleExtensions.WriteLine($"{deleteResult.Error?.Code}: {deleteResult.Error?.Message}"); - return; - } - #endregion + ConsoleExtensions.WriteLine("Assistant modify:", ConsoleColor.DarkCyan); + var asstResult = await sdk.Beta.Assistants.AssistantModify(assistantId, new AssistantModifyRequest() + { + Name = "Qicha rename" + }); + if (asstResult.Successful) + { + ConsoleExtensions.WriteLine(asstResult.ToJson()); + } + else + { + ConsoleExtensions.WriteLine($"{asstResult.Error?.Code}: {asstResult.Error?.Message}"); + return; } - /// - /// How Assistants work - /// see how-it-works - /// - /// - /// - public static async Task RunHowAssistantsWorkTest(IOpenAIService sdk) + #endregion + + #region // Assistant retrieve + + ConsoleExtensions.WriteLine("Assistant retrieve:", ConsoleColor.DarkCyan); + var asstRetrieveResult = await sdk.Beta.Assistants.AssistantRetrieve(assistantId); + if (asstRetrieveResult.Successful) { - ConsoleExtensions.WriteLine("How assistant work Testing is starting:", ConsoleColor.DarkCyan); + ConsoleExtensions.WriteLine(asstRetrieveResult.ToJson()); + } + else + { + ConsoleExtensions.WriteLine($"{asstRetrieveResult.Error?.Code}: {asstRetrieveResult.Error?.Message}"); + return; + } - #region//upload file - const string fileName = "betterway_corp.csv"; - var sampleFile = await FileExtensions.ReadAllBytesAsync($"SampleData/{fileName}"); - var sampleFileAsString = Encoding.UTF8.GetString(sampleFile); + #endregion - ConsoleExtensions.WriteLine($"Uploading file: {fileName}", ConsoleColor.DarkCyan); - var uploadFilesResponse = await sdk.Files.FileUpload(UploadFilePurposes.UploadFilePurpose.Assistants, sampleFile, fileName); - if (uploadFilesResponse.Successful) - { - ConsoleExtensions.WriteLine($"{fileName} uploaded", ConsoleColor.DarkGreen); - } - else - { - ConsoleExtensions.WriteLine($"{fileName} failed", ConsoleColor.DarkRed); - return; - } - var uplaodFileId = uploadFilesResponse.Id; - ConsoleExtensions.WriteLine($"uplaodFileId:{uplaodFileId}, purpose:{uploadFilesResponse.Purpose}"); - #endregion - - #region//create assistants - var func = new FunctionDefinitionBuilder("get_corp_location", "get location of corp") - .AddParameter("name", PropertyDefinition.DefineString("compary name, e.g. Betterway")) - .Validate() - .Build(); - - ConsoleExtensions.WriteLine("Assistant Create Test:", ConsoleColor.DarkCyan); - 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", - Model = Models.Gpt_3_5_Turbo_1106, - Tools = new List() { ToolDefinition.DefineCodeInterpreter(), ToolDefinition.DefineRetrieval(), ToolDefinition.DefineFunction(func) }, - FileIds = new List() { uplaodFileId }, - }); - - if (assistantResult.Successful) - { - ConsoleExtensions.WriteLine(assistantResult.ToJson()); - } - else - { - ConsoleExtensions.WriteLine($"{assistantResult.Error?.Code}: {assistantResult.Error?.Message}"); - return; - } - var assistantId = assistantResult.Id; - ConsoleExtensions.WriteLine($"assistantId:{assistantId} "); - #endregion - - #region //create thread - ConsoleExtensions.WriteLine("Thread Create Test:", ConsoleColor.DarkCyan); - var threadResult = await sdk.Beta.Threads.ThreadCreate(); - if (threadResult.Successful) - { - ConsoleExtensions.WriteLine(threadResult.ToJson()); - } - else - { - ConsoleExtensions.WriteLine($"{threadResult.Error?.Code}: {threadResult.Error?.Message}"); - return; - } - var threadId = threadResult.Id; - ConsoleExtensions.WriteLine($"threadId: {threadId}"); - #endregion + #region // Assistant delete - #region//create thread message - ConsoleExtensions.WriteLine("Message Create Test:", ConsoleColor.DarkCyan); - var messageResult = await sdk.Beta.Messages.MessageCreate(threadId, new MessageCreateRequest - { - Role = StaticValues.AssistantsStatics.MessageStatics.Roles.User, - Content = "Where is Zhejiang Jiacheng Supply Chain Co., LTD.", - FileIds = new List() { uplaodFileId }, - }); + ConsoleExtensions.WriteLine("Assistant delete:", ConsoleColor.DarkCyan); + var deleteResult = await sdk.Beta.Assistants.AssistantDelete(assistantId); + if (deleteResult.Successful) + { + ConsoleExtensions.WriteLine(deleteResult.ToJson()); + } + else + { + ConsoleExtensions.WriteLine($"{deleteResult.Error?.Code}: {deleteResult.Error?.Message}"); + } - if (messageResult.Successful) - { - ConsoleExtensions.WriteLine(messageResult.ToJson()); - } - else - { - ConsoleExtensions.WriteLine($"{messageResult.Error?.Code}: {messageResult.Error?.Message}"); - return; - } - var messageId = messageResult.Id; - #endregion + #endregion + } - #region//create run - ConsoleExtensions.WriteLine("Run Create Test:", ConsoleColor.DarkCyan); - var runResult = await sdk.Beta.Runs.RunCreate(threadId, new RunCreateRequest() - { - AssistantId = assistantId, - }); - if (runResult.Successful) - { - ConsoleExtensions.WriteLine(runResult.ToJson()); - } - else - { - ConsoleExtensions.WriteLine($"{runResult.Error?.Code}: {runResult.Error?.Message}"); - return; - } + /// + /// How Assistants work + /// see how-it-works + /// + /// + /// + public static async Task RunHowAssistantsWorkTest(IOpenAIService sdk) + { + ConsoleExtensions.WriteLine("How assistant work Testing is starting:", ConsoleColor.DarkCyan); + + #region //upload file + + const string fileName = "betterway_corp.csv"; + var sampleFile = await FileExtensions.ReadAllBytesAsync($"SampleData/{fileName}"); + var sampleFileAsString = Encoding.UTF8.GetString(sampleFile); + + ConsoleExtensions.WriteLine($"Uploading file: {fileName}", ConsoleColor.DarkCyan); + var uploadFilesResponse = await sdk.Files.FileUpload(UploadFilePurposes.UploadFilePurpose.Assistants, sampleFile, fileName); + if (uploadFilesResponse.Successful) + { + ConsoleExtensions.WriteLine($"{fileName} uploaded", ConsoleColor.DarkGreen); + } + else + { + ConsoleExtensions.WriteLine($"{fileName} failed", ConsoleColor.DarkRed); + return; + } + + var uplaodFileId = uploadFilesResponse.Id; + ConsoleExtensions.WriteLine($"uplaodFileId:{uplaodFileId}, purpose:{uploadFilesResponse.Purpose}"); + + #endregion + + #region //create assistants + + var func = new FunctionDefinitionBuilder("get_corp_location", "get location of corp").AddParameter("name", PropertyDefinition.DefineString("compary name, e.g. Betterway")) + .Validate() + .Build(); + + ConsoleExtensions.WriteLine("Assistant Create Test:", ConsoleColor.DarkCyan); + 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", + Model = Models.Gpt_3_5_Turbo_1106, + Tools = new List() { ToolDefinition.DefineCodeInterpreter(), ToolDefinition.DefineRetrieval(), ToolDefinition.DefineFunction(func) }, + FileIds = new List() { uplaodFileId } + }); + + if (assistantResult.Successful) + { + ConsoleExtensions.WriteLine(assistantResult.ToJson()); + } + else + { + ConsoleExtensions.WriteLine($"{assistantResult.Error?.Code}: {assistantResult.Error?.Message}"); + return; + } + + var assistantId = assistantResult.Id; + ConsoleExtensions.WriteLine($"assistantId:{assistantId} "); + + #endregion + + #region //create thread + + ConsoleExtensions.WriteLine("Thread Create Test:", ConsoleColor.DarkCyan); + var threadResult = await sdk.Beta.Threads.ThreadCreate(); + if (threadResult.Successful) + { + ConsoleExtensions.WriteLine(threadResult.ToJson()); + } + else + { + ConsoleExtensions.WriteLine($"{threadResult.Error?.Code}: {threadResult.Error?.Message}"); + return; + } + + var threadId = threadResult.Id; + ConsoleExtensions.WriteLine($"threadId: {threadId}"); + + #endregion + + #region //create thread message + + ConsoleExtensions.WriteLine("Message Create Test:", ConsoleColor.DarkCyan); + var messageResult = await sdk.Beta.Messages.MessageCreate(threadId, new MessageCreateRequest + { + Role = StaticValues.AssistantsStatics.MessageStatics.Roles.User, + Content = "Where is Zhejiang Jiacheng Supply Chain Co., LTD.", + FileIds = new List() { uplaodFileId } + }); + + if (messageResult.Successful) + { + ConsoleExtensions.WriteLine(messageResult.ToJson()); + } + else + { + ConsoleExtensions.WriteLine($"{messageResult.Error?.Code}: {messageResult.Error?.Message}"); + return; + } + + var messageId = messageResult.Id; + + #endregion + + #region //create run + + ConsoleExtensions.WriteLine("Run Create Test:", ConsoleColor.DarkCyan); + var runResult = await sdk.Beta.Runs.RunCreate(threadId, new RunCreateRequest() + { + AssistantId = assistantId + }); + if (runResult.Successful) + { + ConsoleExtensions.WriteLine(runResult.ToJson()); + } + else + { + ConsoleExtensions.WriteLine($"{runResult.Error?.Code}: {runResult.Error?.Message}"); + return; + } + + var runId = runResult.Id; + ConsoleExtensions.WriteLine($"runId: {runId}"); + + #endregion - var runId = runResult.Id; - ConsoleExtensions.WriteLine($"runId: {runId}"); - #endregion - - #region//waiting for run completed - ConsoleExtensions.WriteLine("waiting for run completed:", ConsoleColor.DarkCyan); - var runningStatusList = new List() - { - StaticValues.AssistantsStatics.RunStatus.Queued, - StaticValues.AssistantsStatics.RunStatus.InProgress, - StaticValues.AssistantsStatics.RunStatus.RequiresAction, - }; - - //鑾峰彇浠诲姟淇℃伅 - var runRetrieveResult = await sdk.Beta.Runs.RunRetrieve(threadId, runId); - while (runningStatusList.Contains(runRetrieveResult.Status)) + #region //waiting for run completed + + ConsoleExtensions.WriteLine("waiting for run completed:", ConsoleColor.DarkCyan); + var runningStatusList = new List() + { + StaticValues.AssistantsStatics.RunStatus.Queued, + StaticValues.AssistantsStatics.RunStatus.InProgress, + StaticValues.AssistantsStatics.RunStatus.RequiresAction + }; + + //Get task information + var runRetrieveResult = await sdk.Beta.Runs.RunRetrieve(threadId, runId); + while (runningStatusList.Contains(runRetrieveResult.Status)) + { + /* + * 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. + * All outputs must be submitted in a single request. + */ + var requireAction = runRetrieveResult.RequiredAction; + if (runRetrieveResult.Status == StaticValues.AssistantsStatics.RunStatus.RequiresAction && requireAction != null && requireAction.Type == StaticValues.AssistantsStatics.RequiredActionTypes.SubmitToolOutputs) { - /* - * 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. - * All outputs must be submitted in a single request. - */ - var requireAction = runRetrieveResult.RequiredAction; - if (runRetrieveResult.Status == StaticValues.AssistantsStatics.RunStatus.RequiresAction - && requireAction != null && requireAction.Type == StaticValues.AssistantsStatics.RequiredActionTypes.SubmitToolOutputs) + var myFunc = new List() { "get_corp_location" }; + var toolOutputs = new List(); + foreach (var toolCall in requireAction.SubmitToolOutputs.ToolCalls) { - var myFunc = new List() { "get_corp_location" }; - var toolOutputs = new List(); - foreach (var toolCall in requireAction.SubmitToolOutputs.ToolCalls) - { - ConsoleExtensions.WriteLine($"ToolCall:{toolCall?.ToJson()}"); - if (toolCall?.FunctionCall == null) continue; + ConsoleExtensions.WriteLine($"ToolCall:{toolCall?.ToJson()}"); + if (toolCall?.FunctionCall == null) continue; - var funcName = toolCall.FunctionCall.Name; - if (myFunc.Contains(funcName)) - { - //do sumbit tool - var toolOutput = new ToolOutput() - { - ToolCallId = toolCall.Id, - Output = @"Zhejiang Jiacheng Supply Chain Co., Ltd. is located in Jiacheng International Business Center, -No.615 Bayi North Street, Wucheng District, Jinhua City, Zhejiang Province", - }; - toolOutputs.Add(toolOutput); - } - } - - //All outputs must be submitted in a single request. - if (toolOutputs.Any()) + var funcName = toolCall.FunctionCall.Name; + if (myFunc.Contains(funcName)) { - await sdk.Beta.Runs.RunSubmitToolOutputs(threadId, runId, new SubmitToolOutputsToRunRequest() + //do sumbit tool + var toolOutput = new ToolOutput() { - ToolOutputs = toolOutputs, - }); + ToolCallId = toolCall.Id, + Output = @"Zhejiang Jiacheng Supply Chain Co., Ltd. is located in Jiacheng International Business Center, +No.615 Bayi North Street, Wucheng District, Jinhua City, Zhejiang Province" + }; + toolOutputs.Add(toolOutput); } - - await Task.Delay(500); } - runRetrieveResult = await sdk.Beta.Runs.RunRetrieve(threadId, runId); - if (!runningStatusList.Contains(runRetrieveResult.Status)) { break; } + //All outputs must be submitted in a single request. + if (toolOutputs.Any()) + { + await sdk.Beta.Runs.RunSubmitToolOutputs(threadId, runId, new SubmitToolOutputsToRunRequest() + { + ToolOutputs = toolOutputs + }); + } + await Task.Delay(500); } - #endregion - - #region// message list - //鑾峰彇鏈缁堟秷鎭粨鏋 - ConsoleExtensions.WriteLine("Message list:", ConsoleColor.DarkCyan); - var messageListResult = await sdk.Beta.Messages.MessageList(threadId); - if (messageListResult.Successful) + runRetrieveResult = await sdk.Beta.Runs.RunRetrieve(threadId, runId); + if (!runningStatusList.Contains(runRetrieveResult.Status)) { - 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(); - ConsoleExtensions.WriteLine(replys.ToJson()); + break; } - else - { - ConsoleExtensions.WriteLine($"{messageListResult.Error?.Code}: {messageListResult.Error?.Message}"); - return; - } - #endregion } + #endregion + + #region // message list + + //Get the final message result + ConsoleExtensions.WriteLine("Message list:", ConsoleColor.DarkCyan); + var messageListResult = await sdk.Beta.Messages.MessageList(threadId); + if (messageListResult.Successful) + { + 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(); + ConsoleExtensions.WriteLine(replys.ToJson()); + } + else + { + ConsoleExtensions.WriteLine($"{messageListResult.Error?.Code}: {messageListResult.Error?.Message}"); + } + #endregion } -} +} \ No newline at end of file diff --git a/OpenAI.SDK/Extensions/ModelExtension.cs b/OpenAI.SDK/Extensions/ModelExtension.cs index dce014ae..e2df1048 100644 --- a/OpenAI.SDK/Extensions/ModelExtension.cs +++ b/OpenAI.SDK/Extensions/ModelExtension.cs @@ -4,8 +4,15 @@ namespace OpenAI.Extensions; public static class ModelExtension { - public static void ProcessModelId(this IOpenAiModels.IModel modelFromObject, string? modelFromParameter, string? defaultModelId) + public static void ProcessModelId(this IOpenAiModels.IModel modelFromObject, string? modelFromParameter, string? defaultModelId,bool allowNull =false) { - modelFromObject.Model = modelFromParameter ?? modelFromObject.Model ?? defaultModelId ?? throw new ArgumentNullException("Model Id"); + if (allowNull) + { + modelFromObject.Model = modelFromParameter ?? modelFromObject.Model ?? defaultModelId; + } + else + { + modelFromObject.Model = modelFromParameter ?? modelFromObject.Model ?? defaultModelId ?? throw new ArgumentNullException("Model Id"); + } } } \ No newline at end of file diff --git a/OpenAI.SDK/Managers/OpenAIRunService.cs b/OpenAI.SDK/Managers/OpenAIRunService.cs index 64d39a92..c2b7a2d9 100644 --- a/OpenAI.SDK/Managers/OpenAIRunService.cs +++ b/OpenAI.SDK/Managers/OpenAIRunService.cs @@ -23,7 +23,7 @@ public async Task RunCreate(string threadId, RunCreateRequest reque throw new ArgumentNullException(nameof(threadId)); } - request.ProcessModelId(modelId, _defaultModelId); + request.ProcessModelId(modelId, _defaultModelId,true); return await _httpClient.PostAndReadAsAsync(_endpointProvider.RunCreate(threadId), request, cancellationToken); } diff --git a/OpenAI.sln.DotSettings b/OpenAI.sln.DotSettings index b71f8592..1374a314 100644 --- a/OpenAI.sln.DotSettings +++ b/OpenAI.sln.DotSettings @@ -2,6 +2,7 @@ AI CREOL True + True True True True From 287328f47da5c80fe32f7743ec5c74a42c35ed76 Mon Sep 17 00:00:00 2001 From: Tolga Kayhan Date: Mon, 15 Apr 2024 22:52:54 +0100 Subject: [PATCH 19/26] updated csproj --- OpenAI.Playground/OpenAI.Playground.csproj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/OpenAI.Playground/OpenAI.Playground.csproj b/OpenAI.Playground/OpenAI.Playground.csproj index 464bb626..05e050cc 100644 --- a/OpenAI.Playground/OpenAI.Playground.csproj +++ b/OpenAI.Playground/OpenAI.Playground.csproj @@ -60,10 +60,10 @@ PreserveNewest - Always + PreserveNewest - Always + PreserveNewest PreserveNewest From 318c0b67c6eb17d423775e9b234aea3358e2fb5f Mon Sep 17 00:00:00 2001 From: Tolga Kayhan Date: Mon, 15 Apr 2024 23:02:44 +0100 Subject: [PATCH 20/26] code cleanup --- OpenAI.Playground/ConsoleExtensions.cs | 2 +- OpenAI.Playground/Program.cs | 8 +++---- OpenAI.Playground/StringExtension.cs | 31 +++++++++----------------- 3 files changed, 16 insertions(+), 25 deletions(-) diff --git a/OpenAI.Playground/ConsoleExtensions.cs b/OpenAI.Playground/ConsoleExtensions.cs index f4212fe3..e4b9d61a 100644 --- a/OpenAI.Playground/ConsoleExtensions.cs +++ b/OpenAI.Playground/ConsoleExtensions.cs @@ -2,7 +2,7 @@ public static class ConsoleExtensions { - public static void WriteLine(string value, ConsoleColor color = ConsoleColor.Gray) + public static void WriteLine(string? value, ConsoleColor color = ConsoleColor.Gray) { var defaultColor = Console.ForegroundColor; Console.ForegroundColor = color; diff --git a/OpenAI.Playground/Program.cs b/OpenAI.Playground/Program.cs index 8f6678ae..2cc99932 100644 --- a/OpenAI.Playground/Program.cs +++ b/OpenAI.Playground/Program.cs @@ -39,13 +39,13 @@ // | / \ / \ | \ /) | ( \ /o\ / ) | (\ / | / \ / \ | // |-----------------------------------------------------------------------| -await ChatCompletionTestHelper.RunSimpleChatCompletionTest(sdk); +//await ChatCompletionTestHelper.RunSimpleChatCompletionTest(sdk); //await ChatCompletionTestHelper.RunSimpleCompletionStreamTest(sdk); -//Assistants -//await AssistantTestHelper.RunAssistantApiTest(sdk); -//await AssistantTestHelper.RunHowAssistantsWorkTest(sdk); +//Assistants - BETA +await AssistantTestHelper.RunAssistantApiTest(sdk); +await AssistantTestHelper.RunHowAssistantsWorkTest(sdk); // Vision diff --git a/OpenAI.Playground/StringExtension.cs b/OpenAI.Playground/StringExtension.cs index a4240df7..7d1aaef3 100644 --- a/OpenAI.Playground/StringExtension.cs +++ b/OpenAI.Playground/StringExtension.cs @@ -1,25 +1,16 @@ -锘縰sing System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http.Json; -using System.Text; -using System.Text.Json; -using System.Threading.Tasks; +锘縰sing System.Text.Json; -namespace OpenAI.Playground +namespace OpenAI.Playground; + +public static class StringExtension { - public static class StringExtension + public static string? ToJson(this object? s) { - public static string ToJson(this object s) - { - if (s == null) return null; - return JsonSerializer.Serialize(s); - } + return s == null ? null : JsonSerializer.Serialize(s); + } - public static T D(this string json) where T : class - { - if (string.IsNullOrWhiteSpace(json)) return null; - return JsonSerializer.Deserialize(json); - } + public static T? D(this string json) where T : class + { + return string.IsNullOrWhiteSpace(json) ? null : JsonSerializer.Deserialize(json); } -} +} \ No newline at end of file From f3d1d84cc2f0ac0ba8c37f19d937577a37714801 Mon Sep 17 00:00:00 2001 From: Tolga Kayhan Date: Mon, 15 Apr 2024 23:03:32 +0100 Subject: [PATCH 21/26] Code Cleanup --- OpenAI.Playground/Program.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/OpenAI.Playground/Program.cs b/OpenAI.Playground/Program.cs index 2cc99932..159a8718 100644 --- a/OpenAI.Playground/Program.cs +++ b/OpenAI.Playground/Program.cs @@ -39,13 +39,13 @@ // | / \ / \ | \ /) | ( \ /o\ / ) | (\ / | / \ / \ | // |-----------------------------------------------------------------------| -//await ChatCompletionTestHelper.RunSimpleChatCompletionTest(sdk); +await ChatCompletionTestHelper.RunSimpleChatCompletionTest(sdk); //await ChatCompletionTestHelper.RunSimpleCompletionStreamTest(sdk); //Assistants - BETA -await AssistantTestHelper.RunAssistantApiTest(sdk); -await AssistantTestHelper.RunHowAssistantsWorkTest(sdk); +//await AssistantTestHelper.RunAssistantApiTest(sdk); +//await AssistantTestHelper.RunHowAssistantsWorkTest(sdk); // Vision From a3622ec7bf0c2c1af17c76fc36ac6a2b52e8094a Mon Sep 17 00:00:00 2001 From: Tolga Kayhan Date: Mon, 15 Apr 2024 23:27:24 +0100 Subject: [PATCH 22/26] playground fixes --- OpenAI.Playground/Program.cs | 6 + .../TestHelpers/AssistantTestHelper.cs | 2 +- .../TestHelpers/MessageTestHelper.cs | 88 ++++----- .../TestHelpers/RunTestHelper.cs | 187 ++++++++++-------- .../TestHelpers/ThreadTestHelper.cs | 105 +++++----- 5 files changed, 201 insertions(+), 187 deletions(-) diff --git a/OpenAI.Playground/Program.cs b/OpenAI.Playground/Program.cs index 159a8718..af5ab188 100644 --- a/OpenAI.Playground/Program.cs +++ b/OpenAI.Playground/Program.cs @@ -47,7 +47,13 @@ //await AssistantTestHelper.RunAssistantApiTest(sdk); //await AssistantTestHelper.RunHowAssistantsWorkTest(sdk); +await MessageTestHelper.RunMessageCreateTest(sdk); +await ThreadTestHelper.RunThreadCreateTest(sdk); +await ThreadTestHelper.RunThreadRetrieveTest(sdk); + +await RunTestHelper.RunRunCreateTest(sdk); +await RunTestHelper.RunRunCancelTest(sdk); // Vision //await VisionTestHelper.RunSimpleVisionTest(sdk); //await VisionTestHelper.RunSimpleVisionStreamTest(sdk); diff --git a/OpenAI.Playground/TestHelpers/AssistantTestHelper.cs b/OpenAI.Playground/TestHelpers/AssistantTestHelper.cs index 75753ec1..5ac65cfd 100644 --- a/OpenAI.Playground/TestHelpers/AssistantTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/AssistantTestHelper.cs @@ -151,7 +151,7 @@ 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("compary name, e.g. Betterway")) + var func = new FunctionDefinitionBuilder("get_corp_location", "get location of corp").AddParameter("name", PropertyDefinition.DefineString("company name, e.g. Betterway")) .Validate() .Build(); diff --git a/OpenAI.Playground/TestHelpers/MessageTestHelper.cs b/OpenAI.Playground/TestHelpers/MessageTestHelper.cs index deb13738..abc326b2 100644 --- a/OpenAI.Playground/TestHelpers/MessageTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/MessageTestHelper.cs @@ -1,67 +1,61 @@ 锘縰sing OpenAI.Interfaces; using OpenAI.ObjectModels; using OpenAI.ObjectModels.RequestModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -namespace OpenAI.Playground.TestHelpers +namespace OpenAI.Playground.TestHelpers; + +internal static class MessageTestHelper { - internal static class MessageTestHelper + public static async Task RunMessageCreateTest(IOpenAIService sdk) { - public static async Task RunMessageCreateTest(IOpenAIService sdk) + ConsoleExtensions.WriteLine("Message create Testing is starting:", ConsoleColor.Cyan); + + try { - ConsoleExtensions.WriteLine("Message create Testing is starting:", ConsoleColor.Cyan); + ConsoleExtensions.WriteLine("Message Create Test:", ConsoleColor.DarkCyan); - try + var threadResult = await sdk.Beta.Threads.ThreadCreate(); + if (threadResult.Successful) { - ConsoleExtensions.WriteLine("Message Create Test:", ConsoleColor.DarkCyan); - - var threadResult = await sdk.Beta.Threads.ThreadCreate(); - if (threadResult.Successful) - { - ConsoleExtensions.WriteLine(threadResult.ToJson()); - } - else + ConsoleExtensions.WriteLine(threadResult.ToJson()); + } + else + { + if (threadResult.Error == null) { - if (threadResult.Error == null) - { - throw new Exception("Unknown Error"); - } - ConsoleExtensions.WriteLine($"{threadResult.Error.Code}: {threadResult.Error.Message}"); + throw new Exception("Unknown Error"); } - var threadId = threadResult.Id; - ConsoleExtensions.WriteLine($"threadId :{threadId}"); - //var threadId = "thread_eG76zeIGn8XoMN8yYOR1VxfG"; + ConsoleExtensions.WriteLine($"{threadResult.Error.Code}: {threadResult.Error.Message}"); + } - var messageResult = await sdk.Beta.Messages.MessageCreate(threadId, new MessageCreateRequest - { - Role = StaticValues.AssistantsStatics.MessageStatics.Roles.User, - Content = "How does AI work? Explain it in simple terms.", - }); + var threadId = threadResult.Id; + ConsoleExtensions.WriteLine($"threadId :{threadId}"); - if (messageResult.Successful) - { - ConsoleExtensions.WriteLine(messageResult.ToJson()); - } - else - { - if (messageResult.Error == null) - { - throw new Exception("Unknown Error"); - } + var messageResult = await sdk.Beta.Messages.MessageCreate(threadId, new MessageCreateRequest + { + Role = StaticValues.AssistantsStatics.MessageStatics.Roles.User, + Content = "How does AI work? Explain it in simple terms." + }); - ConsoleExtensions.WriteLine($"{messageResult.Error.Code}: {messageResult.Error.Message}"); - } + if (messageResult.Successful) + { + ConsoleExtensions.WriteLine(messageResult.ToJson()); } - catch (Exception e) + else { - Console.WriteLine(e); - throw; + if (messageResult.Error == null) + { + throw new Exception("Unknown Error"); + } + + ConsoleExtensions.WriteLine($"{messageResult.Error.Code}: {messageResult.Error.Message}"); } } + catch (Exception e) + { + Console.WriteLine(e); + throw; + } } -} +} \ No newline at end of file diff --git a/OpenAI.Playground/TestHelpers/RunTestHelper.cs b/OpenAI.Playground/TestHelpers/RunTestHelper.cs index d3301071..da7281a3 100644 --- a/OpenAI.Playground/TestHelpers/RunTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/RunTestHelper.cs @@ -3,111 +3,134 @@ using OpenAI.ObjectModels; using OpenAI.ObjectModels.RequestModels; using OpenAI.ObjectModels.SharedModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http.Headers; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -namespace OpenAI.Playground.TestHelpers +namespace OpenAI.Playground.TestHelpers; + +internal static class RunTestHelper { - internal static class RunTestHelper + public static async Task RunRunCreateTest(IOpenAIService sdk) { - public static async Task RunRunCreateTest(IOpenAIService sdk) - { - ConsoleExtensions.WriteLine("Run create Testing is starting:", ConsoleColor.Cyan); + ConsoleExtensions.WriteLine("Run create Testing is starting:", ConsoleColor.Cyan); - try + + try + { + 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 threadId = "thread_eG76zeIGn8XoMN8yYOR1VxfG"; - var assistantId = $"asst_wnD0KzUtotn40AtnvLMufh9j"; - ConsoleExtensions.WriteLine("Run Create Test:", ConsoleColor.DarkCyan); - var runResult = await sdk.Beta.Runs.RunCreate(threadId, new RunCreateRequest() - { - AssistantId = assistantId, - }); - if (runResult.Successful) + 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.DefineRetrieval(), ToolDefinition.DefineFunction(func) }, + Model = Models.Gpt_3_5_Turbo_1106 + }); + var runResult = await sdk.Beta.Runs.RunCreate(threadId, new RunCreateRequest() + { + AssistantId = assistantResult.Id, + }); + if (runResult.Successful) + { + ConsoleExtensions.WriteLine(runResult.ToJson()); + } + else + { + if (runResult.Error == null) { - ConsoleExtensions.WriteLine(runResult.ToJson()); + throw new Exception("Unknown Error"); } - else - { - if (runResult.Error == null) - { - throw new Exception("Unknown Error"); - } - ConsoleExtensions.WriteLine($"{runResult.Error.Code}: {runResult.Error.Message}"); - } + ConsoleExtensions.WriteLine($"{runResult.Error.Code}: {runResult.Error.Message}"); + } + + var runId = runResult.Id; + ConsoleExtensions.WriteLine($"runId: {runId}"); - var runId = runResult.Id; - ConsoleExtensions.WriteLine($"runId: {runId}"); + var doneStatusList = new List() + { StaticValues.AssistantsStatics.RunStatus.Cancelled, StaticValues.AssistantsStatics.RunStatus.Completed, StaticValues.AssistantsStatics.RunStatus.Failed, StaticValues.AssistantsStatics.RunStatus.Expired }; + var runStatus = StaticValues.AssistantsStatics.RunStatus.Queued; + var attemptCount = 0; + var maxAttempts = 10; - var doneStatusList = new List() { StaticValues.AssistantsStatics.RunStatus.Cancelled, StaticValues.AssistantsStatics.RunStatus.Completed, StaticValues.AssistantsStatics.RunStatus.Failed, StaticValues.AssistantsStatics.RunStatus.Expired }; - var runStatus = StaticValues.AssistantsStatics.RunStatus.Queued; - do + do + { + var runRetrieveResult = await sdk.Beta.Runs.RunRetrieve(threadId, runId); + runStatus = runRetrieveResult.Status; + if (doneStatusList.Contains(runStatus)) { - var runRetrieveResult = await sdk.Beta.Runs.RunRetrieve(threadId, runId); - runStatus = runRetrieveResult.Status; - if (doneStatusList.Contains(runStatus)) { break; } + break; + } - /* - * 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. - * All outputs must be submitted in a single request. - */ - var requireAction = runRetrieveResult.RequiredAction; - if (runStatus == StaticValues.AssistantsStatics.RunStatus.RequiresAction && requireAction.Type == StaticValues.AssistantsStatics.RequiredActionTypes.SubmitToolOutputs) + var requireAction = runRetrieveResult.RequiredAction; + if (runStatus == StaticValues.AssistantsStatics.RunStatus.RequiresAction && requireAction.Type == StaticValues.AssistantsStatics.RequiredActionTypes.SubmitToolOutputs) + { + var toolCalls = requireAction.SubmitToolOutputs.ToolCalls; + foreach (var toolCall in toolCalls) { - var toolCalls = requireAction.SubmitToolOutputs.ToolCalls; - foreach (var toolCall in toolCalls) - { - ConsoleExtensions.WriteLine($"ToolCall:{toolCall?.ToJson()}"); - if (toolCall.FunctionCall == null) return; + ConsoleExtensions.WriteLine($"ToolCall:{toolCall?.ToJson()}"); + if (toolCall.FunctionCall == null) return; - var funcName = toolCall.FunctionCall.Name; - if (funcName == "get_current_weather") - { - //do sumbit tool - } + var funcName = toolCall.FunctionCall.Name; + if (funcName == "get_corp_location") + { + await sdk.Beta.Runs.RunCancel(threadId, runRetrieveResult.Id); + // Do submit tool } } - await Task.Delay(1000); - } while (!doneStatusList.Contains(runStatus)); - } - catch (Exception e) - { - Console.WriteLine(e); - throw; - } + } + + await Task.Delay(1000); + attemptCount++; + if (attemptCount >= maxAttempts) + { + throw new Exception("The maximum number of attempts has been reached."); + } + } while (!doneStatusList.Contains(runStatus)); } + catch (Exception e) + { + Console.WriteLine(e); + throw; + } + } - public static async Task RunRunCancelTest(IOpenAIService sdk) + 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 { - ConsoleExtensions.WriteLine("Run cancel Testing is starting:", ConsoleColor.Cyan); + 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.DefineRetrieval(), ToolDefinition.DefineFunction(func) }, + Model = Models.Gpt_3_5_Turbo_1106 + }); + var runCreateResult = await sdk.Beta.Runs.RunCreate(threadId, new RunCreateRequest() + { + AssistantId = assistantResult.Id, + }); - var threadId = "thread_H43Cyjd8LY8dQNA5N2zbepc0"; - var lastRunId = $"run_0qyHIm4sd9Ugczv0zi5c9BLU"; - ConsoleExtensions.WriteLine("Run Cancel Test:", ConsoleColor.DarkCyan); - var runResult = await sdk.Beta.Runs.RunCancel(threadId, lastRunId); - if (runResult.Successful) - { - ConsoleExtensions.WriteLine(runResult.ToJson()); - } - else + ConsoleExtensions.WriteLine("Run Cancel Test:", ConsoleColor.DarkCyan); + var runResult = await sdk.Beta.Runs.RunCancel(threadId, runCreateResult.Id); + if (runResult.Successful) + { + ConsoleExtensions.WriteLine(runResult.ToJson()); + } + else + { + if (runResult.Error == null) { - if (runResult.Error == null) - { - throw new Exception("Unknown Error"); - } - - ConsoleExtensions.WriteLine($"{runResult.Error.Code}: {runResult.Error.Message}"); + throw new Exception("Unknown Error"); } - + ConsoleExtensions.WriteLine($"{runResult.Error.Code}: {runResult.Error.Message}"); } } -} +} \ No newline at end of file diff --git a/OpenAI.Playground/TestHelpers/ThreadTestHelper.cs b/OpenAI.Playground/TestHelpers/ThreadTestHelper.cs index 2fde9e9a..e1b3a8f7 100644 --- a/OpenAI.Playground/TestHelpers/ThreadTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/ThreadTestHelper.cs @@ -1,78 +1,69 @@ -锘縰sing OpenAI.Builders; -using OpenAI.Interfaces; -using OpenAI.ObjectModels; -using OpenAI.ObjectModels.RequestModels; -using OpenAI.ObjectModels.SharedModels; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +锘縰sing OpenAI.Interfaces; -namespace OpenAI.Playground.TestHelpers +namespace OpenAI.Playground.TestHelpers; + +internal static class ThreadTestHelper { - internal static class ThreadTestHelper + public static async Task RunThreadCreateTest(IOpenAIService sdk) { - public static async Task RunThreadCreateTest(IOpenAIService sdk) + ConsoleExtensions.WriteLine("Thread create Testing is starting:", ConsoleColor.Cyan); + + try { - ConsoleExtensions.WriteLine("Thread create Testing is starting:", ConsoleColor.Cyan); + ConsoleExtensions.WriteLine("Thread Create Test:", ConsoleColor.DarkCyan); + var threadResult = await sdk.Beta.Threads.ThreadCreate(); - try + if (threadResult.Successful) { - ConsoleExtensions.WriteLine("Thread Create Test:", ConsoleColor.DarkCyan); - var threadResult = await sdk.Beta.Threads.ThreadCreate(); - - if (threadResult.Successful) + ConsoleExtensions.WriteLine(threadResult.ToJson()); + return threadResult.Id; + } + else + { + if (threadResult.Error == null) { - ConsoleExtensions.WriteLine(threadResult.ToJson()); + throw new Exception("Unknown Error"); } - else - { - if (threadResult.Error == null) - { - throw new Exception("Unknown Error"); - } - ConsoleExtensions.WriteLine($"{threadResult.Error.Code}: {threadResult.Error.Message}"); - } - } - catch (Exception e) - { - Console.WriteLine(e); - throw; + ConsoleExtensions.WriteLine($"{threadResult.Error.Code}: {threadResult.Error.Message}"); } } - - public static async Task RunThreadRetrieveTest(IOpenAIService sdk) + catch (Exception e) { - ConsoleExtensions.WriteLine("Thread retrieve Testing is starting:", ConsoleColor.Cyan); + Console.WriteLine(e); + throw; + } - try - { - ConsoleExtensions.WriteLine("Thread Retrieve Test:", ConsoleColor.DarkCyan); + throw new InvalidOperationException(); + } - var threadId = "thread_eG76zeIGn8XoMN8yYOR1VxfG"; - var threadResult = await sdk.Beta.Threads.ThreadRetrieve(threadId); + public static async Task RunThreadRetrieveTest(IOpenAIService sdk) + { + ConsoleExtensions.WriteLine("Thread retrieve Testing is starting:", ConsoleColor.Cyan); + try + { + ConsoleExtensions.WriteLine("Thread Retrieve Test:", ConsoleColor.DarkCyan); + var threadId = await RunThreadCreateTest(sdk); + var threadResult = await sdk.Beta.Threads.ThreadRetrieve(threadId); - if (threadResult.Successful) + if (threadResult.Successful) + { + ConsoleExtensions.WriteLine(threadResult.ToJson()); + } + else + { + if (threadResult.Error == null) { - ConsoleExtensions.WriteLine(threadResult.ToJson()); + throw new Exception("Unknown Error"); } - else - { - if (threadResult.Error == null) - { - throw new Exception("Unknown Error"); - } - ConsoleExtensions.WriteLine($"{threadResult.Error.Code}: {threadResult.Error.Message}"); - } - } - catch (Exception e) - { - Console.WriteLine(e); - throw; + ConsoleExtensions.WriteLine($"{threadResult.Error.Code}: {threadResult.Error.Message}"); } } + catch (Exception e) + { + Console.WriteLine(e); + throw; + } } -} +} \ No newline at end of file From b8f124c518ae2e2132fc41ceeaaad703e2304ff4 Mon Sep 17 00:00:00 2001 From: Tolga Kayhan Date: Tue, 16 Apr 2024 00:13:52 +0100 Subject: [PATCH 23/26] Read me update --- OpenAI.SDK/OpenAI.csproj | 2 +- Readme.md | 61 +++++++++++++--------------------------- 2 files changed, 21 insertions(+), 42 deletions(-) diff --git a/OpenAI.SDK/OpenAI.csproj b/OpenAI.SDK/OpenAI.csproj index 7bab23c3..f2c26434 100644 --- a/OpenAI.SDK/OpenAI.csproj +++ b/OpenAI.SDK/OpenAI.csproj @@ -10,7 +10,7 @@ OpenAI-Betalgo.png true OpenAI SDK by Betalgo - 8.0.1 + 8.0.2-beta 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 45326e8c..8d41afef 100644 --- a/Readme.md +++ b/Readme.md @@ -1,59 +1,36 @@ -# Dotnet SDK for OpenAI ChatGPT, Whisper, GPT-4 and DALL路E +# .NET SDK for OpenAI APIs +## .Net SDK for OpenAI, *Community Library*: [![Betalgo.OpenAI](https://img.shields.io/nuget/v/Betalgo.OpenAI?style=for-the-badge)](https://www.nuget.org/packages/Betalgo.OpenAI/) - ``` Install-Package Betalgo.OpenAI ``` -Dotnet SDK for OpenAI -*Unofficial*. -*OpenAI doesn't have any official .Net SDK.* -## Checkout the wiki page: -https://github.com/betalgo/openai/wiki -Betalgo.OpenAI: [![Static Badge](https://img.shields.io/badge/API%20Docs-DNDocs-190088?logo=readme&logoColor=white)](https://dndocs.com/d/betalgo-openai/api/OpenAI.OpenAiOptions.html) -Betalgo.OpenAI.Utilities: [![Static Badge](https://img.shields.io/badge/API%20Docs-DNDocs-190088?logo=readme&logoColor=white)](https://dndocs.com/d/betalgo-openai/api/OpenAI.Utilities.Embedding.EmbeddingTools.html) -## Checkout new ***experimental*** utilities library: +## ***experimental*** utilities library: [![Betalgo.OpenAI.Utilities](https://img.shields.io/nuget/v/Betalgo.OpenAI.Utilities?style=for-the-badge)](https://www.nuget.org/packages/Betalgo.OpenAI.Utilities/) ``` Install-Package Betalgo.OpenAI.Utilities ``` + +## Documentations and links: +[Wiki Page](https://github.com/betalgo/openai/wiki) +[Feature Availability Table](https://github.com/betalgo/openai/wiki/Feature-Availability) +[Change Logs](https://github.com/betalgo/openai/wiki/Change-Logs) + +Betalgo.OpenAI: [![Static Badge](https://img.shields.io/badge/API%20Docs-DNDocs-190088?logo=readme&logoColor=white)](https://dndocs.com/d/betalgo-openai/api/OpenAI.OpenAiOptions.html) +Betalgo.OpenAI.Utilities: [![Static Badge](https://img.shields.io/badge/API%20Docs-DNDocs-190088?logo=readme&logoColor=white)](https://dndocs.com/d/betalgo-openai/api/OpenAI.Utilities.Embedding.EmbeddingTools.html) + +--- + Maintenance of this project is made possible by all the bug reporters, [contributors](https://github.com/betalgo/openai/graphs/contributors) and [sponsors](https://github.com/sponsors/kayhantolga). 馃挅 Sponsors: [@betalgo](https://github.com/betalgo), [Laser Cat Eyes](https://lasercateyes.com/) -[@tylerje](https://github.com/tylerje) -[@oferavnery](https://github.com/oferavnery) -[@MayDay-wpf](https://github.com/MayDay-wpf) -[@AnukarOP](https://github.com/AnukarOP) -[@Removable](https://github.com/Removable) - -## Features -- [x] Dev day Updates -- [x] Vision Api -- [X] Tools -- [X] [Function Calling](https://github.com/betalgo/openai/wiki/Function-Calling) -- [x] [Chat GPT](https://github.com/betalgo/openai/wiki/Chat-GPT) -- [x] [Azure OpenAI](https://github.com/betalgo/openai/wiki/Azure-OpenAI) -- [x] [Image DALL路E](https://github.com/betalgo/openai/wiki/Dall-E) -- [x] [Models](https://github.com/betalgo/openai/wiki/Models) -- [x] [Completions](https://github.com/betalgo/openai/wiki/Completions) -- [x] [Edit](https://github.com/betalgo/openai/wiki/Edit) -- [x] [Embeddings](https://github.com/betalgo/openai/wiki/Embeddings) -- [x] [Files](https://github.com/betalgo/openai/wiki/Files) -- [x] [Chatgpt Fine-Tuning](https://github.com/betalgo/openai/wiki/Chatgpt-Fine-Tuning) -- [x] [Fine-tunes](https://github.com/betalgo/openai/wiki/Fine-Tuning) -- [x] [Moderation](https://github.com/betalgo/openai/wiki/Moderation) -- [x] [Tokenizer-GPT3](https://github.com/betalgo/openai/wiki/Tokenizer) -- [ ] [Tokenizer](https://github.com/betalgo/openai/wiki/Tokenizer) -- [x] [Whisper](https://github.com/betalgo/openai/wiki/Whisper) -- [x] [Rate limit](https://github.com/betalgo/openai/wiki/Rate-Limit) -- [x] [Proxy](https://github.com/betalgo/openai/wiki/Proxy) - - -For changelogs please go to end of the document. +[@tylerje](https://github.com/tylerje) ,[@oferavnery](https://github.com/oferavnery), [@MayDay-wpf](https://github.com/MayDay-wpf), [@AnukarOP](https://github.com/AnukarOP), [@Removable](https://github.com/Removable) + +--- ## Sample Usages The repository contains a sample project named **OpenAI.Playground** that you can refer to for a better understanding of how the library works. However, please exercise caution while experimenting with it, as some of the test methods may result in unintended consequences such as file deletion or fine tuning. @@ -301,9 +278,11 @@ I initially developed this SDK for my personal use and later decided to share it I will always be using the latest libraries, and future releases will frequently include breaking changes. Please take this into consideration before deciding to use the library. I want to make it clear that I cannot accept any responsibility for any damage caused by using the library. If you feel that this is not suitable for your purposes, you are free to explore alternative libraries or the OpenAI Web-API. -I am incredibly busy. If I forgot your name, please accept my apologies and let me know so I can add it to the list. +If I forgot your name in change logs, please accept my apologies and let me know so I can add it to the list. ## Changelog +### 8.0.2-beta +- Added support for beta features, such as assistants, threads, messages, and run. Still missing some of the endpoints, but good progress achieved. See complete list from here: [Feature Availability Table](https://github.com/betalgo/openai/wiki/Feature-Availability). Thanks to @CongquanHu and @alistein. ### 8.0.1 - Added support for new Models `gpt-4-turbo` and `gpt-4-turbo-2024-04-09` thanks to @ChaseIngersol ### 8.0.0 From 34a4920592b15fe1fa48d2b6f432eccdafad792f Mon Sep 17 00:00:00 2001 From: Tolga Kayhan Date: Tue, 16 Apr 2024 00:15:31 +0100 Subject: [PATCH 24/26] moved some files --- .../{ => ExtensionsAndHelpers}/ConsoleExtensions.cs | 2 +- .../{ => ExtensionsAndHelpers}/StringExtension.cs | 2 +- OpenAI.Playground/TestHelpers/AssistantTestHelper.cs | 1 + OpenAI.Playground/TestHelpers/AudioTestHelper.cs | 1 + OpenAI.Playground/TestHelpers/ChatCompletionTestHelper.cs | 1 + OpenAI.Playground/TestHelpers/CompletionTestHelper.cs | 1 + OpenAI.Playground/TestHelpers/EditTestHelper.cs | 1 + OpenAI.Playground/TestHelpers/EmbeddingTestHelper.cs | 1 + OpenAI.Playground/TestHelpers/FileTestHelper.cs | 1 + OpenAI.Playground/TestHelpers/FineTuningJobTestHelper.cs | 1 + OpenAI.Playground/TestHelpers/FineTuningTestHelper.cs | 1 + OpenAI.Playground/TestHelpers/ImageTestHelper.cs | 1 + OpenAI.Playground/TestHelpers/MessageTestHelper.cs | 1 + OpenAI.Playground/TestHelpers/ModelTestHelper.cs | 1 + OpenAI.Playground/TestHelpers/ModerationTestHelper.cs | 1 + OpenAI.Playground/TestHelpers/RunTestHelper.cs | 1 + OpenAI.Playground/TestHelpers/ThreadTestHelper.cs | 1 + OpenAI.Playground/TestHelpers/TokenizerTestHelper.cs | 3 ++- OpenAI.Playground/TestHelpers/VisionTestHelper.cs | 1 + 19 files changed, 20 insertions(+), 3 deletions(-) rename OpenAI.Playground/{ => ExtensionsAndHelpers}/ConsoleExtensions.cs (85%) rename OpenAI.Playground/{ => ExtensionsAndHelpers}/StringExtension.cs (87%) diff --git a/OpenAI.Playground/ConsoleExtensions.cs b/OpenAI.Playground/ExtensionsAndHelpers/ConsoleExtensions.cs similarity index 85% rename from OpenAI.Playground/ConsoleExtensions.cs rename to OpenAI.Playground/ExtensionsAndHelpers/ConsoleExtensions.cs index e4b9d61a..816de5d7 100644 --- a/OpenAI.Playground/ConsoleExtensions.cs +++ b/OpenAI.Playground/ExtensionsAndHelpers/ConsoleExtensions.cs @@ -1,4 +1,4 @@ -锘縩amespace OpenAI.Playground; +锘縩amespace OpenAI.Playground.ExtensionsAndHelpers; public static class ConsoleExtensions { diff --git a/OpenAI.Playground/StringExtension.cs b/OpenAI.Playground/ExtensionsAndHelpers/StringExtension.cs similarity index 87% rename from OpenAI.Playground/StringExtension.cs rename to OpenAI.Playground/ExtensionsAndHelpers/StringExtension.cs index 7d1aaef3..fea3cf4d 100644 --- a/OpenAI.Playground/StringExtension.cs +++ b/OpenAI.Playground/ExtensionsAndHelpers/StringExtension.cs @@ -1,6 +1,6 @@ 锘縰sing System.Text.Json; -namespace OpenAI.Playground; +namespace OpenAI.Playground.ExtensionsAndHelpers; public static class StringExtension { diff --git a/OpenAI.Playground/TestHelpers/AssistantTestHelper.cs b/OpenAI.Playground/TestHelpers/AssistantTestHelper.cs index 5ac65cfd..208e5156 100644 --- a/OpenAI.Playground/TestHelpers/AssistantTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/AssistantTestHelper.cs @@ -4,6 +4,7 @@ using OpenAI.ObjectModels; using OpenAI.ObjectModels.RequestModels; using OpenAI.ObjectModels.SharedModels; +using OpenAI.Playground.ExtensionsAndHelpers; namespace OpenAI.Playground.TestHelpers; diff --git a/OpenAI.Playground/TestHelpers/AudioTestHelper.cs b/OpenAI.Playground/TestHelpers/AudioTestHelper.cs index d41cb0a1..a06b77b4 100644 --- a/OpenAI.Playground/TestHelpers/AudioTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/AudioTestHelper.cs @@ -1,6 +1,7 @@ 锘縰sing OpenAI.Interfaces; using OpenAI.ObjectModels; using OpenAI.ObjectModels.RequestModels; +using OpenAI.Playground.ExtensionsAndHelpers; namespace OpenAI.Playground.TestHelpers; diff --git a/OpenAI.Playground/TestHelpers/ChatCompletionTestHelper.cs b/OpenAI.Playground/TestHelpers/ChatCompletionTestHelper.cs index 303b2ac1..aa509190 100644 --- a/OpenAI.Playground/TestHelpers/ChatCompletionTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/ChatCompletionTestHelper.cs @@ -3,6 +3,7 @@ using OpenAI.ObjectModels; using OpenAI.ObjectModels.RequestModels; using OpenAI.ObjectModels.SharedModels; +using OpenAI.Playground.ExtensionsAndHelpers; namespace OpenAI.Playground.TestHelpers; diff --git a/OpenAI.Playground/TestHelpers/CompletionTestHelper.cs b/OpenAI.Playground/TestHelpers/CompletionTestHelper.cs index 0d12bb95..0837e21b 100644 --- a/OpenAI.Playground/TestHelpers/CompletionTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/CompletionTestHelper.cs @@ -1,6 +1,7 @@ 锘縰sing OpenAI.Interfaces; using OpenAI.ObjectModels; using OpenAI.ObjectModels.RequestModels; +using OpenAI.Playground.ExtensionsAndHelpers; namespace OpenAI.Playground.TestHelpers; diff --git a/OpenAI.Playground/TestHelpers/EditTestHelper.cs b/OpenAI.Playground/TestHelpers/EditTestHelper.cs index d057358f..7ec0fec1 100644 --- a/OpenAI.Playground/TestHelpers/EditTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/EditTestHelper.cs @@ -1,6 +1,7 @@ 锘縰sing OpenAI.Interfaces; using OpenAI.ObjectModels; using OpenAI.ObjectModels.RequestModels; +using OpenAI.Playground.ExtensionsAndHelpers; namespace OpenAI.Playground.TestHelpers; diff --git a/OpenAI.Playground/TestHelpers/EmbeddingTestHelper.cs b/OpenAI.Playground/TestHelpers/EmbeddingTestHelper.cs index 0fd69129..66068d42 100644 --- a/OpenAI.Playground/TestHelpers/EmbeddingTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/EmbeddingTestHelper.cs @@ -1,6 +1,7 @@ 锘縰sing OpenAI.Interfaces; using OpenAI.ObjectModels; using OpenAI.ObjectModels.RequestModels; +using OpenAI.Playground.ExtensionsAndHelpers; namespace OpenAI.Playground.TestHelpers; diff --git a/OpenAI.Playground/TestHelpers/FileTestHelper.cs b/OpenAI.Playground/TestHelpers/FileTestHelper.cs index 62759630..a965f5f9 100644 --- a/OpenAI.Playground/TestHelpers/FileTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/FileTestHelper.cs @@ -1,6 +1,7 @@ 锘縰sing System.Text; using OpenAI.Interfaces; using OpenAI.ObjectModels; +using OpenAI.Playground.ExtensionsAndHelpers; namespace OpenAI.Playground.TestHelpers; diff --git a/OpenAI.Playground/TestHelpers/FineTuningJobTestHelper.cs b/OpenAI.Playground/TestHelpers/FineTuningJobTestHelper.cs index a1b119d4..93ef4dd9 100644 --- a/OpenAI.Playground/TestHelpers/FineTuningJobTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/FineTuningJobTestHelper.cs @@ -2,6 +2,7 @@ using OpenAI.ObjectModels; using OpenAI.ObjectModels.RequestModels; using OpenAI.ObjectModels.ResponseModels.FineTuningJobResponseModels; +using OpenAI.Playground.ExtensionsAndHelpers; namespace OpenAI.Playground.TestHelpers; diff --git a/OpenAI.Playground/TestHelpers/FineTuningTestHelper.cs b/OpenAI.Playground/TestHelpers/FineTuningTestHelper.cs index 4e1fcd40..78e5858f 100644 --- a/OpenAI.Playground/TestHelpers/FineTuningTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/FineTuningTestHelper.cs @@ -2,6 +2,7 @@ using OpenAI.ObjectModels; using OpenAI.ObjectModels.RequestModels; using OpenAI.ObjectModels.ResponseModels.FineTuneResponseModels; +using OpenAI.Playground.ExtensionsAndHelpers; namespace OpenAI.Playground.TestHelpers; diff --git a/OpenAI.Playground/TestHelpers/ImageTestHelper.cs b/OpenAI.Playground/TestHelpers/ImageTestHelper.cs index b90fa7ee..bc41e739 100644 --- a/OpenAI.Playground/TestHelpers/ImageTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/ImageTestHelper.cs @@ -1,6 +1,7 @@ 锘縰sing OpenAI.Interfaces; using OpenAI.ObjectModels; using OpenAI.ObjectModels.RequestModels; +using OpenAI.Playground.ExtensionsAndHelpers; namespace OpenAI.Playground.TestHelpers; diff --git a/OpenAI.Playground/TestHelpers/MessageTestHelper.cs b/OpenAI.Playground/TestHelpers/MessageTestHelper.cs index abc326b2..af5e472b 100644 --- a/OpenAI.Playground/TestHelpers/MessageTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/MessageTestHelper.cs @@ -1,6 +1,7 @@ 锘縰sing OpenAI.Interfaces; using OpenAI.ObjectModels; using OpenAI.ObjectModels.RequestModels; +using OpenAI.Playground.ExtensionsAndHelpers; namespace OpenAI.Playground.TestHelpers; diff --git a/OpenAI.Playground/TestHelpers/ModelTestHelper.cs b/OpenAI.Playground/TestHelpers/ModelTestHelper.cs index 80d95690..1206a2a1 100644 --- a/OpenAI.Playground/TestHelpers/ModelTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/ModelTestHelper.cs @@ -1,4 +1,5 @@ 锘縰sing OpenAI.Interfaces; +using OpenAI.Playground.ExtensionsAndHelpers; namespace OpenAI.Playground.TestHelpers; diff --git a/OpenAI.Playground/TestHelpers/ModerationTestHelper.cs b/OpenAI.Playground/TestHelpers/ModerationTestHelper.cs index 94feddf0..1c47f049 100644 --- a/OpenAI.Playground/TestHelpers/ModerationTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/ModerationTestHelper.cs @@ -1,5 +1,6 @@ 锘縰sing OpenAI.Interfaces; using OpenAI.ObjectModels.RequestModels; +using OpenAI.Playground.ExtensionsAndHelpers; namespace OpenAI.Playground.TestHelpers; diff --git a/OpenAI.Playground/TestHelpers/RunTestHelper.cs b/OpenAI.Playground/TestHelpers/RunTestHelper.cs index da7281a3..7b9e810d 100644 --- a/OpenAI.Playground/TestHelpers/RunTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/RunTestHelper.cs @@ -3,6 +3,7 @@ using OpenAI.ObjectModels; using OpenAI.ObjectModels.RequestModels; using OpenAI.ObjectModels.SharedModels; +using OpenAI.Playground.ExtensionsAndHelpers; namespace OpenAI.Playground.TestHelpers; diff --git a/OpenAI.Playground/TestHelpers/ThreadTestHelper.cs b/OpenAI.Playground/TestHelpers/ThreadTestHelper.cs index e1b3a8f7..993a0f9f 100644 --- a/OpenAI.Playground/TestHelpers/ThreadTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/ThreadTestHelper.cs @@ -1,4 +1,5 @@ 锘縰sing OpenAI.Interfaces; +using OpenAI.Playground.ExtensionsAndHelpers; namespace OpenAI.Playground.TestHelpers; diff --git a/OpenAI.Playground/TestHelpers/TokenizerTestHelper.cs b/OpenAI.Playground/TestHelpers/TokenizerTestHelper.cs index b5e2f378..464730d7 100644 --- a/OpenAI.Playground/TestHelpers/TokenizerTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/TokenizerTestHelper.cs @@ -1,4 +1,5 @@ -锘縰sing OpenAI.Tokenizer.GPT3; +锘縰sing OpenAI.Playground.ExtensionsAndHelpers; +using OpenAI.Tokenizer.GPT3; namespace OpenAI.Playground.TestHelpers; diff --git a/OpenAI.Playground/TestHelpers/VisionTestHelper.cs b/OpenAI.Playground/TestHelpers/VisionTestHelper.cs index fc3e09db..2c92a52d 100644 --- a/OpenAI.Playground/TestHelpers/VisionTestHelper.cs +++ b/OpenAI.Playground/TestHelpers/VisionTestHelper.cs @@ -1,6 +1,7 @@ using OpenAI.Interfaces; using OpenAI.ObjectModels; using OpenAI.ObjectModels.RequestModels; +using OpenAI.Playground.ExtensionsAndHelpers; using static OpenAI.ObjectModels.StaticValues; namespace OpenAI.Playground.TestHelpers; From 9506c3b00766788d3bd0d6eec7e200748ce8bcdb Mon Sep 17 00:00:00 2001 From: Tolga Kayhan Date: Tue, 16 Apr 2024 00:19:18 +0100 Subject: [PATCH 25/26] Fixed a bug in configuration --- OpenAI.Playground/Program.cs | 4 ++-- .../Extensions/OpenAIServiceCollectionExtensions.cs | 13 +++---------- 2 files changed, 5 insertions(+), 12 deletions(-) diff --git a/OpenAI.Playground/Program.cs b/OpenAI.Playground/Program.cs index af5ab188..6785b5c9 100644 --- a/OpenAI.Playground/Program.cs +++ b/OpenAI.Playground/Program.cs @@ -19,7 +19,7 @@ serviceCollection.AddLaserCatEyesHttpClientListener(); -serviceCollection.AddOpenAIService(); +serviceCollection.AddOpenAIService(r=>r.UseBeta = true); //// DeploymentId and ResourceName are only for Azure OpenAI. If you want to use Azure OpenAI services you have to set Provider type To Azure. //serviceCollection.AddOpenAIService(options => //{ @@ -44,7 +44,7 @@ //Assistants - BETA -//await AssistantTestHelper.RunAssistantApiTest(sdk); +await AssistantTestHelper.RunAssistantApiTest(sdk); //await AssistantTestHelper.RunHowAssistantsWorkTest(sdk); await MessageTestHelper.RunMessageCreateTest(sdk); diff --git a/OpenAI.SDK/Extensions/OpenAIServiceCollectionExtensions.cs b/OpenAI.SDK/Extensions/OpenAIServiceCollectionExtensions.cs index efc4fdf2..b4d1e4f8 100644 --- a/OpenAI.SDK/Extensions/OpenAIServiceCollectionExtensions.cs +++ b/OpenAI.SDK/Extensions/OpenAIServiceCollectionExtensions.cs @@ -9,30 +9,23 @@ public static class OpenAIServiceCollectionExtensions public static IHttpClientBuilder AddOpenAIService(this IServiceCollection services, Action? setupAction = null) { var optionsBuilder = services.AddOptions(); + optionsBuilder.BindConfiguration(OpenAiOptions.SettingKey); if (setupAction != null) { optionsBuilder.Configure(setupAction); } - else - { - optionsBuilder.BindConfiguration(OpenAiOptions.SettingKey); - } return services.AddHttpClient(); } - public static IHttpClientBuilder AddOpenAIService(this IServiceCollection services, string name, Action? setupAction = null) - where TServiceInterface : class, IOpenAIService + public static IHttpClientBuilder AddOpenAIService(this IServiceCollection services, string name, Action? setupAction = null) where TServiceInterface : class, IOpenAIService { var optionsBuilder = services.AddOptions(name); + optionsBuilder.BindConfiguration($"{OpenAiOptions.SettingKey}:{name}"); if (setupAction != null) { optionsBuilder.Configure(setupAction); } - else - { - optionsBuilder.BindConfiguration($"{OpenAiOptions.SettingKey}:{name}"); - } return services.AddHttpClient(); } From a4bf0b43c5d475870ce46fc9b3d61e9715734a8f Mon Sep 17 00:00:00 2001 From: Tolga Kayhan Date: Tue, 16 Apr 2024 00:25:32 +0100 Subject: [PATCH 26/26] documentation update --- OpenAI.Playground/Program.cs | 17 ++++++++++------- Readme.md | 6 ++++++ 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/OpenAI.Playground/Program.cs b/OpenAI.Playground/Program.cs index 6785b5c9..6f5f26b2 100644 --- a/OpenAI.Playground/Program.cs +++ b/OpenAI.Playground/Program.cs @@ -18,8 +18,10 @@ // It is in Beta version, if you don't want to use it just comment out below line. serviceCollection.AddLaserCatEyesHttpClientListener(); - +//if you want to use beta services you have to set UseBeta to true. Otherwise, it will use the stable version of OpenAI apis. serviceCollection.AddOpenAIService(r=>r.UseBeta = true); + +//serviceCollection.AddOpenAIService(); //// DeploymentId and ResourceName are only for Azure OpenAI. If you want to use Azure OpenAI services you have to set Provider type To Azure. //serviceCollection.AddOpenAIService(options => //{ @@ -44,16 +46,17 @@ //Assistants - BETA -await AssistantTestHelper.RunAssistantApiTest(sdk); +//await AssistantTestHelper.RunAssistantApiTest(sdk); //await AssistantTestHelper.RunHowAssistantsWorkTest(sdk); -await MessageTestHelper.RunMessageCreateTest(sdk); +//await MessageTestHelper.RunMessageCreateTest(sdk); + +//await ThreadTestHelper.RunThreadCreateTest(sdk); +//await ThreadTestHelper.RunThreadRetrieveTest(sdk); -await ThreadTestHelper.RunThreadCreateTest(sdk); -await ThreadTestHelper.RunThreadRetrieveTest(sdk); +//await RunTestHelper.RunRunCreateTest(sdk); +//await RunTestHelper.RunRunCancelTest(sdk); -await RunTestHelper.RunRunCreateTest(sdk); -await RunTestHelper.RunRunCancelTest(sdk); // Vision //await VisionTestHelper.RunSimpleVisionTest(sdk); //await VisionTestHelper.RunSimpleVisionStreamTest(sdk); diff --git a/Readme.md b/Readme.md index 8d41afef..09824272 100644 --- a/Readme.md +++ b/Readme.md @@ -54,11 +54,16 @@ var openAiService = new OpenAIService(new OpenAiOptions() "OpenAIServiceOptions": { //"ApiKey":"Your api key goes here" //,"Organization": "Your Organization Id goes here (optional)" + //,"UseBeta": "true/false (optional)" }, ``` *(How to use [user secret](https://docs.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-6.0&tabs=windows) ? Right click your project name in "solution explorer" then click "Manage User Secret", it is a good way to keep your api keys)* +### For Beta Features: +- Use `"UseBeta": true` in your config file or `serviceCollection.AddOpenAIService(r=>r.UseBeta = true);` or `new OpenAiOptions { UseBeta = true }` in your service registration. + + #### Program.cs ```csharp serviceCollection.AddOpenAIService(); @@ -283,6 +288,7 @@ If I forgot your name in change logs, please accept my apologies and let me know ## Changelog ### 8.0.2-beta - Added support for beta features, such as assistants, threads, messages, and run. Still missing some of the endpoints, but good progress achieved. See complete list from here: [Feature Availability Table](https://github.com/betalgo/openai/wiki/Feature-Availability). Thanks to @CongquanHu and @alistein. +- Use `"UseBeta": true` in your config file or `serviceCollection.AddOpenAIService(r=>r.UseBeta = true);` or `new OpenAiOptions { UseBeta = true }` in your service registration. ### 8.0.1 - Added support for new Models `gpt-4-turbo` and `gpt-4-turbo-2024-04-09` thanks to @ChaseIngersol ### 8.0.0