From c79550cc7543c5360014d5489866d8e62fb2a317 Mon Sep 17 00:00:00 2001 From: Konboi Date: Wed, 7 Feb 2024 14:52:10 +0900 Subject: [PATCH 01/40] fix indent and version --- .github/workflows/test.yml | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 830e797f..9472b4ad 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -7,17 +7,14 @@ on: jobs: test: runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - - name: Set up JDK 1.8 - uses: actions/setup-java@v3 - with: - distribution: temurin - java-version: 8 - - - name: Test - run: ./gradlew test --stacktrace - env: - OPENAI_TOKEN: ${{ secrets.OPENAI_TOKEN }} + - uses: actions/checkout@v4 + - name: Set up JDK 1.8 + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: 8 + - name: Test + run: ./gradlew test --stacktrace + env: + OPENAI_TOKEN: ${{ secrets.OPENAI_TOKEN }} From a051f45b594e886335aa20e6669589c39cb4edf7 Mon Sep 17 00:00:00 2001 From: Konboi Date: Wed, 7 Feb 2024 14:54:11 +0900 Subject: [PATCH 02/40] test on PR --- .github/workflows/test.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 9472b4ad..7eedd2d2 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -3,7 +3,8 @@ name: Test on: push: branches: [ main ] - + pull_request: + branches: [ main ] jobs: test: runs-on: ubuntu-latest From 00dd7caa07325ace164c4052919decb3274a68aa Mon Sep 17 00:00:00 2001 From: Konboi Date: Wed, 7 Feb 2024 15:26:44 +0900 Subject: [PATCH 03/40] for debug --- .github/workflows/test.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 7eedd2d2..ba858c55 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -17,5 +17,5 @@ jobs: java-version: 8 - name: Test run: ./gradlew test --stacktrace - env: - OPENAI_TOKEN: ${{ secrets.OPENAI_TOKEN }} + #env: + # OPENAI_TOKEN: ${{ secrets.OPENAI_TOKEN }} From ee903aa175e253959deb607f344527cdf78d1b6f Mon Sep 17 00:00:00 2001 From: Konboi Date: Wed, 7 Feb 2024 15:39:59 +0900 Subject: [PATCH 04/40] rename package from com.theokanning to com.launchableinc --- .../launchableinc/openai/DeleteResult.java | 25 ++++ .../openai/ListSearchParameters.java | 52 +++++++ .../com/launchableinc/openai/OpenAiError.java | 40 +++++ .../openai/OpenAiHttpException.java | 31 ++++ .../launchableinc/openai/OpenAiResponse.java | 41 +++++ .../java/com/launchableinc/openai/Usage.java | 29 ++++ .../openai/assistants/Assistant.java | 67 +++++++++ .../openai/assistants/AssistantFile.java | 30 ++++ .../assistants/AssistantFileRequest.java | 6 +- .../openai/assistants/AssistantFunction.java | 12 +- .../openai/assistants/AssistantRequest.java | 52 +++++++ .../openai/assistants/AssistantSortOrder.java | 12 ++ .../openai/assistants/AssistantToolsEnum.java | 15 ++ .../assistants/ModifyAssistantRequest.java | 51 +++++++ .../launchableinc/openai/assistants/Tool.java | 21 +++ .../openai/audio/CreateSpeechRequest.java | 45 ++++++ .../audio/CreateTranscriptionRequest.java | 49 ++++++ .../audio/CreateTranslationRequest.java | 43 ++++++ .../openai/audio/TranscriptionResult.java | 48 ++++++ .../openai/audio/TranscriptionSegment.java | 32 ++++ .../openai/audio/TranslationResult.java | 48 ++++++ .../openai/billing/BillingUsage.java | 28 ++++ .../openai/billing/CreditGrantsResponse.java | 35 +++++ .../openai/billing/DailyCost.java | 24 +++ .../launchableinc/openai/billing/Datum.java | 36 +++++ .../openai/billing/Grants.java | 10 +- .../openai/billing/LineItem.java | 21 +++ .../launchableinc/openai/billing/Plan.java | 13 ++ .../openai/billing/Subscription.java | 50 +++++++ .../openai/common/LastError.java | 10 +- .../openai/completion/CompletionChoice.java | 33 +++++ .../openai/completion/CompletionChunk.java | 39 +++++ .../openai/completion/CompletionRequest.java | 139 +++++++++++++++++ .../openai/completion/CompletionResult.java | 46 ++++++ .../openai/completion/LogProbResult.java | 40 +++++ .../completion/chat/ChatCompletionChoice.java | 29 ++++ .../completion/chat/ChatCompletionChunk.java | 37 +++++ .../chat/ChatCompletionRequest.java | 129 ++++++++++++++++ .../completion/chat/ChatCompletionResult.java | 44 ++++++ .../openai/completion/chat/ChatFunction.java | 72 +++++++++ .../completion/chat/ChatFunctionCall.java | 24 +++ .../completion/chat/ChatFunctionDynamic.java | 64 ++++++++ .../chat/ChatFunctionParameters.java | 27 ++++ .../completion/chat/ChatFunctionProperty.java | 26 ++++ .../openai/completion/chat/ChatMessage.java | 22 +-- .../completion/chat/ChatMessageRole.java | 21 +++ .../launchableinc/openai/edit/EditChoice.java | 22 +++ .../openai/edit/EditRequest.java | 56 +++++++ .../launchableinc/openai/edit/EditResult.java | 35 +++++ .../openai/edit/EditUsage.java | 0 .../openai/embedding/Embedding.java | 0 .../openai/embedding/EmbeddingRequest.java | 0 .../openai/embedding/EmbeddingResult.java | 0 .../openai/engine/Engine.java | 0 .../openai/file/File.java | 0 .../openai/fine_tuning/FineTuningEvent.java | 0 .../openai/fine_tuning/FineTuningJob.java | 0 .../fine_tuning/FineTuningJobRequest.java | 0 .../openai/fine_tuning/Hyperparameters.java | 0 .../openai/finetune/FineTuneEvent.java | 0 .../openai/finetune/FineTuneRequest.java | 0 .../openai/finetune/FineTuneResult.java | 0 .../openai/finetune/HyperParameters.java | 0 .../openai/image/CreateImageEditRequest.java | 0 .../openai/image/CreateImageRequest.java | 69 +++++++++ .../image/CreateImageVariationRequest.java | 0 .../openai/image/Image.java | 0 .../openai/image/ImageResult.java | 0 .../openai/messages/Message.java | 0 .../openai/messages/MessageContent.java | 0 .../openai/messages/MessageFile.java | 0 .../openai/messages/MessageRequest.java | 0 .../openai/messages/ModifyMessageRequest.java | 0 .../openai/messages/content/Annotation.java | 0 .../openai/messages/content/FileCitation.java | 0 .../openai/messages/content/FilePath.java | 0 .../openai/messages/content/ImageFile.java | 0 .../openai/messages/content/Text.java | 0 .../openai/model/Model.java | 0 .../openai/model/Permission.java | 0 .../openai/moderation/Moderation.java | 0 .../moderation/ModerationCategories.java | 0 .../moderation/ModerationCategoryScores.java | 0 .../openai/moderation/ModerationRequest.java | 0 .../openai/moderation/ModerationResult.java | 0 .../runs/CreateThreadAndRunRequest.java | 0 .../openai/runs/MessageCreation.java | 0 .../openai/runs/RequiredAction.java | 0 .../openai/runs/Run.java | 0 .../openai/runs/RunCreateRequest.java | 0 .../openai/runs/RunImage.java | 0 .../openai/runs/RunStep.java | 0 .../openai/runs/StepDetails.java | 0 .../runs/SubmitToolOutputRequestItem.java | 0 .../openai/runs/SubmitToolOutputs.java | 0 .../openai/runs/SubmitToolOutputsRequest.java | 0 .../openai/runs/ToolCall.java | 0 .../openai/runs/ToolCallCodeInterpreter.java | 0 .../runs/ToolCallCodeInterpreterOutput.java | 0 .../openai/runs/ToolCallFunction.java | 0 .../openai/threads/Thread.java | 0 .../openai/threads/ThreadRequest.java | 0 .../openai/utils/TikTokensUtil.java | 0 .../com/theokanning/openai/DeleteResult.java | 24 --- .../openai/ListSearchParameters.java | 51 ------- .../com/theokanning/openai/OpenAiError.java | 39 ----- .../openai/OpenAiHttpException.java | 31 ---- .../theokanning/openai/OpenAiResponse.java | 40 ----- .../java/com/theokanning/openai/Usage.java | 28 ---- .../openai/assistants/Assistant.java | 67 --------- .../openai/assistants/AssistantFile.java | 30 ---- .../openai/assistants/AssistantRequest.java | 52 ------- .../openai/assistants/AssistantSortOrder.java | 12 -- .../openai/assistants/AssistantToolsEnum.java | 15 -- .../assistants/ModifyAssistantRequest.java | 51 ------- .../theokanning/openai/assistants/Tool.java | 20 --- .../openai/audio/CreateSpeechRequest.java | 45 ------ .../audio/CreateTranscriptionRequest.java | 46 ------ .../audio/CreateTranslationRequest.java | 41 ----- .../openai/audio/TranscriptionResult.java | 44 ------ .../openai/audio/TranscriptionSegment.java | 32 ---- .../openai/audio/TranslationResult.java | 44 ------ .../openai/billing/BillingUsage.java | 29 ---- .../openai/billing/CreditGrantsResponse.java | 35 ----- .../theokanning/openai/billing/DailyCost.java | 24 --- .../com/theokanning/openai/billing/Datum.java | 36 ----- .../theokanning/openai/billing/LineItem.java | 21 --- .../com/theokanning/openai/billing/Plan.java | 13 -- .../openai/billing/Subscription.java | 51 ------- .../openai/completion/CompletionChoice.java | 31 ---- .../openai/completion/CompletionChunk.java | 37 ----- .../openai/completion/CompletionRequest.java | 140 ------------------ .../openai/completion/CompletionResult.java | 44 ------ .../openai/completion/LogProbResult.java | 40 ----- .../completion/chat/ChatCompletionChoice.java | 28 ---- .../completion/chat/ChatCompletionChunk.java | 35 ----- .../chat/ChatCompletionRequest.java | 121 --------------- .../completion/chat/ChatCompletionResult.java | 43 ------ .../openai/completion/chat/ChatFunction.java | 70 --------- .../completion/chat/ChatFunctionCall.java | 23 --- .../completion/chat/ChatFunctionDynamic.java | 62 -------- .../chat/ChatFunctionParameters.java | 27 ---- .../completion/chat/ChatFunctionProperty.java | 25 ---- .../completion/chat/ChatMessageRole.java | 21 --- .../theokanning/openai/edit/EditChoice.java | 22 --- .../theokanning/openai/edit/EditRequest.java | 57 ------- .../theokanning/openai/edit/EditResult.java | 35 ----- .../openai/image/CreateImageRequest.java | 60 -------- .../openai/JsonTest.java | 0 .../openai/ListSearchParameters.java | 52 +++++++ .../openai/AuthenticationInterceptor.java | 0 .../openai/OpenAiApi.java | 0 .../client/AuthenticationInterceptor.java | 0 .../openai/client/OpenAiApi.java | 0 .../service/AuthenticationInterceptor.java | 0 .../service/ChatCompletionRequestMixIn.java | 0 ...etionRequestSerializerAndDeserializer.java | 0 ...allArgumentsSerializerAndDeserializer.java | 0 .../openai/service/ChatFunctionCallMixIn.java | 0 .../openai/service/ChatFunctionMixIn.java | 0 .../ChatFunctionParametersSerializer.java | 0 .../service/ChatMessageAccumulator.java | 0 .../openai/service/FunctionExecutor.java | 0 .../openai/service/OpenAiService.java | 0 .../openai/service/ResponseBodyCallback.java | 0 .../openai/service/SSE.java | 0 .../openai/service/SSEFormatException.java | 0 .../openai/service/AssistantFunctionTest.java | 0 .../openai/service/AssistantTest.java | 0 .../openai/service/AudioTest.java | 0 .../openai/service/ChatCompletionTest.java | 0 .../openai/service/CompletionTest.java | 0 .../openai/service/EditTest.java | 0 .../openai/service/EmbeddingTest.java | 0 .../openai/service/FileTest.java | 0 .../openai/service/FineTuneTest.java | 0 .../openai/service/FineTuningTest.java | 0 .../openai/service/ImageTest.java | 0 .../openai/service/MessageTest.java | 0 .../openai/service/ModelTest.java | 0 .../openai/service/ModerationTest.java | 0 .../openai/service/OpenAiServiceTest.java | 0 .../service/ResponseBodyCallbackTest.java | 0 .../openai/service/RunTest.java | 0 .../openai/service/ThreadTest.java | 0 185 files changed, 1974 insertions(+), 1870 deletions(-) create mode 100644 api/src/main/java/com/launchableinc/openai/DeleteResult.java create mode 100644 api/src/main/java/com/launchableinc/openai/ListSearchParameters.java create mode 100644 api/src/main/java/com/launchableinc/openai/OpenAiError.java create mode 100644 api/src/main/java/com/launchableinc/openai/OpenAiHttpException.java create mode 100644 api/src/main/java/com/launchableinc/openai/OpenAiResponse.java create mode 100644 api/src/main/java/com/launchableinc/openai/Usage.java create mode 100644 api/src/main/java/com/launchableinc/openai/assistants/Assistant.java create mode 100644 api/src/main/java/com/launchableinc/openai/assistants/AssistantFile.java rename api/src/main/java/com/{theokanning => launchableinc}/openai/assistants/AssistantFileRequest.java (74%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/assistants/AssistantFunction.java (66%) create mode 100644 api/src/main/java/com/launchableinc/openai/assistants/AssistantRequest.java create mode 100644 api/src/main/java/com/launchableinc/openai/assistants/AssistantSortOrder.java create mode 100644 api/src/main/java/com/launchableinc/openai/assistants/AssistantToolsEnum.java create mode 100644 api/src/main/java/com/launchableinc/openai/assistants/ModifyAssistantRequest.java create mode 100644 api/src/main/java/com/launchableinc/openai/assistants/Tool.java create mode 100644 api/src/main/java/com/launchableinc/openai/audio/CreateSpeechRequest.java create mode 100644 api/src/main/java/com/launchableinc/openai/audio/CreateTranscriptionRequest.java create mode 100644 api/src/main/java/com/launchableinc/openai/audio/CreateTranslationRequest.java create mode 100644 api/src/main/java/com/launchableinc/openai/audio/TranscriptionResult.java create mode 100644 api/src/main/java/com/launchableinc/openai/audio/TranscriptionSegment.java create mode 100644 api/src/main/java/com/launchableinc/openai/audio/TranslationResult.java create mode 100644 api/src/main/java/com/launchableinc/openai/billing/BillingUsage.java create mode 100644 api/src/main/java/com/launchableinc/openai/billing/CreditGrantsResponse.java create mode 100644 api/src/main/java/com/launchableinc/openai/billing/DailyCost.java create mode 100644 api/src/main/java/com/launchableinc/openai/billing/Datum.java rename api/src/main/java/com/{theokanning => launchableinc}/openai/billing/Grants.java (52%) create mode 100644 api/src/main/java/com/launchableinc/openai/billing/LineItem.java create mode 100644 api/src/main/java/com/launchableinc/openai/billing/Plan.java create mode 100644 api/src/main/java/com/launchableinc/openai/billing/Subscription.java rename api/src/main/java/com/{theokanning => launchableinc}/openai/common/LastError.java (72%) create mode 100644 api/src/main/java/com/launchableinc/openai/completion/CompletionChoice.java create mode 100644 api/src/main/java/com/launchableinc/openai/completion/CompletionChunk.java create mode 100644 api/src/main/java/com/launchableinc/openai/completion/CompletionRequest.java create mode 100644 api/src/main/java/com/launchableinc/openai/completion/CompletionResult.java create mode 100644 api/src/main/java/com/launchableinc/openai/completion/LogProbResult.java create mode 100644 api/src/main/java/com/launchableinc/openai/completion/chat/ChatCompletionChoice.java create mode 100644 api/src/main/java/com/launchableinc/openai/completion/chat/ChatCompletionChunk.java create mode 100644 api/src/main/java/com/launchableinc/openai/completion/chat/ChatCompletionRequest.java create mode 100644 api/src/main/java/com/launchableinc/openai/completion/chat/ChatCompletionResult.java create mode 100644 api/src/main/java/com/launchableinc/openai/completion/chat/ChatFunction.java create mode 100644 api/src/main/java/com/launchableinc/openai/completion/chat/ChatFunctionCall.java create mode 100644 api/src/main/java/com/launchableinc/openai/completion/chat/ChatFunctionDynamic.java create mode 100644 api/src/main/java/com/launchableinc/openai/completion/chat/ChatFunctionParameters.java create mode 100644 api/src/main/java/com/launchableinc/openai/completion/chat/ChatFunctionProperty.java rename api/src/main/java/com/{theokanning => launchableinc}/openai/completion/chat/ChatMessage.java (63%) create mode 100644 api/src/main/java/com/launchableinc/openai/completion/chat/ChatMessageRole.java create mode 100644 api/src/main/java/com/launchableinc/openai/edit/EditChoice.java create mode 100644 api/src/main/java/com/launchableinc/openai/edit/EditRequest.java create mode 100644 api/src/main/java/com/launchableinc/openai/edit/EditResult.java rename api/src/main/java/com/{theokanning => launchableinc}/openai/edit/EditUsage.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/embedding/Embedding.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/embedding/EmbeddingRequest.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/embedding/EmbeddingResult.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/engine/Engine.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/file/File.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/fine_tuning/FineTuningEvent.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/fine_tuning/FineTuningJob.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/fine_tuning/FineTuningJobRequest.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/fine_tuning/Hyperparameters.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/finetune/FineTuneEvent.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/finetune/FineTuneRequest.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/finetune/FineTuneResult.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/finetune/HyperParameters.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/image/CreateImageEditRequest.java (100%) create mode 100644 api/src/main/java/com/launchableinc/openai/image/CreateImageRequest.java rename api/src/main/java/com/{theokanning => launchableinc}/openai/image/CreateImageVariationRequest.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/image/Image.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/image/ImageResult.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/messages/Message.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/messages/MessageContent.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/messages/MessageFile.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/messages/MessageRequest.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/messages/ModifyMessageRequest.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/messages/content/Annotation.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/messages/content/FileCitation.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/messages/content/FilePath.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/messages/content/ImageFile.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/messages/content/Text.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/model/Model.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/model/Permission.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/moderation/Moderation.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/moderation/ModerationCategories.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/moderation/ModerationCategoryScores.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/moderation/ModerationRequest.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/moderation/ModerationResult.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/runs/CreateThreadAndRunRequest.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/runs/MessageCreation.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/runs/RequiredAction.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/runs/Run.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/runs/RunCreateRequest.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/runs/RunImage.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/runs/RunStep.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/runs/StepDetails.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/runs/SubmitToolOutputRequestItem.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/runs/SubmitToolOutputs.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/runs/SubmitToolOutputsRequest.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/runs/ToolCall.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/runs/ToolCallCodeInterpreter.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/runs/ToolCallCodeInterpreterOutput.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/runs/ToolCallFunction.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/threads/Thread.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/threads/ThreadRequest.java (100%) rename api/src/main/java/com/{theokanning => launchableinc}/openai/utils/TikTokensUtil.java (100%) delete mode 100644 api/src/main/java/com/theokanning/openai/DeleteResult.java delete mode 100644 api/src/main/java/com/theokanning/openai/ListSearchParameters.java delete mode 100644 api/src/main/java/com/theokanning/openai/OpenAiError.java delete mode 100644 api/src/main/java/com/theokanning/openai/OpenAiHttpException.java delete mode 100644 api/src/main/java/com/theokanning/openai/OpenAiResponse.java delete mode 100644 api/src/main/java/com/theokanning/openai/Usage.java delete mode 100644 api/src/main/java/com/theokanning/openai/assistants/Assistant.java delete mode 100644 api/src/main/java/com/theokanning/openai/assistants/AssistantFile.java delete mode 100644 api/src/main/java/com/theokanning/openai/assistants/AssistantRequest.java delete mode 100644 api/src/main/java/com/theokanning/openai/assistants/AssistantSortOrder.java delete mode 100644 api/src/main/java/com/theokanning/openai/assistants/AssistantToolsEnum.java delete mode 100644 api/src/main/java/com/theokanning/openai/assistants/ModifyAssistantRequest.java delete mode 100644 api/src/main/java/com/theokanning/openai/assistants/Tool.java delete mode 100644 api/src/main/java/com/theokanning/openai/audio/CreateSpeechRequest.java delete mode 100644 api/src/main/java/com/theokanning/openai/audio/CreateTranscriptionRequest.java delete mode 100644 api/src/main/java/com/theokanning/openai/audio/CreateTranslationRequest.java delete mode 100644 api/src/main/java/com/theokanning/openai/audio/TranscriptionResult.java delete mode 100644 api/src/main/java/com/theokanning/openai/audio/TranscriptionSegment.java delete mode 100644 api/src/main/java/com/theokanning/openai/audio/TranslationResult.java delete mode 100644 api/src/main/java/com/theokanning/openai/billing/BillingUsage.java delete mode 100644 api/src/main/java/com/theokanning/openai/billing/CreditGrantsResponse.java delete mode 100644 api/src/main/java/com/theokanning/openai/billing/DailyCost.java delete mode 100644 api/src/main/java/com/theokanning/openai/billing/Datum.java delete mode 100644 api/src/main/java/com/theokanning/openai/billing/LineItem.java delete mode 100644 api/src/main/java/com/theokanning/openai/billing/Plan.java delete mode 100644 api/src/main/java/com/theokanning/openai/billing/Subscription.java delete mode 100644 api/src/main/java/com/theokanning/openai/completion/CompletionChoice.java delete mode 100644 api/src/main/java/com/theokanning/openai/completion/CompletionChunk.java delete mode 100644 api/src/main/java/com/theokanning/openai/completion/CompletionRequest.java delete mode 100644 api/src/main/java/com/theokanning/openai/completion/CompletionResult.java delete mode 100644 api/src/main/java/com/theokanning/openai/completion/LogProbResult.java delete mode 100644 api/src/main/java/com/theokanning/openai/completion/chat/ChatCompletionChoice.java delete mode 100644 api/src/main/java/com/theokanning/openai/completion/chat/ChatCompletionChunk.java delete mode 100644 api/src/main/java/com/theokanning/openai/completion/chat/ChatCompletionRequest.java delete mode 100644 api/src/main/java/com/theokanning/openai/completion/chat/ChatCompletionResult.java delete mode 100644 api/src/main/java/com/theokanning/openai/completion/chat/ChatFunction.java delete mode 100644 api/src/main/java/com/theokanning/openai/completion/chat/ChatFunctionCall.java delete mode 100644 api/src/main/java/com/theokanning/openai/completion/chat/ChatFunctionDynamic.java delete mode 100644 api/src/main/java/com/theokanning/openai/completion/chat/ChatFunctionParameters.java delete mode 100644 api/src/main/java/com/theokanning/openai/completion/chat/ChatFunctionProperty.java delete mode 100644 api/src/main/java/com/theokanning/openai/completion/chat/ChatMessageRole.java delete mode 100644 api/src/main/java/com/theokanning/openai/edit/EditChoice.java delete mode 100644 api/src/main/java/com/theokanning/openai/edit/EditRequest.java delete mode 100644 api/src/main/java/com/theokanning/openai/edit/EditResult.java delete mode 100644 api/src/main/java/com/theokanning/openai/image/CreateImageRequest.java rename api/src/test/java/com/{theokanning => launchableinc}/openai/JsonTest.java (100%) create mode 100644 api/src/test/java/com/launchableinc/openai/ListSearchParameters.java rename client/src/main/java/com/{theokanning => launchableinc}/openai/AuthenticationInterceptor.java (100%) rename client/src/main/java/com/{theokanning => launchableinc}/openai/OpenAiApi.java (100%) rename client/src/main/java/com/{theokanning => launchableinc}/openai/client/AuthenticationInterceptor.java (100%) rename client/src/main/java/com/{theokanning => launchableinc}/openai/client/OpenAiApi.java (100%) rename service/src/main/java/com/{theokanning => launchableinc}/openai/service/AuthenticationInterceptor.java (100%) rename service/src/main/java/com/{theokanning => launchableinc}/openai/service/ChatCompletionRequestMixIn.java (100%) rename service/src/main/java/com/{theokanning => launchableinc}/openai/service/ChatCompletionRequestSerializerAndDeserializer.java (100%) rename service/src/main/java/com/{theokanning => launchableinc}/openai/service/ChatFunctionCallArgumentsSerializerAndDeserializer.java (100%) rename service/src/main/java/com/{theokanning => launchableinc}/openai/service/ChatFunctionCallMixIn.java (100%) rename service/src/main/java/com/{theokanning => launchableinc}/openai/service/ChatFunctionMixIn.java (100%) rename service/src/main/java/com/{theokanning => launchableinc}/openai/service/ChatFunctionParametersSerializer.java (100%) rename service/src/main/java/com/{theokanning => launchableinc}/openai/service/ChatMessageAccumulator.java (100%) rename service/src/main/java/com/{theokanning => launchableinc}/openai/service/FunctionExecutor.java (100%) rename service/src/main/java/com/{theokanning => launchableinc}/openai/service/OpenAiService.java (100%) rename service/src/main/java/com/{theokanning => launchableinc}/openai/service/ResponseBodyCallback.java (100%) rename service/src/main/java/com/{theokanning => launchableinc}/openai/service/SSE.java (100%) rename service/src/main/java/com/{theokanning => launchableinc}/openai/service/SSEFormatException.java (100%) rename service/src/test/java/com/{theokanning => launchableinc}/openai/service/AssistantFunctionTest.java (100%) rename service/src/test/java/com/{theokanning => launchableinc}/openai/service/AssistantTest.java (100%) rename service/src/test/java/com/{theokanning => launchableinc}/openai/service/AudioTest.java (100%) rename service/src/test/java/com/{theokanning => launchableinc}/openai/service/ChatCompletionTest.java (100%) rename service/src/test/java/com/{theokanning => launchableinc}/openai/service/CompletionTest.java (100%) rename service/src/test/java/com/{theokanning => launchableinc}/openai/service/EditTest.java (100%) rename service/src/test/java/com/{theokanning => launchableinc}/openai/service/EmbeddingTest.java (100%) rename service/src/test/java/com/{theokanning => launchableinc}/openai/service/FileTest.java (100%) rename service/src/test/java/com/{theokanning => launchableinc}/openai/service/FineTuneTest.java (100%) rename service/src/test/java/com/{theokanning => launchableinc}/openai/service/FineTuningTest.java (100%) rename service/src/test/java/com/{theokanning => launchableinc}/openai/service/ImageTest.java (100%) rename service/src/test/java/com/{theokanning => launchableinc}/openai/service/MessageTest.java (100%) rename service/src/test/java/com/{theokanning => launchableinc}/openai/service/ModelTest.java (100%) rename service/src/test/java/com/{theokanning => launchableinc}/openai/service/ModerationTest.java (100%) rename service/src/test/java/com/{theokanning => launchableinc}/openai/service/OpenAiServiceTest.java (100%) rename service/src/test/java/com/{theokanning => launchableinc}/openai/service/ResponseBodyCallbackTest.java (100%) rename service/src/test/java/com/{theokanning => launchableinc}/openai/service/RunTest.java (100%) rename service/src/test/java/com/{theokanning => launchableinc}/openai/service/ThreadTest.java (100%) diff --git a/api/src/main/java/com/launchableinc/openai/DeleteResult.java b/api/src/main/java/com/launchableinc/openai/DeleteResult.java new file mode 100644 index 00000000..6668bded --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/DeleteResult.java @@ -0,0 +1,25 @@ +package com.launchableinc.openai; + +import lombok.Data; + +/** + * A response when deleting an object + */ +@Data +public class DeleteResult { + + /** + * The id of the object. + */ + String id; + + /** + * The type of object deleted, for example "file" or "model" + */ + String object; + + /** + * True if successfully deleted + */ + boolean deleted; +} diff --git a/api/src/main/java/com/launchableinc/openai/ListSearchParameters.java b/api/src/main/java/com/launchableinc/openai/ListSearchParameters.java new file mode 100644 index 00000000..15b12b07 --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/ListSearchParameters.java @@ -0,0 +1,52 @@ +package com.launchableinc.openai; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * Common options when getting a list of objects + */ +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Data +public class ListSearchParameters { + + /** + * A limit on the number of objects to be returned. Limit can range between 1 and 100, and the + * default is 20 + */ + + Integer limit; + + /** + * Sort order by the 'created_at' timestamp of the objects. 'asc' for ascending order and 'desc' + * for descending order. + */ + Order order; + + /** + * 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 + */ + String after; + + /** + * 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. + */ + String before; + + public enum Order { + @JsonProperty("asc") + ASCENDING, + + @JsonProperty("desc") + DESCENDING + } +} diff --git a/api/src/main/java/com/launchableinc/openai/OpenAiError.java b/api/src/main/java/com/launchableinc/openai/OpenAiError.java new file mode 100644 index 00000000..b2063bf3 --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/OpenAiError.java @@ -0,0 +1,40 @@ +package com.launchableinc.openai; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * Represents the error body when an OpenAI request fails + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class OpenAiError { + + public OpenAiErrorDetails error; + + @Data + @NoArgsConstructor + @AllArgsConstructor + public static class OpenAiErrorDetails { + + /** + * Human-readable error message + */ + String message; + + /** + * OpenAI error type, for example "invalid_request_error" + * https://platform.openai.com/docs/guides/error-codes/python-library-error-types + */ + String type; + + String param; + + /** + * OpenAI error code, for example "invalid_api_key" + */ + String code; + } +} diff --git a/api/src/main/java/com/launchableinc/openai/OpenAiHttpException.java b/api/src/main/java/com/launchableinc/openai/OpenAiHttpException.java new file mode 100644 index 00000000..87b60dae --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/OpenAiHttpException.java @@ -0,0 +1,31 @@ +package com.launchableinc.openai; + +public class OpenAiHttpException extends RuntimeException { + + /** + * HTTP status code + */ + public final int statusCode; + + /** + * OpenAI error code, for example "invalid_api_key" + */ + public final String code; + + + public final String param; + + /** + * OpenAI error type, for example "invalid_request_error" + * https://platform.openai.com/docs/guides/error-codes/python-library-error-types + */ + public final String type; + + public OpenAiHttpException(OpenAiError error, Exception parent, int statusCode) { + super(error.error.message, parent); + this.statusCode = statusCode; + this.code = error.error.code; + this.param = error.error.param; + this.type = error.error.type; + } +} diff --git a/api/src/main/java/com/launchableinc/openai/OpenAiResponse.java b/api/src/main/java/com/launchableinc/openai/OpenAiResponse.java new file mode 100644 index 00000000..6c97306a --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/OpenAiResponse.java @@ -0,0 +1,41 @@ +package com.launchableinc.openai; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +import java.util.List; + +/** + * A wrapper class to fit the OpenAI engine and search endpoints + */ +@Data +public class OpenAiResponse { + + /** + * A list containing the actual results + */ + public List data; + + /** + * The type of object returned, should be "list" + */ + public String object; + + /** + * The first id included + */ + @JsonProperty("first_id") + public String firstId; + + /** + * The last id included + */ + @JsonProperty("last_id") + public String lastId; + + /** + * True if there are objects after lastId + */ + @JsonProperty("has_more") + public boolean hasMore; +} diff --git a/api/src/main/java/com/launchableinc/openai/Usage.java b/api/src/main/java/com/launchableinc/openai/Usage.java new file mode 100644 index 00000000..57734fa4 --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/Usage.java @@ -0,0 +1,29 @@ +package com.launchableinc.openai; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +/** + * The OpenAI resources used by a request + */ +@Data +public class Usage { + + /** + * The number of prompt tokens used. + */ + @JsonProperty("prompt_tokens") + long promptTokens; + + /** + * The number of completion tokens used. + */ + @JsonProperty("completion_tokens") + long completionTokens; + + /** + * The number of total tokens used + */ + @JsonProperty("total_tokens") + long totalTokens; +} diff --git a/api/src/main/java/com/launchableinc/openai/assistants/Assistant.java b/api/src/main/java/com/launchableinc/openai/assistants/Assistant.java new file mode 100644 index 00000000..afe494db --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/assistants/Assistant.java @@ -0,0 +1,67 @@ +package com.launchableinc.openai.assistants; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.*; + +import java.util.List; +import java.util.Map; + +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Data +public class Assistant { + + /** + * The identifier, which can be referenced in API endpoints. + */ + String id; + + /** + * The object type which is always 'assistant' + */ + String object; + + /** + * The Unix timestamp(in seconds) for when the assistant was created + */ + @JsonProperty("created_at") + Integer createdAt; + + /** + * The name of the assistant. The maximum length is 256 + */ + String name; + + /** + * The description of the assistant. + */ + String description; + + /** + * ID of the model to use + */ + @NonNull + String model; + + /** + * The system instructions that the assistant uses. + */ + String instructions; + + /** + * A list of tools enabled on the assistant. + */ + List tools; + + /** + * A list of file IDs attached to this assistant. + */ + @JsonProperty("file_ids") + List fileIds; + + /** + * Set of 16 key-value pairs that can be attached to an object. + */ + Map metadata; +} diff --git a/api/src/main/java/com/launchableinc/openai/assistants/AssistantFile.java b/api/src/main/java/com/launchableinc/openai/assistants/AssistantFile.java new file mode 100644 index 00000000..67edd270 --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/assistants/AssistantFile.java @@ -0,0 +1,30 @@ +package com.launchableinc.openai.assistants; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +@Data +public class AssistantFile { + + /** + * The identifier of the Assistant File + */ + String id; + + /** + * The object type, which is always assistant.file. + */ + String object; + + /** + * The Unix timestamp (in seconds) for when the assistant file was created. + */ + @JsonProperty("created_at") + String createdAt; + + /** + * The assistant ID that the file is attached to + */ + @JsonProperty("assistant_id") + String assistantId; +} diff --git a/api/src/main/java/com/theokanning/openai/assistants/AssistantFileRequest.java b/api/src/main/java/com/launchableinc/openai/assistants/AssistantFileRequest.java similarity index 74% rename from api/src/main/java/com/theokanning/openai/assistants/AssistantFileRequest.java rename to api/src/main/java/com/launchableinc/openai/assistants/AssistantFileRequest.java index 98ee009f..d997374a 100644 --- a/api/src/main/java/com/theokanning/openai/assistants/AssistantFileRequest.java +++ b/api/src/main/java/com/launchableinc/openai/assistants/AssistantFileRequest.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.assistants; +package com.launchableinc.openai.assistants; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; @@ -12,6 +12,6 @@ @Data public class AssistantFileRequest { - @JsonProperty("file_id") - String fileId; + @JsonProperty("file_id") + String fileId; } diff --git a/api/src/main/java/com/theokanning/openai/assistants/AssistantFunction.java b/api/src/main/java/com/launchableinc/openai/assistants/AssistantFunction.java similarity index 66% rename from api/src/main/java/com/theokanning/openai/assistants/AssistantFunction.java rename to api/src/main/java/com/launchableinc/openai/assistants/AssistantFunction.java index 3abee5ae..10a8d463 100644 --- a/api/src/main/java/com/theokanning/openai/assistants/AssistantFunction.java +++ b/api/src/main/java/com/launchableinc/openai/assistants/AssistantFunction.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.assistants; +package com.launchableinc.openai.assistants; import lombok.AllArgsConstructor; import lombok.Builder; @@ -20,9 +20,9 @@ @Data public class AssistantFunction { - private String description; - - private String name; - - private Map parameters; + private String description; + + private String name; + + private Map parameters; } diff --git a/api/src/main/java/com/launchableinc/openai/assistants/AssistantRequest.java b/api/src/main/java/com/launchableinc/openai/assistants/AssistantRequest.java new file mode 100644 index 00000000..69f3e34d --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/assistants/AssistantRequest.java @@ -0,0 +1,52 @@ +package com.launchableinc.openai.assistants; + + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.*; + +import java.util.List; +import java.util.Map; + +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Data +public class AssistantRequest { + + /** + * ID of the model to use + */ + @NonNull + String model; + + /** + * The name of the assistant. The maximum length is 256 + */ + String name; + + /** + * The description of the assistant. + */ + String description; + + /** + * The system instructions that the assistant uses. + */ + String instructions; + + /** + * A list of tools enabled on the assistant. + */ + List tools; + + /** + * A list of file IDs attached to this assistant. + */ + @JsonProperty("file_ids") + List fileIds; + + /** + * Set of 16 key-value pairs that can be attached to an object. + */ + Map metadata; +} diff --git a/api/src/main/java/com/launchableinc/openai/assistants/AssistantSortOrder.java b/api/src/main/java/com/launchableinc/openai/assistants/AssistantSortOrder.java new file mode 100644 index 00000000..c8d96dc4 --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/assistants/AssistantSortOrder.java @@ -0,0 +1,12 @@ +package com.launchableinc.openai.assistants; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public enum AssistantSortOrder { + + @JsonProperty("asc") + ASC, + + @JsonProperty("desc") + DESC +} diff --git a/api/src/main/java/com/launchableinc/openai/assistants/AssistantToolsEnum.java b/api/src/main/java/com/launchableinc/openai/assistants/AssistantToolsEnum.java new file mode 100644 index 00000000..c969e264 --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/assistants/AssistantToolsEnum.java @@ -0,0 +1,15 @@ +package com.launchableinc.openai.assistants; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public enum AssistantToolsEnum { + + @JsonProperty("code_interpreter") + CODE_INTERPRETER, + + @JsonProperty("function") + FUNCTION, + + @JsonProperty("retrieval") + RETRIEVAL +} diff --git a/api/src/main/java/com/launchableinc/openai/assistants/ModifyAssistantRequest.java b/api/src/main/java/com/launchableinc/openai/assistants/ModifyAssistantRequest.java new file mode 100644 index 00000000..158ca3f6 --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/assistants/ModifyAssistantRequest.java @@ -0,0 +1,51 @@ +package com.launchableinc.openai.assistants; + + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.*; + +import java.util.List; +import java.util.Map; + +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Data +public class ModifyAssistantRequest { + + /** + * ID of the model to use + */ + String model; + + /** + * The name of the assistant. The maximum length is 256 + */ + String name; + + /** + * The description of the assistant. + */ + String description; + + /** + * The system instructions that the assistant uses. + */ + String instructions; + + /** + * A list of tools enabled on the assistant. + */ + List tools; + + /** + * A list of file IDs attached to this assistant. + */ + @JsonProperty("file_ids") + List fileIds; + + /** + * Set of 16 key-value pairs that can be attached to an object. + */ + Map metadata; +} diff --git a/api/src/main/java/com/launchableinc/openai/assistants/Tool.java b/api/src/main/java/com/launchableinc/openai/assistants/Tool.java new file mode 100644 index 00000000..5825148b --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/assistants/Tool.java @@ -0,0 +1,21 @@ +package com.launchableinc.openai.assistants; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@NoArgsConstructor +@AllArgsConstructor +@Data +public class Tool { + + /** + * The type of tool being defined + */ + AssistantToolsEnum type; + + /** + * Function definition, only used if type is "function" + */ + AssistantFunction function; +} diff --git a/api/src/main/java/com/launchableinc/openai/audio/CreateSpeechRequest.java b/api/src/main/java/com/launchableinc/openai/audio/CreateSpeechRequest.java new file mode 100644 index 00000000..177d3265 --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/audio/CreateSpeechRequest.java @@ -0,0 +1,45 @@ +package com.launchableinc.openai.audio; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.NonNull; + +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Data +public class CreateSpeechRequest { + + /** + * The name of the model to use. + */ + @NonNull + String model; + + /** + * The text to generate audio for. The maximum length is 4096 characters. + */ + @NonNull + String input; + + /** + * The voice to use when generating the audio. + */ + @NonNull + String voice; + + /** + * The format to audio in. Supported formats are mp3, opus, aac, and flac. Defaults to mp3. + */ + @JsonProperty("response_format") + String responseFormat; + + /** + * The speed of the generated audio. Select a value from 0.25 to 4.0. Defaults to 1.0. + */ + Double speed; +} diff --git a/api/src/main/java/com/launchableinc/openai/audio/CreateTranscriptionRequest.java b/api/src/main/java/com/launchableinc/openai/audio/CreateTranscriptionRequest.java new file mode 100644 index 00000000..98201d10 --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/audio/CreateTranscriptionRequest.java @@ -0,0 +1,49 @@ +package com.launchableinc.openai.audio; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.*; + +/** + * A request for OpenAi to create transcription based on an audio file All fields except model are + * optional + *

+ * https://platform.openai.com/docs/api-reference/audio/create + */ +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Data +public class CreateTranscriptionRequest { + + /** + * The name of the model to use. + */ + @NonNull + String model; + + /** + * An optional text to guide the model's style or continue a previous audio segment. The prompt + * should match the audio language. + */ + String prompt; + + /** + * The format of the transcript output, in one of these options: json or verbose_json + */ + @JsonProperty("response_format") + String responseFormat; + + /** + * The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more + * random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, + * the model will use log probability to automatically increase the temperature until certain + * thresholds are hit. + */ + Double temperature; + + /** + * The language of the input audio. Supplying the input language in ISO-639-1 format will improve + * accuracy and latency. + */ + String language; +} diff --git a/api/src/main/java/com/launchableinc/openai/audio/CreateTranslationRequest.java b/api/src/main/java/com/launchableinc/openai/audio/CreateTranslationRequest.java new file mode 100644 index 00000000..1c099639 --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/audio/CreateTranslationRequest.java @@ -0,0 +1,43 @@ +package com.launchableinc.openai.audio; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.*; + +/** + * A request for OpenAi to create English translation based on an audio file All fields except model + * are optional + *

+ * https://platform.openai.com/docs/api-reference/audio/create + */ +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Data +public class CreateTranslationRequest { + + /** + * The name of the model to use. + */ + @NonNull + String model; + + /** + * An optional text to guide the model's style or continue a previous audio segment. The prompt + * should be in English. + */ + String prompt; + + /** + * The format of the translated output, in one of these options: json or verbose_json + */ + @JsonProperty("response_format") + String responseFormat; + + /** + * The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more + * random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, + * the model will use log probability to automatically increase the temperature until certain + * thresholds are hit. + */ + Double temperature; +} diff --git a/api/src/main/java/com/launchableinc/openai/audio/TranscriptionResult.java b/api/src/main/java/com/launchableinc/openai/audio/TranscriptionResult.java new file mode 100644 index 00000000..2c3cdebd --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/audio/TranscriptionResult.java @@ -0,0 +1,48 @@ +package com.launchableinc.openai.audio; + +import lombok.Data; + +import java.util.List; + +/** + * An object with the text transcription + *

+ * https://platform.openai.com/docs/api-reference/audio/create + */ +@Data +public class TranscriptionResult { + + /** + * The text transcription. + */ + String text; + + /** + * Task name + * + * @apiNote verbose_json response format only + */ + String task; + + /** + * Speech language + * + * @apiNote verbose_json response format only + */ + String language; + + /** + * Speech duration + * + * @apiNote verbose_json response format only + */ + Double duration; + + /** + * List of segments + * + * @apiNote verbose_json response format only + */ + List segments; + +} diff --git a/api/src/main/java/com/launchableinc/openai/audio/TranscriptionSegment.java b/api/src/main/java/com/launchableinc/openai/audio/TranscriptionSegment.java new file mode 100644 index 00000000..1d601c80 --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/audio/TranscriptionSegment.java @@ -0,0 +1,32 @@ +package com.launchableinc.openai.audio; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +import java.util.List; + +/** + * An object represents transcription segment + *

+ * https://platform.openai.com/docs/api-reference/audio/create + */ +@Data +public class TranscriptionSegment { + + Integer id; + Integer seek; + Double start; + Double end; + String text; + List tokens; + Double temperature; + @JsonProperty("avg_logprob") + Double averageLogProb; + @JsonProperty("compression_ratio") + Double compressionRatio; + @JsonProperty("no_speech_prob") + Double noSpeechProb; + @JsonProperty("transient") + Boolean transientFlag; + +} diff --git a/api/src/main/java/com/launchableinc/openai/audio/TranslationResult.java b/api/src/main/java/com/launchableinc/openai/audio/TranslationResult.java new file mode 100644 index 00000000..86d389da --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/audio/TranslationResult.java @@ -0,0 +1,48 @@ +package com.launchableinc.openai.audio; + +import lombok.Data; + +import java.util.List; + +/** + * An object with the English transcription + *

+ * https://platform.openai.com/docs/api-reference/audio/create + */ +@Data +public class TranslationResult { + + /** + * Translated text. + */ + String text; + + /** + * Task name + * + * @apiNote verbose_json response format only + */ + String task; + + /** + * Translated language + * + * @apiNote verbose_json response format only + */ + String language; + + /** + * Speech duration + * + * @apiNote verbose_json response format only + */ + Double duration; + + /** + * List of segments + * + * @apiNote verbose_json response format only + */ + List segments; + +} diff --git a/api/src/main/java/com/launchableinc/openai/billing/BillingUsage.java b/api/src/main/java/com/launchableinc/openai/billing/BillingUsage.java new file mode 100644 index 00000000..39617a34 --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/billing/BillingUsage.java @@ -0,0 +1,28 @@ +package com.launchableinc.openai.billing; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +import java.math.BigDecimal; +import java.util.List; + +/** + * Amount consumption information + */ +@Data +public class BillingUsage { + + @JsonProperty("object") + private String object; + /** + * Account expenditure details + */ + @JsonProperty("daily_costs") + private List dailyCosts; + /** + * Total usage amount: cents + */ + @JsonProperty("total_usage") + private BigDecimal totalUsage; + +} diff --git a/api/src/main/java/com/launchableinc/openai/billing/CreditGrantsResponse.java b/api/src/main/java/com/launchableinc/openai/billing/CreditGrantsResponse.java new file mode 100644 index 00000000..829be6a8 --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/billing/CreditGrantsResponse.java @@ -0,0 +1,35 @@ +package com.launchableinc.openai.billing; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +import java.io.Serializable; +import java.math.BigDecimal; + +/** + * Return value of balance inquiry interface + */ +@Data +public class CreditGrantsResponse implements Serializable { + + private String object; + /** + * Total amount: US dollars + */ + @JsonProperty("total_granted") + private BigDecimal totalGranted; + /** + * Total usage amount: US dollars + */ + @JsonProperty("total_used") + private BigDecimal totalUsed; + /** + * Total remaining amount: US dollars + */ + @JsonProperty("total_available") + private BigDecimal totalAvailable; + /** + * Balance details + */ + private Grants grants; +} diff --git a/api/src/main/java/com/launchableinc/openai/billing/DailyCost.java b/api/src/main/java/com/launchableinc/openai/billing/DailyCost.java new file mode 100644 index 00000000..df24053c --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/billing/DailyCost.java @@ -0,0 +1,24 @@ +package com.launchableinc.openai.billing; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +import java.util.List; + +/** + * List of amount consumption + */ +@Data +public class DailyCost { + + /** + * + */ + @JsonProperty("timestamp") + private long timestamp; + /** + * Model consumption amount details + */ + @JsonProperty("line_items") + private List lineItems; +} diff --git a/api/src/main/java/com/launchableinc/openai/billing/Datum.java b/api/src/main/java/com/launchableinc/openai/billing/Datum.java new file mode 100644 index 00000000..121d537e --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/billing/Datum.java @@ -0,0 +1,36 @@ +package com.launchableinc.openai.billing; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +import java.math.BigDecimal; + +/** + * + */ +@Data +public class Datum { + + private String object; + private String id; + /** + * Gift amount: US dollars + */ + @JsonProperty("grant_amount") + private BigDecimal grantAmount; + /** + * Usage amount: US dollars + */ + @JsonProperty("used_amount") + private BigDecimal usedAmount; + /** + * Effective timestamp + */ + @JsonProperty("effective_at") + private Long effectiveAt; + /** + * Expiration timestamp + */ + @JsonProperty("expires_at") + private Long expiresAt; +} diff --git a/api/src/main/java/com/theokanning/openai/billing/Grants.java b/api/src/main/java/com/launchableinc/openai/billing/Grants.java similarity index 52% rename from api/src/main/java/com/theokanning/openai/billing/Grants.java rename to api/src/main/java/com/launchableinc/openai/billing/Grants.java index 8826f04a..f1fe3c33 100644 --- a/api/src/main/java/com/theokanning/openai/billing/Grants.java +++ b/api/src/main/java/com/launchableinc/openai/billing/Grants.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.billing; +package com.launchableinc.openai.billing; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; @@ -6,12 +6,12 @@ import java.util.List; /** - * * */ @Data public class Grants { - private String object; - @JsonProperty("data") - private List data; + + private String object; + @JsonProperty("data") + private List data; } diff --git a/api/src/main/java/com/launchableinc/openai/billing/LineItem.java b/api/src/main/java/com/launchableinc/openai/billing/LineItem.java new file mode 100644 index 00000000..1507a9e4 --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/billing/LineItem.java @@ -0,0 +1,21 @@ +package com.launchableinc.openai.billing; + +import lombok.Data; + +import java.math.BigDecimal; + +/** + * List of amount consumption + */ +@Data +public class LineItem { + + /** + * model name + */ + private String name; + /** + * Expenditure amount + */ + private BigDecimal cost; +} diff --git a/api/src/main/java/com/launchableinc/openai/billing/Plan.java b/api/src/main/java/com/launchableinc/openai/billing/Plan.java new file mode 100644 index 00000000..5c8d1704 --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/billing/Plan.java @@ -0,0 +1,13 @@ +package com.launchableinc.openai.billing; + +import lombok.Data; + +/** + * + */ +@Data +public class Plan { + + private String title; + private String id; +} diff --git a/api/src/main/java/com/launchableinc/openai/billing/Subscription.java b/api/src/main/java/com/launchableinc/openai/billing/Subscription.java new file mode 100644 index 00000000..6a733d77 --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/billing/Subscription.java @@ -0,0 +1,50 @@ +package com.launchableinc.openai.billing; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +/** + * Account information + */ +@Data +public class Subscription { + + @JsonProperty("object") + private String object; + @JsonProperty("has_payment_method") + private boolean hasPaymentMethod; + @JsonProperty("canceled") + private boolean canceled; + @JsonProperty("canceled_at") + private Object canceledAt; + @JsonProperty("delinquent") + private Object delinquent; + @JsonProperty("access_until") + private long accessUntil; + @JsonProperty("soft_limit") + private long softLimit; + @JsonProperty("hard_limit") + private long hardLimit; + @JsonProperty("system_hard_limit") + private long systemHardLimit; + @JsonProperty("soft_limit_usd") + private double softLimitUsd; + @JsonProperty("hard_limit_usd") + private double hardLimitUsd; + @JsonProperty("system_hard_limit_usd") + private double systemHardLimitUsd; + @JsonProperty("plan") + private Plan plan; + @JsonProperty("account_name") + private String accountName; + @JsonProperty("po_number") + private Object poNumber; + @JsonProperty("billing_email") + private Object billingEmail; + @JsonProperty("tax_ids") + private Object taxIds; + @JsonProperty("billing_address") + private Object billingAddress; + @JsonProperty("business_address") + private Object businessAddress; +} diff --git a/api/src/main/java/com/theokanning/openai/common/LastError.java b/api/src/main/java/com/launchableinc/openai/common/LastError.java similarity index 72% rename from api/src/main/java/com/theokanning/openai/common/LastError.java rename to api/src/main/java/com/launchableinc/openai/common/LastError.java index 6a9f99de..7ec484d5 100644 --- a/api/src/main/java/com/theokanning/openai/common/LastError.java +++ b/api/src/main/java/com/launchableinc/openai/common/LastError.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.common; +package com.launchableinc.openai.common; import lombok.AllArgsConstructor; import lombok.Builder; @@ -17,8 +17,8 @@ @NoArgsConstructor @AllArgsConstructor public class LastError { - - private String code; - - private String message; + + private String code; + + private String message; } diff --git a/api/src/main/java/com/launchableinc/openai/completion/CompletionChoice.java b/api/src/main/java/com/launchableinc/openai/completion/CompletionChoice.java new file mode 100644 index 00000000..75ee0095 --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/completion/CompletionChoice.java @@ -0,0 +1,33 @@ +package com.launchableinc.openai.completion; + +import lombok.Data; + +/** + * A completion generated by OpenAI + *

+ * https://beta.openai.com/docs/api-reference/completions/create + */ +@Data +public class CompletionChoice { + + /** + * The generated text. Will include the prompt if {@link CompletionRequest#echo } is true + */ + String text; + + /** + * This index of this completion in the returned list. + */ + Integer index; + + /** + * The log probabilities of the chosen tokens and the top {@link CompletionRequest#logprobs} + * tokens + */ + LogProbResult logprobs; + + /** + * The reason why GPT stopped generating, for example "length". + */ + String finish_reason; +} diff --git a/api/src/main/java/com/launchableinc/openai/completion/CompletionChunk.java b/api/src/main/java/com/launchableinc/openai/completion/CompletionChunk.java new file mode 100644 index 00000000..83753720 --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/completion/CompletionChunk.java @@ -0,0 +1,39 @@ +package com.launchableinc.openai.completion; + +import lombok.Data; +import java.util.List; + +/** + * Object containing a response chunk from the completions streaming api. + *

+ * https://beta.openai.com/docs/api-reference/completions/create + */ +@Data +public class CompletionChunk { + + /** + * A unique id assigned to this completion. + */ + String id; + + /** + * https://beta.openai.com/docs/api-reference/create-completion The type of object returned, + * should be "text_completion" + */ + String object; + + /** + * The creation time in epoch seconds. + */ + long created; + + /** + * The model used. + */ + String model; + + /** + * A list of generated completions. + */ + List choices; +} diff --git a/api/src/main/java/com/launchableinc/openai/completion/CompletionRequest.java b/api/src/main/java/com/launchableinc/openai/completion/CompletionRequest.java new file mode 100644 index 00000000..478d1868 --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/completion/CompletionRequest.java @@ -0,0 +1,139 @@ +package com.launchableinc.openai.completion; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; +import java.util.Map; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * A request for OpenAi to generate a predicted completion for a prompt. All fields are nullable. + *

+ * https://beta.openai.com/docs/api-reference/completions/create + */ +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Data +public class CompletionRequest { + + /** + * The name of the model to use. Required if specifying a fine-tuned model or if using the new + * v1/completions endpoint. + */ + String model; + + /** + * An optional prompt to complete from + */ + String prompt; + + /** + * The suffix that comes after a completion of inserted text. + */ + String suffix; + + /** + * The maximum number of tokens to generate. Requests can use up to 2048 tokens shared between + * prompt and completion. (One token is roughly 4 characters for normal English text) + */ + @JsonProperty("max_tokens") + Integer maxTokens; + + /** + * What sampling temperature to use. Higher values means the model will take more risks. Try 0.9 + * for more creative applications, and 0 (argmax sampling) for ones with a well-defined answer. + *

+ * We generally recommend using this or {@link CompletionRequest#topP} but not both. + */ + Double temperature; + + /** + * An alternative to sampling with temperature, called nucleus sampling, where the model considers + * the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising + * the top 10% probability mass are considered. + *

+ * We generally recommend using this or {@link CompletionRequest#temperature} but not both. + */ + @JsonProperty("top_p") + Double topP; + + /** + * How many completions to generate for each prompt. + *

+ * Because this parameter generates many completions, it can quickly consume your token quota. Use + * carefully and ensure that you have reasonable settings for {@link CompletionRequest#maxTokens} + * and {@link CompletionRequest#stop}. + */ + Integer n; + + /** + * Whether to stream back partial progress. If set, tokens will be sent as data-only server-sent + * events as they become available, with the stream terminated by a data: DONE message. + */ + Boolean stream; + + /** + * Include the log probabilities on the logprobs most likely tokens, as well the chosen tokens. + * For example, if logprobs is 10, the API will return a list of the 10 most likely tokens. The + * API will always return the logprob of the sampled token, so there may be up to logprobs+1 + * elements in the response. + */ + Integer logprobs; + + /** + * Echo back the prompt in addition to the completion + */ + Boolean echo; + + /** + * Up to 4 sequences where the API will stop generating further tokens. The returned text will not + * contain the stop sequence. + */ + List stop; + + /** + * Number between 0 and 1 (default 0) that penalizes new tokens based on whether they appear in + * the text so far. Increases the model's likelihood to talk about new topics. + */ + @JsonProperty("presence_penalty") + Double presencePenalty; + + /** + * Number between 0 and 1 (default 0) that penalizes new tokens based on their existing frequency + * in the text so far. Decreases the model's likelihood to repeat the same line verbatim. + */ + @JsonProperty("frequency_penalty") + Double frequencyPenalty; + + /** + * Generates best_of completions server-side and returns the "best" (the one with the lowest log + * probability per token). Results cannot be streamed. + *

+ * When used with {@link CompletionRequest#n}, best_of controls the number of candidate + * completions and n specifies how many to return, best_of must be greater than n. + */ + @JsonProperty("best_of") + Integer bestOf; + + /** + * Modify the likelihood of specified tokens appearing in the completion. + *

+ * Maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from + * -100 to 100. + *

+ * https://beta.openai.com/docs/api-reference/completions/create#completions/create-logit_bias + */ + @JsonProperty("logit_bias") + Map logitBias; + + /** + * A unique identifier representing your end-user, which will help OpenAI to monitor and detect + * abuse. + */ + String user; +} diff --git a/api/src/main/java/com/launchableinc/openai/completion/CompletionResult.java b/api/src/main/java/com/launchableinc/openai/completion/CompletionResult.java new file mode 100644 index 00000000..0060fb2a --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/completion/CompletionResult.java @@ -0,0 +1,46 @@ +package com.launchableinc.openai.completion; + +import com.launchableinc.openai.Usage; +import lombok.Data; + +import java.util.List; + +/** + * An object containing a response from the completion api + *

+ * https://beta.openai.com/docs/api-reference/completions/create + */ +@Data +public class CompletionResult { + + /** + * A unique id assigned to this completion. + */ + String id; + + /** + * https://beta.openai.com/docs/api-reference/create-completion The type of object returned, + * should be "text_completion" + */ + String object; + + /** + * The creation time in epoch seconds. + */ + long created; + + /** + * The GPT model used. + */ + String model; + + /** + * A list of generated completions. + */ + List choices; + + /** + * The API usage for this request + */ + Usage usage; +} diff --git a/api/src/main/java/com/launchableinc/openai/completion/LogProbResult.java b/api/src/main/java/com/launchableinc/openai/completion/LogProbResult.java new file mode 100644 index 00000000..22c6fa8d --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/completion/LogProbResult.java @@ -0,0 +1,40 @@ +package com.launchableinc.openai.completion; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +import java.util.List; +import java.util.Map; + +/** + * Log probabilities of different token options Returned if {@link CompletionRequest#logprobs} is + * greater than zero + *

+ * https://beta.openai.com/docs/api-reference/create-completion + */ +@Data +public class LogProbResult { + + /** + * The tokens chosen by the completion api + */ + List tokens; + + /** + * The log probability of each token in {@link tokens} + */ + @JsonProperty("token_logprobs") + List tokenLogprobs; + + /** + * A map for each index in the completion result. The map contains the top + * {@link CompletionRequest#logprobs} tokens and their probabilities + */ + @JsonProperty("top_logprobs") + List> topLogprobs; + + /** + * The character offset from the start of the returned text for each of the chosen tokens. + */ + List textOffset; +} diff --git a/api/src/main/java/com/launchableinc/openai/completion/chat/ChatCompletionChoice.java b/api/src/main/java/com/launchableinc/openai/completion/chat/ChatCompletionChoice.java new file mode 100644 index 00000000..f6ec50c6 --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/completion/chat/ChatCompletionChoice.java @@ -0,0 +1,29 @@ +package com.launchableinc.openai.completion.chat; + +import com.fasterxml.jackson.annotation.JsonAlias; +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; + +/** + * A chat completion generated by OpenAI + */ +@Data +public class ChatCompletionChoice { + + /** + * This index of this completion in the returned list. + */ + Integer index; + + /** + * The {@link ChatMessageRole#assistant} message or delta (when streaming) which was generated + */ + @JsonAlias("delta") + ChatMessage message; + + /** + * The reason why GPT stopped generating, for example "length". + */ + @JsonProperty("finish_reason") + String finishReason; +} diff --git a/api/src/main/java/com/launchableinc/openai/completion/chat/ChatCompletionChunk.java b/api/src/main/java/com/launchableinc/openai/completion/chat/ChatCompletionChunk.java new file mode 100644 index 00000000..21cc6200 --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/completion/chat/ChatCompletionChunk.java @@ -0,0 +1,37 @@ +package com.launchableinc.openai.completion.chat; + +import lombok.Data; + +import java.util.List; + +/** + * Object containing a response chunk from the chat completions streaming api. + */ +@Data +public class ChatCompletionChunk { + + /** + * Unique id assigned to this chat completion. + */ + String id; + + /** + * The type of object returned, should be "chat.completion.chunk" + */ + String object; + + /** + * The creation time in epoch seconds. + */ + long created; + + /** + * The model used. + */ + String model; + + /** + * A list of all generated completions. + */ + List choices; +} \ No newline at end of file diff --git a/api/src/main/java/com/launchableinc/openai/completion/chat/ChatCompletionRequest.java b/api/src/main/java/com/launchableinc/openai/completion/chat/ChatCompletionRequest.java new file mode 100644 index 00000000..4bc5f5da --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/completion/chat/ChatCompletionRequest.java @@ -0,0 +1,129 @@ +package com.launchableinc.openai.completion.chat; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; +import java.util.Map; + +@Data +@Builder +@AllArgsConstructor +@NoArgsConstructor +public class ChatCompletionRequest { + + /** + * ID of the model to use. + */ + String model; + + /** + * The messages to generate chat completions for, in the chat format.
see + * {@link ChatMessage} + */ + List messages; + + /** + * 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.
We + * generally recommend altering this or top_p but not both. + */ + Double temperature; + + /** + * An alternative to sampling with temperature, called nucleus sampling, where the model considers + * the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising + * the top 10% probability mass are considered.
We generally recommend altering this or + * temperature but not both. + */ + @JsonProperty("top_p") + Double topP; + + /** + * How many chat completion chatCompletionChoices to generate for each input message. + */ + Integer n; + + /** + * If set, partial message deltas will be sent, like in ChatGPT. Tokens will be sent as data-only + * server-sent + * events as they become available, with the stream terminated by a data: [DONE] message. + */ + Boolean stream; + + /** + * Up to 4 sequences where the API will stop generating further tokens. + */ + List stop; + + /** + * The maximum number of tokens allowed for the generated answer. By default, the number of tokens + * the model can return will be (4096 - prompt tokens). + */ + @JsonProperty("max_tokens") + Integer maxTokens; + + /** + * Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear + * in the text so far, increasing the model's likelihood to talk about new topics. + */ + @JsonProperty("presence_penalty") + Double presencePenalty; + + /** + * Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing + * frequency in the text so far, decreasing the model's likelihood to repeat the same line + * verbatim. + */ + @JsonProperty("frequency_penalty") + Double frequencyPenalty; + + /** + * Accepts a json object that maps tokens (specified by their token ID in the tokenizer) to an + * associated bias value from -100 to 100. Mathematically, the bias is added to the logits + * generated by the model prior to sampling. The exact effect will vary per model, but values + * between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 + * should result in a ban or exclusive selection of the relevant token. + */ + @JsonProperty("logit_bias") + Map logitBias; + + + /** + * A unique identifier representing your end-user, which will help OpenAI to monitor and detect + * abuse. + */ + String user; + + /** + * A list of the available functions. + */ + List functions; + + /** + * Controls how the model responds to function calls, as specified in the OpenAI + * documentation. + */ + @JsonProperty("function_call") + ChatCompletionRequestFunctionCall functionCall; + + @Data + @Builder + @AllArgsConstructor + @NoArgsConstructor + public static class ChatCompletionRequestFunctionCall { + + String name; + + public static ChatCompletionRequestFunctionCall of(String name) { + return new ChatCompletionRequestFunctionCall(name); + } + + } +} diff --git a/api/src/main/java/com/launchableinc/openai/completion/chat/ChatCompletionResult.java b/api/src/main/java/com/launchableinc/openai/completion/chat/ChatCompletionResult.java new file mode 100644 index 00000000..c9c487e6 --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/completion/chat/ChatCompletionResult.java @@ -0,0 +1,44 @@ +package com.launchableinc.openai.completion.chat; + +import com.launchableinc.openai.Usage; +import lombok.Data; + +import java.util.List; + +/** + * Object containing a response from the chat completions api. + */ +@Data +public class ChatCompletionResult { + + /** + * Unique id assigned to this chat completion. + */ + String id; + + /** + * The type of object returned, should be "chat.completion" + */ + String object; + + /** + * The creation time in epoch seconds. + */ + long created; + + /** + * The GPT model used. + */ + String model; + + /** + * A list of all generated completions. + */ + List choices; + + /** + * The API usage for this request. + */ + Usage usage; + +} diff --git a/api/src/main/java/com/launchableinc/openai/completion/chat/ChatFunction.java b/api/src/main/java/com/launchableinc/openai/completion/chat/ChatFunction.java new file mode 100644 index 00000000..41257601 --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/completion/chat/ChatFunction.java @@ -0,0 +1,72 @@ +package com.launchableinc.openai.completion.chat; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.NonNull; + +import java.util.function.Function; + +@Data +@NoArgsConstructor +public class ChatFunction { + + /** + * The name of the function being called. + */ + @NonNull + private String name; + + /** + * A description of what the function does, used by the model to choose when and how to call the + * function. + */ + private String description; + + /** + * The parameters the functions accepts. + */ + @JsonProperty("parameters") + private Class parametersClass; + + @JsonIgnore + private Function executor; + + public static Builder builder() { + return new Builder(); + } + + public static class Builder { + + private String name; + private String description; + private Class parameters; + private Function executor; + + public Builder name(String name) { + this.name = name; + return this; + } + + public Builder description(String description) { + this.description = description; + return this; + } + + public Builder executor(Class requestClass, Function executor) { + this.parameters = requestClass; + this.executor = (Function) executor; + return this; + } + + public ChatFunction build() { + ChatFunction chatFunction = new ChatFunction(); + chatFunction.setName(name); + chatFunction.setDescription(description); + chatFunction.setParametersClass(parameters); + chatFunction.setExecutor(executor); + return chatFunction; + } + } +} \ No newline at end of file diff --git a/api/src/main/java/com/launchableinc/openai/completion/chat/ChatFunctionCall.java b/api/src/main/java/com/launchableinc/openai/completion/chat/ChatFunctionCall.java new file mode 100644 index 00000000..c2a4ac84 --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/completion/chat/ChatFunctionCall.java @@ -0,0 +1,24 @@ +package com.launchableinc.openai.completion.chat; + +import com.fasterxml.jackson.databind.JsonNode; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class ChatFunctionCall { + + /** + * The name of the function being called + */ + String name; + + /** + * The arguments of the call produced by the model, represented as a JsonNode for easy + * manipulation. + */ + JsonNode arguments; + +} diff --git a/api/src/main/java/com/launchableinc/openai/completion/chat/ChatFunctionDynamic.java b/api/src/main/java/com/launchableinc/openai/completion/chat/ChatFunctionDynamic.java new file mode 100644 index 00000000..56eeea92 --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/completion/chat/ChatFunctionDynamic.java @@ -0,0 +1,64 @@ +package com.launchableinc.openai.completion.chat; + +import lombok.Data; +import lombok.NonNull; + + +@Data +public class ChatFunctionDynamic { + + /** + * The name of the function being called. + */ + @NonNull + private String name; + + /** + * A description of what the function does, used by the model to choose when and how to call the + * function. + */ + private String description; + + /** + * The parameters the functions accepts. + */ + private ChatFunctionParameters parameters; + + public static Builder builder() { + return new Builder(); + } + + public static class Builder { + + private String name; + private String description; + private ChatFunctionParameters parameters = new ChatFunctionParameters(); + + public Builder name(String name) { + this.name = name; + return this; + } + + public Builder description(String description) { + this.description = description; + return this; + } + + public Builder parameters(ChatFunctionParameters parameters) { + this.parameters = parameters; + return this; + } + + public Builder addProperty(ChatFunctionProperty property) { + this.parameters.addProperty(property); + return this; + } + + public ChatFunctionDynamic build() { + ChatFunctionDynamic chatFunction = new ChatFunctionDynamic(name); + chatFunction.setDescription(description); + chatFunction.setParameters(parameters); + return chatFunction; + } + } +} diff --git a/api/src/main/java/com/launchableinc/openai/completion/chat/ChatFunctionParameters.java b/api/src/main/java/com/launchableinc/openai/completion/chat/ChatFunctionParameters.java new file mode 100644 index 00000000..53961959 --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/completion/chat/ChatFunctionParameters.java @@ -0,0 +1,27 @@ +package com.launchableinc.openai.completion.chat; + +import lombok.Data; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +@Data +public class ChatFunctionParameters { + + private final String type = "object"; + + private final HashMap properties = new HashMap<>(); + + private List required; + + public void addProperty(ChatFunctionProperty property) { + properties.put(property.getName(), property); + if (Boolean.TRUE.equals(property.getRequired())) { + if (this.required == null) { + this.required = new ArrayList<>(); + } + this.required.add(property.getName()); + } + } +} diff --git a/api/src/main/java/com/launchableinc/openai/completion/chat/ChatFunctionProperty.java b/api/src/main/java/com/launchableinc/openai/completion/chat/ChatFunctionProperty.java new file mode 100644 index 00000000..488b3ab4 --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/completion/chat/ChatFunctionProperty.java @@ -0,0 +1,26 @@ +package com.launchableinc.openai.completion.chat; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Builder; +import lombok.Data; +import lombok.NonNull; + +import java.util.Set; + +@Data +@Builder +public class ChatFunctionProperty { + + @NonNull + @JsonIgnore + private String name; + @NonNull + private String type; + @JsonIgnore + private Boolean required; + private String description; + private ChatFunctionProperty items; + @JsonProperty("enum") + private Set enumValues; +} \ No newline at end of file diff --git a/api/src/main/java/com/theokanning/openai/completion/chat/ChatMessage.java b/api/src/main/java/com/launchableinc/openai/completion/chat/ChatMessage.java similarity index 63% rename from api/src/main/java/com/theokanning/openai/completion/chat/ChatMessage.java rename to api/src/main/java/com/launchableinc/openai/completion/chat/ChatMessage.java index 912a71f0..c1868bab 100644 --- a/api/src/main/java/com/theokanning/openai/completion/chat/ChatMessage.java +++ b/api/src/main/java/com/launchableinc/openai/completion/chat/ChatMessage.java @@ -1,17 +1,21 @@ -package com.theokanning.openai.completion.chat; +package com.launchableinc.openai.completion.chat; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.*; /** - *

Each object has a role (either "system", "user", or "assistant") and content (the content of the message). Conversations can be as short as 1 message or fill many pages.

- *

Typically, a conversation is formatted with a system message first, followed by alternating user and assistant messages.

- *

The system message helps set the behavior of the assistant. In the example above, the assistant was instructed with "You are a helpful assistant."
- * The user messages help instruct the assistant. They can be generated by the end users of an application, or set by a developer as an instruction.
- * The assistant messages help store prior responses. They can also be written by a developer to help give examples of desired behavior. + *

Each object has a role (either "system", "user", or "assistant") and content (the content of + * the message). Conversations can be as short as 1 message or fill many pages.

+ *

Typically, a conversation is formatted with a system message first, followed by alternating + * user and assistant messages.

+ *

The system message helps set the behavior of the assistant. In the example above, the + * assistant was instructed with "You are a helpful assistant."
The user messages help instruct + * the assistant. They can be generated by the end users of an application, or set by a developer as + * an instruction.
The assistant messages help store prior responses. They can also be written + * by a developer to help give examples of desired behavior. *

- * + *

* see OpenAi documentation */ @Data @@ -21,8 +25,8 @@ public class ChatMessage { /** - * Must be either 'system', 'user', 'assistant' or 'function'.
- * You may use {@link ChatMessageRole} enum. + * Must be either 'system', 'user', 'assistant' or 'function'.
You may use + * {@link ChatMessageRole} enum. */ @NonNull String role; diff --git a/api/src/main/java/com/launchableinc/openai/completion/chat/ChatMessageRole.java b/api/src/main/java/com/launchableinc/openai/completion/chat/ChatMessageRole.java new file mode 100644 index 00000000..31406caa --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/completion/chat/ChatMessageRole.java @@ -0,0 +1,21 @@ +package com.launchableinc.openai.completion.chat; + +/** + * see {@link ChatMessage} documentation. + */ +public enum ChatMessageRole { + SYSTEM("system"), + USER("user"), + ASSISTANT("assistant"), + FUNCTION("function"); + + private final String value; + + ChatMessageRole(final String value) { + this.value = value; + } + + public String value() { + return value; + } +} diff --git a/api/src/main/java/com/launchableinc/openai/edit/EditChoice.java b/api/src/main/java/com/launchableinc/openai/edit/EditChoice.java new file mode 100644 index 00000000..c8684535 --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/edit/EditChoice.java @@ -0,0 +1,22 @@ +package com.launchableinc.openai.edit; + +import lombok.Data; + +/** + * An edit generated by OpenAi + *

+ * https://beta.openai.com/docs/api-reference/edits/create + */ +@Data +public class EditChoice { + + /** + * The edited text. + */ + String text; + + /** + * This index of this completion in the returned list. + */ + Integer index; +} diff --git a/api/src/main/java/com/launchableinc/openai/edit/EditRequest.java b/api/src/main/java/com/launchableinc/openai/edit/EditRequest.java new file mode 100644 index 00000000..4f98ad44 --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/edit/EditRequest.java @@ -0,0 +1,56 @@ +package com.launchableinc.openai.edit; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.*; + +/** + * Given a prompt and an instruction, OpenAi will return an edited version of the prompt + *

+ * https://beta.openai.com/docs/api-reference/edits/create + */ +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Data +public class EditRequest { + + /** + * The name of the model to use. Required if using the new v1/edits endpoint. + */ + String model; + + /** + * The input text to use as a starting point for the edit. + */ + String input; + + /** + * The instruction that tells the model how to edit the prompt. For example, "Fix the spelling + * mistakes" + */ + @NonNull + String instruction; + + /** + * How many edits to generate for the input and instruction. + */ + Integer n; + + /** + * What sampling temperature to use. Higher values means the model will take more risks. Try 0.9 + * for more creative applications, and 0 (argmax sampling) for ones with a well-defined answer. + *

+ * We generally recommend altering this or {@link EditRequest#topP} but not both. + */ + Double temperature; + + /** + * An alternative to sampling with temperature, called nucleus sampling, where the model considers + * the results of the tokens with top_p probability mass.So 0.1 means only the tokens comprising + * the top 10% probability mass are considered. + *

+ * We generally recommend altering this or {@link EditRequest#temperature} but not both. + */ + @JsonProperty("top_p") + Double topP; +} diff --git a/api/src/main/java/com/launchableinc/openai/edit/EditResult.java b/api/src/main/java/com/launchableinc/openai/edit/EditResult.java new file mode 100644 index 00000000..aa070bfe --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/edit/EditResult.java @@ -0,0 +1,35 @@ +package com.launchableinc.openai.edit; + +import com.launchableinc.openai.Usage; +import lombok.Data; + +import java.util.List; + +/** + * A list of edits generated by OpenAI + *

+ * https://beta.openai.com/docs/api-reference/edits/create + */ +@Data +public class EditResult { + + /** + * The type of object returned, should be "edit" + */ + public String object; + + /** + * The creation time in epoch milliseconds. + */ + public long created; + + /** + * A list of generated edits. + */ + public List choices; + + /** + * The API usage for this request + */ + public Usage usage; +} diff --git a/api/src/main/java/com/theokanning/openai/edit/EditUsage.java b/api/src/main/java/com/launchableinc/openai/edit/EditUsage.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/edit/EditUsage.java rename to api/src/main/java/com/launchableinc/openai/edit/EditUsage.java diff --git a/api/src/main/java/com/theokanning/openai/embedding/Embedding.java b/api/src/main/java/com/launchableinc/openai/embedding/Embedding.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/embedding/Embedding.java rename to api/src/main/java/com/launchableinc/openai/embedding/Embedding.java diff --git a/api/src/main/java/com/theokanning/openai/embedding/EmbeddingRequest.java b/api/src/main/java/com/launchableinc/openai/embedding/EmbeddingRequest.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/embedding/EmbeddingRequest.java rename to api/src/main/java/com/launchableinc/openai/embedding/EmbeddingRequest.java diff --git a/api/src/main/java/com/theokanning/openai/embedding/EmbeddingResult.java b/api/src/main/java/com/launchableinc/openai/embedding/EmbeddingResult.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/embedding/EmbeddingResult.java rename to api/src/main/java/com/launchableinc/openai/embedding/EmbeddingResult.java diff --git a/api/src/main/java/com/theokanning/openai/engine/Engine.java b/api/src/main/java/com/launchableinc/openai/engine/Engine.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/engine/Engine.java rename to api/src/main/java/com/launchableinc/openai/engine/Engine.java diff --git a/api/src/main/java/com/theokanning/openai/file/File.java b/api/src/main/java/com/launchableinc/openai/file/File.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/file/File.java rename to api/src/main/java/com/launchableinc/openai/file/File.java diff --git a/api/src/main/java/com/theokanning/openai/fine_tuning/FineTuningEvent.java b/api/src/main/java/com/launchableinc/openai/fine_tuning/FineTuningEvent.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/fine_tuning/FineTuningEvent.java rename to api/src/main/java/com/launchableinc/openai/fine_tuning/FineTuningEvent.java diff --git a/api/src/main/java/com/theokanning/openai/fine_tuning/FineTuningJob.java b/api/src/main/java/com/launchableinc/openai/fine_tuning/FineTuningJob.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/fine_tuning/FineTuningJob.java rename to api/src/main/java/com/launchableinc/openai/fine_tuning/FineTuningJob.java diff --git a/api/src/main/java/com/theokanning/openai/fine_tuning/FineTuningJobRequest.java b/api/src/main/java/com/launchableinc/openai/fine_tuning/FineTuningJobRequest.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/fine_tuning/FineTuningJobRequest.java rename to api/src/main/java/com/launchableinc/openai/fine_tuning/FineTuningJobRequest.java diff --git a/api/src/main/java/com/theokanning/openai/fine_tuning/Hyperparameters.java b/api/src/main/java/com/launchableinc/openai/fine_tuning/Hyperparameters.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/fine_tuning/Hyperparameters.java rename to api/src/main/java/com/launchableinc/openai/fine_tuning/Hyperparameters.java diff --git a/api/src/main/java/com/theokanning/openai/finetune/FineTuneEvent.java b/api/src/main/java/com/launchableinc/openai/finetune/FineTuneEvent.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/finetune/FineTuneEvent.java rename to api/src/main/java/com/launchableinc/openai/finetune/FineTuneEvent.java diff --git a/api/src/main/java/com/theokanning/openai/finetune/FineTuneRequest.java b/api/src/main/java/com/launchableinc/openai/finetune/FineTuneRequest.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/finetune/FineTuneRequest.java rename to api/src/main/java/com/launchableinc/openai/finetune/FineTuneRequest.java diff --git a/api/src/main/java/com/theokanning/openai/finetune/FineTuneResult.java b/api/src/main/java/com/launchableinc/openai/finetune/FineTuneResult.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/finetune/FineTuneResult.java rename to api/src/main/java/com/launchableinc/openai/finetune/FineTuneResult.java diff --git a/api/src/main/java/com/theokanning/openai/finetune/HyperParameters.java b/api/src/main/java/com/launchableinc/openai/finetune/HyperParameters.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/finetune/HyperParameters.java rename to api/src/main/java/com/launchableinc/openai/finetune/HyperParameters.java diff --git a/api/src/main/java/com/theokanning/openai/image/CreateImageEditRequest.java b/api/src/main/java/com/launchableinc/openai/image/CreateImageEditRequest.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/image/CreateImageEditRequest.java rename to api/src/main/java/com/launchableinc/openai/image/CreateImageEditRequest.java diff --git a/api/src/main/java/com/launchableinc/openai/image/CreateImageRequest.java b/api/src/main/java/com/launchableinc/openai/image/CreateImageRequest.java new file mode 100644 index 00000000..06143fac --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/image/CreateImageRequest.java @@ -0,0 +1,69 @@ +package com.launchableinc.openai.image; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import lombok.*; + +/** + * A request for OpenAi to create an image based on a prompt All fields except prompt are optional + *

+ * https://beta.openai.com/docs/api-reference/images/create + */ +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Data +public class CreateImageRequest { + + /** + * A text description of the desired image(s). The maximum length is 1000 characters for dall-e-2 + * and 4000 characters for dall-e-3. + */ + @NonNull + String prompt; + + /** + * The model to use for image generation. Defaults to "dall-e-2". + */ + String model; + + /** + * The number of images to generate. Must be between 1 and 10. For dall-e-3, only n=1 is + * supported. Defaults to 1. + */ + Integer n; + + /** + * The quality of the image that will be generated. "hd" creates images with finer details and + * greater consistency across the image. This param is only supported for dall-e-3. Defaults to + * "standard". + */ + String quality; + + /** + * The size of the generated images. Must be one of 256x256, 512x512, or 1024x1024 for dall-e-2. + * Must be one of 1024x1024, 1792x1024, or 1024x1792 for dall-e-3 models. Defaults to 1024x1024. + */ + String size; + + /** + * The format in which the generated images are returned. Must be one of url or b64_json. Defaults + * to url. + */ + @JsonProperty("response_format") + String responseFormat; + + /** + * The style of the generated images. Must be one of vivid or natural. Vivid causes the model to + * lean towards generating hyper-real and dramatic images. Natural causes the model to produce + * more natural, less hyper-real looking images. This param is only supported for dall-e-3. + * Defaults to vivid. + */ + String style; + + /** + * A unique identifier representing your end-user, which will help OpenAI to monitor and detect + * abuse. + */ + String user; +} diff --git a/api/src/main/java/com/theokanning/openai/image/CreateImageVariationRequest.java b/api/src/main/java/com/launchableinc/openai/image/CreateImageVariationRequest.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/image/CreateImageVariationRequest.java rename to api/src/main/java/com/launchableinc/openai/image/CreateImageVariationRequest.java diff --git a/api/src/main/java/com/theokanning/openai/image/Image.java b/api/src/main/java/com/launchableinc/openai/image/Image.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/image/Image.java rename to api/src/main/java/com/launchableinc/openai/image/Image.java diff --git a/api/src/main/java/com/theokanning/openai/image/ImageResult.java b/api/src/main/java/com/launchableinc/openai/image/ImageResult.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/image/ImageResult.java rename to api/src/main/java/com/launchableinc/openai/image/ImageResult.java diff --git a/api/src/main/java/com/theokanning/openai/messages/Message.java b/api/src/main/java/com/launchableinc/openai/messages/Message.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/messages/Message.java rename to api/src/main/java/com/launchableinc/openai/messages/Message.java diff --git a/api/src/main/java/com/theokanning/openai/messages/MessageContent.java b/api/src/main/java/com/launchableinc/openai/messages/MessageContent.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/messages/MessageContent.java rename to api/src/main/java/com/launchableinc/openai/messages/MessageContent.java diff --git a/api/src/main/java/com/theokanning/openai/messages/MessageFile.java b/api/src/main/java/com/launchableinc/openai/messages/MessageFile.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/messages/MessageFile.java rename to api/src/main/java/com/launchableinc/openai/messages/MessageFile.java diff --git a/api/src/main/java/com/theokanning/openai/messages/MessageRequest.java b/api/src/main/java/com/launchableinc/openai/messages/MessageRequest.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/messages/MessageRequest.java rename to api/src/main/java/com/launchableinc/openai/messages/MessageRequest.java diff --git a/api/src/main/java/com/theokanning/openai/messages/ModifyMessageRequest.java b/api/src/main/java/com/launchableinc/openai/messages/ModifyMessageRequest.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/messages/ModifyMessageRequest.java rename to api/src/main/java/com/launchableinc/openai/messages/ModifyMessageRequest.java diff --git a/api/src/main/java/com/theokanning/openai/messages/content/Annotation.java b/api/src/main/java/com/launchableinc/openai/messages/content/Annotation.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/messages/content/Annotation.java rename to api/src/main/java/com/launchableinc/openai/messages/content/Annotation.java diff --git a/api/src/main/java/com/theokanning/openai/messages/content/FileCitation.java b/api/src/main/java/com/launchableinc/openai/messages/content/FileCitation.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/messages/content/FileCitation.java rename to api/src/main/java/com/launchableinc/openai/messages/content/FileCitation.java diff --git a/api/src/main/java/com/theokanning/openai/messages/content/FilePath.java b/api/src/main/java/com/launchableinc/openai/messages/content/FilePath.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/messages/content/FilePath.java rename to api/src/main/java/com/launchableinc/openai/messages/content/FilePath.java diff --git a/api/src/main/java/com/theokanning/openai/messages/content/ImageFile.java b/api/src/main/java/com/launchableinc/openai/messages/content/ImageFile.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/messages/content/ImageFile.java rename to api/src/main/java/com/launchableinc/openai/messages/content/ImageFile.java diff --git a/api/src/main/java/com/theokanning/openai/messages/content/Text.java b/api/src/main/java/com/launchableinc/openai/messages/content/Text.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/messages/content/Text.java rename to api/src/main/java/com/launchableinc/openai/messages/content/Text.java diff --git a/api/src/main/java/com/theokanning/openai/model/Model.java b/api/src/main/java/com/launchableinc/openai/model/Model.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/model/Model.java rename to api/src/main/java/com/launchableinc/openai/model/Model.java diff --git a/api/src/main/java/com/theokanning/openai/model/Permission.java b/api/src/main/java/com/launchableinc/openai/model/Permission.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/model/Permission.java rename to api/src/main/java/com/launchableinc/openai/model/Permission.java diff --git a/api/src/main/java/com/theokanning/openai/moderation/Moderation.java b/api/src/main/java/com/launchableinc/openai/moderation/Moderation.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/moderation/Moderation.java rename to api/src/main/java/com/launchableinc/openai/moderation/Moderation.java diff --git a/api/src/main/java/com/theokanning/openai/moderation/ModerationCategories.java b/api/src/main/java/com/launchableinc/openai/moderation/ModerationCategories.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/moderation/ModerationCategories.java rename to api/src/main/java/com/launchableinc/openai/moderation/ModerationCategories.java diff --git a/api/src/main/java/com/theokanning/openai/moderation/ModerationCategoryScores.java b/api/src/main/java/com/launchableinc/openai/moderation/ModerationCategoryScores.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/moderation/ModerationCategoryScores.java rename to api/src/main/java/com/launchableinc/openai/moderation/ModerationCategoryScores.java diff --git a/api/src/main/java/com/theokanning/openai/moderation/ModerationRequest.java b/api/src/main/java/com/launchableinc/openai/moderation/ModerationRequest.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/moderation/ModerationRequest.java rename to api/src/main/java/com/launchableinc/openai/moderation/ModerationRequest.java diff --git a/api/src/main/java/com/theokanning/openai/moderation/ModerationResult.java b/api/src/main/java/com/launchableinc/openai/moderation/ModerationResult.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/moderation/ModerationResult.java rename to api/src/main/java/com/launchableinc/openai/moderation/ModerationResult.java diff --git a/api/src/main/java/com/theokanning/openai/runs/CreateThreadAndRunRequest.java b/api/src/main/java/com/launchableinc/openai/runs/CreateThreadAndRunRequest.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/runs/CreateThreadAndRunRequest.java rename to api/src/main/java/com/launchableinc/openai/runs/CreateThreadAndRunRequest.java diff --git a/api/src/main/java/com/theokanning/openai/runs/MessageCreation.java b/api/src/main/java/com/launchableinc/openai/runs/MessageCreation.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/runs/MessageCreation.java rename to api/src/main/java/com/launchableinc/openai/runs/MessageCreation.java diff --git a/api/src/main/java/com/theokanning/openai/runs/RequiredAction.java b/api/src/main/java/com/launchableinc/openai/runs/RequiredAction.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/runs/RequiredAction.java rename to api/src/main/java/com/launchableinc/openai/runs/RequiredAction.java diff --git a/api/src/main/java/com/theokanning/openai/runs/Run.java b/api/src/main/java/com/launchableinc/openai/runs/Run.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/runs/Run.java rename to api/src/main/java/com/launchableinc/openai/runs/Run.java diff --git a/api/src/main/java/com/theokanning/openai/runs/RunCreateRequest.java b/api/src/main/java/com/launchableinc/openai/runs/RunCreateRequest.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/runs/RunCreateRequest.java rename to api/src/main/java/com/launchableinc/openai/runs/RunCreateRequest.java diff --git a/api/src/main/java/com/theokanning/openai/runs/RunImage.java b/api/src/main/java/com/launchableinc/openai/runs/RunImage.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/runs/RunImage.java rename to api/src/main/java/com/launchableinc/openai/runs/RunImage.java diff --git a/api/src/main/java/com/theokanning/openai/runs/RunStep.java b/api/src/main/java/com/launchableinc/openai/runs/RunStep.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/runs/RunStep.java rename to api/src/main/java/com/launchableinc/openai/runs/RunStep.java diff --git a/api/src/main/java/com/theokanning/openai/runs/StepDetails.java b/api/src/main/java/com/launchableinc/openai/runs/StepDetails.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/runs/StepDetails.java rename to api/src/main/java/com/launchableinc/openai/runs/StepDetails.java diff --git a/api/src/main/java/com/theokanning/openai/runs/SubmitToolOutputRequestItem.java b/api/src/main/java/com/launchableinc/openai/runs/SubmitToolOutputRequestItem.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/runs/SubmitToolOutputRequestItem.java rename to api/src/main/java/com/launchableinc/openai/runs/SubmitToolOutputRequestItem.java diff --git a/api/src/main/java/com/theokanning/openai/runs/SubmitToolOutputs.java b/api/src/main/java/com/launchableinc/openai/runs/SubmitToolOutputs.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/runs/SubmitToolOutputs.java rename to api/src/main/java/com/launchableinc/openai/runs/SubmitToolOutputs.java diff --git a/api/src/main/java/com/theokanning/openai/runs/SubmitToolOutputsRequest.java b/api/src/main/java/com/launchableinc/openai/runs/SubmitToolOutputsRequest.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/runs/SubmitToolOutputsRequest.java rename to api/src/main/java/com/launchableinc/openai/runs/SubmitToolOutputsRequest.java diff --git a/api/src/main/java/com/theokanning/openai/runs/ToolCall.java b/api/src/main/java/com/launchableinc/openai/runs/ToolCall.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/runs/ToolCall.java rename to api/src/main/java/com/launchableinc/openai/runs/ToolCall.java diff --git a/api/src/main/java/com/theokanning/openai/runs/ToolCallCodeInterpreter.java b/api/src/main/java/com/launchableinc/openai/runs/ToolCallCodeInterpreter.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/runs/ToolCallCodeInterpreter.java rename to api/src/main/java/com/launchableinc/openai/runs/ToolCallCodeInterpreter.java diff --git a/api/src/main/java/com/theokanning/openai/runs/ToolCallCodeInterpreterOutput.java b/api/src/main/java/com/launchableinc/openai/runs/ToolCallCodeInterpreterOutput.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/runs/ToolCallCodeInterpreterOutput.java rename to api/src/main/java/com/launchableinc/openai/runs/ToolCallCodeInterpreterOutput.java diff --git a/api/src/main/java/com/theokanning/openai/runs/ToolCallFunction.java b/api/src/main/java/com/launchableinc/openai/runs/ToolCallFunction.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/runs/ToolCallFunction.java rename to api/src/main/java/com/launchableinc/openai/runs/ToolCallFunction.java diff --git a/api/src/main/java/com/theokanning/openai/threads/Thread.java b/api/src/main/java/com/launchableinc/openai/threads/Thread.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/threads/Thread.java rename to api/src/main/java/com/launchableinc/openai/threads/Thread.java diff --git a/api/src/main/java/com/theokanning/openai/threads/ThreadRequest.java b/api/src/main/java/com/launchableinc/openai/threads/ThreadRequest.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/threads/ThreadRequest.java rename to api/src/main/java/com/launchableinc/openai/threads/ThreadRequest.java diff --git a/api/src/main/java/com/theokanning/openai/utils/TikTokensUtil.java b/api/src/main/java/com/launchableinc/openai/utils/TikTokensUtil.java similarity index 100% rename from api/src/main/java/com/theokanning/openai/utils/TikTokensUtil.java rename to api/src/main/java/com/launchableinc/openai/utils/TikTokensUtil.java diff --git a/api/src/main/java/com/theokanning/openai/DeleteResult.java b/api/src/main/java/com/theokanning/openai/DeleteResult.java deleted file mode 100644 index 2d8647c0..00000000 --- a/api/src/main/java/com/theokanning/openai/DeleteResult.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.theokanning.openai; - -import lombok.Data; - -/** - * A response when deleting an object - */ -@Data -public class DeleteResult { - /** - * The id of the object. - */ - String id; - - /** - * The type of object deleted, for example "file" or "model" - */ - String object; - - /** - * True if successfully deleted - */ - boolean deleted; -} diff --git a/api/src/main/java/com/theokanning/openai/ListSearchParameters.java b/api/src/main/java/com/theokanning/openai/ListSearchParameters.java deleted file mode 100644 index 53fd484f..00000000 --- a/api/src/main/java/com/theokanning/openai/ListSearchParameters.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.theokanning.openai; - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Common options when getting a list of objects - */ -@Builder -@NoArgsConstructor -@AllArgsConstructor -@Data -public class ListSearchParameters { - /** - * A limit on the number of objects to be returned. - * Limit can range between 1 and 100, and the default is 20 - */ - - Integer limit; - - /** - * Sort order by the 'created_at' timestamp of the objects. - * 'asc' for ascending order and 'desc' for descending order. - */ - Order order; - - /** - * 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 - */ - String after; - - /** - * 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. - */ - String before; - - public enum Order { - @JsonProperty("asc") - ASCENDING, - - @JsonProperty("desc") - DESCENDING - } -} diff --git a/api/src/main/java/com/theokanning/openai/OpenAiError.java b/api/src/main/java/com/theokanning/openai/OpenAiError.java deleted file mode 100644 index 9992037d..00000000 --- a/api/src/main/java/com/theokanning/openai/OpenAiError.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.theokanning.openai; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * Represents the error body when an OpenAI request fails - */ -@Data -@NoArgsConstructor -@AllArgsConstructor -public class OpenAiError { - - public OpenAiErrorDetails error; - - @Data - @NoArgsConstructor - @AllArgsConstructor - public static class OpenAiErrorDetails { - /** - * Human-readable error message - */ - String message; - - /** - * OpenAI error type, for example "invalid_request_error" - * https://platform.openai.com/docs/guides/error-codes/python-library-error-types - */ - String type; - - String param; - - /** - * OpenAI error code, for example "invalid_api_key" - */ - String code; - } -} diff --git a/api/src/main/java/com/theokanning/openai/OpenAiHttpException.java b/api/src/main/java/com/theokanning/openai/OpenAiHttpException.java deleted file mode 100644 index 85533570..00000000 --- a/api/src/main/java/com/theokanning/openai/OpenAiHttpException.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.theokanning.openai; - -public class OpenAiHttpException extends RuntimeException { - - /** - * HTTP status code - */ - public final int statusCode; - - /** - * OpenAI error code, for example "invalid_api_key" - */ - public final String code; - - - public final String param; - - /** - * OpenAI error type, for example "invalid_request_error" - * https://platform.openai.com/docs/guides/error-codes/python-library-error-types - */ - public final String type; - - public OpenAiHttpException(OpenAiError error, Exception parent, int statusCode) { - super(error.error.message, parent); - this.statusCode = statusCode; - this.code = error.error.code; - this.param = error.error.param; - this.type = error.error.type; - } -} diff --git a/api/src/main/java/com/theokanning/openai/OpenAiResponse.java b/api/src/main/java/com/theokanning/openai/OpenAiResponse.java deleted file mode 100644 index f062fc77..00000000 --- a/api/src/main/java/com/theokanning/openai/OpenAiResponse.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.theokanning.openai; - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.Data; - -import java.util.List; - -/** - * A wrapper class to fit the OpenAI engine and search endpoints - */ -@Data -public class OpenAiResponse { - /** - * A list containing the actual results - */ - public List data; - - /** - * The type of object returned, should be "list" - */ - public String object; - - /** - * The first id included - */ - @JsonProperty("first_id") - public String firstId; - - /** - * The last id included - */ - @JsonProperty("last_id") - public String lastId; - - /** - * True if there are objects after lastId - */ - @JsonProperty("has_more") - public boolean hasMore; -} diff --git a/api/src/main/java/com/theokanning/openai/Usage.java b/api/src/main/java/com/theokanning/openai/Usage.java deleted file mode 100644 index 1e7eaa58..00000000 --- a/api/src/main/java/com/theokanning/openai/Usage.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.theokanning.openai; - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.Data; - -/** - * The OpenAI resources used by a request - */ -@Data -public class Usage { - /** - * The number of prompt tokens used. - */ - @JsonProperty("prompt_tokens") - long promptTokens; - - /** - * The number of completion tokens used. - */ - @JsonProperty("completion_tokens") - long completionTokens; - - /** - * The number of total tokens used - */ - @JsonProperty("total_tokens") - long totalTokens; -} diff --git a/api/src/main/java/com/theokanning/openai/assistants/Assistant.java b/api/src/main/java/com/theokanning/openai/assistants/Assistant.java deleted file mode 100644 index 49cf17e9..00000000 --- a/api/src/main/java/com/theokanning/openai/assistants/Assistant.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.theokanning.openai.assistants; - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.*; - -import java.util.List; -import java.util.Map; - -@Builder -@NoArgsConstructor -@AllArgsConstructor -@Data -public class Assistant { - - /** - * The identifier, which can be referenced in API endpoints. - */ - String id; - - /** - * The object type which is always 'assistant' - */ - String object; - - /** - * The Unix timestamp(in seconds) for when the assistant was created - */ - @JsonProperty("created_at") - Integer createdAt; - - /** - * The name of the assistant. The maximum length is 256 - */ - String name; - - /** - * The description of the assistant. - */ - String description; - - /** - * ID of the model to use - */ - @NonNull - String model; - - /** - * The system instructions that the assistant uses. - */ - String instructions; - - /** - * A list of tools enabled on the assistant. - */ - List tools; - - /** - * A list of file IDs attached to this assistant. - */ - @JsonProperty("file_ids") - List fileIds; - - /** - * Set of 16 key-value pairs that can be attached to an object. - */ - Map metadata; -} diff --git a/api/src/main/java/com/theokanning/openai/assistants/AssistantFile.java b/api/src/main/java/com/theokanning/openai/assistants/AssistantFile.java deleted file mode 100644 index c5d551a9..00000000 --- a/api/src/main/java/com/theokanning/openai/assistants/AssistantFile.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.theokanning.openai.assistants; - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.Data; - -@Data -public class AssistantFile { - - /** - * The identifier of the Assistant File - */ - String id; - - /** - * The object type, which is always assistant.file. - */ - String object; - - /** - * The Unix timestamp (in seconds) for when the assistant file was created. - */ - @JsonProperty("created_at") - String createdAt; - - /** - * The assistant ID that the file is attached to - */ - @JsonProperty("assistant_id") - String assistantId; -} diff --git a/api/src/main/java/com/theokanning/openai/assistants/AssistantRequest.java b/api/src/main/java/com/theokanning/openai/assistants/AssistantRequest.java deleted file mode 100644 index bf38ff0b..00000000 --- a/api/src/main/java/com/theokanning/openai/assistants/AssistantRequest.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.theokanning.openai.assistants; - - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.*; - -import java.util.List; -import java.util.Map; - -@Builder -@NoArgsConstructor -@AllArgsConstructor -@Data -public class AssistantRequest { - - /** - * ID of the model to use - */ - @NonNull - String model; - - /** - * The name of the assistant. The maximum length is 256 - */ - String name; - - /** - * The description of the assistant. - */ - String description; - - /** - * The system instructions that the assistant uses. - */ - String instructions; - - /** - * A list of tools enabled on the assistant. - */ - List tools; - - /** - * A list of file IDs attached to this assistant. - */ - @JsonProperty("file_ids") - List fileIds; - - /** - * Set of 16 key-value pairs that can be attached to an object. - */ - Map metadata; -} diff --git a/api/src/main/java/com/theokanning/openai/assistants/AssistantSortOrder.java b/api/src/main/java/com/theokanning/openai/assistants/AssistantSortOrder.java deleted file mode 100644 index 9f784a66..00000000 --- a/api/src/main/java/com/theokanning/openai/assistants/AssistantSortOrder.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.theokanning.openai.assistants; - -import com.fasterxml.jackson.annotation.JsonProperty; - -public enum AssistantSortOrder { - - @JsonProperty("asc") - ASC, - - @JsonProperty("desc") - DESC -} diff --git a/api/src/main/java/com/theokanning/openai/assistants/AssistantToolsEnum.java b/api/src/main/java/com/theokanning/openai/assistants/AssistantToolsEnum.java deleted file mode 100644 index f6b5021d..00000000 --- a/api/src/main/java/com/theokanning/openai/assistants/AssistantToolsEnum.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.theokanning.openai.assistants; - -import com.fasterxml.jackson.annotation.JsonProperty; - -public enum AssistantToolsEnum { - - @JsonProperty("code_interpreter") - CODE_INTERPRETER, - - @JsonProperty("function") - FUNCTION, - - @JsonProperty("retrieval") - RETRIEVAL -} diff --git a/api/src/main/java/com/theokanning/openai/assistants/ModifyAssistantRequest.java b/api/src/main/java/com/theokanning/openai/assistants/ModifyAssistantRequest.java deleted file mode 100644 index 0fcc4f85..00000000 --- a/api/src/main/java/com/theokanning/openai/assistants/ModifyAssistantRequest.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.theokanning.openai.assistants; - - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.*; - -import java.util.List; -import java.util.Map; - -@Builder -@NoArgsConstructor -@AllArgsConstructor -@Data -public class ModifyAssistantRequest { - - /** - * ID of the model to use - */ - String model; - - /** - * The name of the assistant. The maximum length is 256 - */ - String name; - - /** - * The description of the assistant. - */ - String description; - - /** - * The system instructions that the assistant uses. - */ - String instructions; - - /** - * A list of tools enabled on the assistant. - */ - List tools; - - /** - * A list of file IDs attached to this assistant. - */ - @JsonProperty("file_ids") - List fileIds; - - /** - * Set of 16 key-value pairs that can be attached to an object. - */ - Map metadata; -} diff --git a/api/src/main/java/com/theokanning/openai/assistants/Tool.java b/api/src/main/java/com/theokanning/openai/assistants/Tool.java deleted file mode 100644 index f35af0ef..00000000 --- a/api/src/main/java/com/theokanning/openai/assistants/Tool.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.theokanning.openai.assistants; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -@NoArgsConstructor -@AllArgsConstructor -@Data -public class Tool { - /** - * The type of tool being defined - */ - AssistantToolsEnum type; - - /** - * Function definition, only used if type is "function" - */ - AssistantFunction function; -} diff --git a/api/src/main/java/com/theokanning/openai/audio/CreateSpeechRequest.java b/api/src/main/java/com/theokanning/openai/audio/CreateSpeechRequest.java deleted file mode 100644 index 6d2e69ac..00000000 --- a/api/src/main/java/com/theokanning/openai/audio/CreateSpeechRequest.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.theokanning.openai.audio; - -import com.fasterxml.jackson.annotation.JsonProperty; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.NonNull; - -@Builder -@NoArgsConstructor -@AllArgsConstructor -@Data -public class CreateSpeechRequest { - - /** - * The name of the model to use. - */ - @NonNull - String model; - - /** - * The text to generate audio for. The maximum length is 4096 characters. - */ - @NonNull - String input; - - /** - * The voice to use when generating the audio. - */ - @NonNull - String voice; - - /** - * The format to audio in. Supported formats are mp3, opus, aac, and flac. Defaults to mp3. - */ - @JsonProperty("response_format") - String responseFormat; - - /** - * The speed of the generated audio. Select a value from 0.25 to 4.0. Defaults to 1.0. - */ - Double speed; -} diff --git a/api/src/main/java/com/theokanning/openai/audio/CreateTranscriptionRequest.java b/api/src/main/java/com/theokanning/openai/audio/CreateTranscriptionRequest.java deleted file mode 100644 index 5c50480f..00000000 --- a/api/src/main/java/com/theokanning/openai/audio/CreateTranscriptionRequest.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.theokanning.openai.audio; - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.*; - -/** - * A request for OpenAi to create transcription based on an audio file - * All fields except model are optional - * - * https://platform.openai.com/docs/api-reference/audio/create - */ -@Builder -@NoArgsConstructor -@AllArgsConstructor -@Data -public class CreateTranscriptionRequest { - - /** - * The name of the model to use. - */ - @NonNull - String model; - - /** - * An optional text to guide the model's style or continue a previous audio segment. The prompt should match the audio language. - */ - String prompt; - - /** - * The format of the transcript output, in one of these options: json or verbose_json - */ - @JsonProperty("response_format") - String responseFormat; - - /** - * The sampling temperature, between 0 and 1. - * Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. - * If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit. - */ - Double temperature; - - /** - * The language of the input audio. Supplying the input language in ISO-639-1 format will improve accuracy and latency. - */ - String language; -} diff --git a/api/src/main/java/com/theokanning/openai/audio/CreateTranslationRequest.java b/api/src/main/java/com/theokanning/openai/audio/CreateTranslationRequest.java deleted file mode 100644 index ace5cc36..00000000 --- a/api/src/main/java/com/theokanning/openai/audio/CreateTranslationRequest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.theokanning.openai.audio; - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.*; - -/** - * A request for OpenAi to create English translation based on an audio file - * All fields except model are optional - * - * https://platform.openai.com/docs/api-reference/audio/create - */ -@Builder -@NoArgsConstructor -@AllArgsConstructor -@Data -public class CreateTranslationRequest { - - /** - * The name of the model to use. - */ - @NonNull - String model; - - /** - * An optional text to guide the model's style or continue a previous audio segment. The prompt should be in English. - */ - String prompt; - - /** - * The format of the translated output, in one of these options: json or verbose_json - */ - @JsonProperty("response_format") - String responseFormat; - - /** - * The sampling temperature, between 0 and 1. - * Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. - * If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit. - */ - Double temperature; -} diff --git a/api/src/main/java/com/theokanning/openai/audio/TranscriptionResult.java b/api/src/main/java/com/theokanning/openai/audio/TranscriptionResult.java deleted file mode 100644 index 2794a346..00000000 --- a/api/src/main/java/com/theokanning/openai/audio/TranscriptionResult.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.theokanning.openai.audio; - -import lombok.Data; - -import java.util.List; - -/** - * An object with the text transcription - * - * https://platform.openai.com/docs/api-reference/audio/create - */ -@Data -public class TranscriptionResult { - - /** - * The text transcription. - */ - String text; - - /** - * Task name - * @apiNote verbose_json response format only - */ - String task; - - /** - * Speech language - * @apiNote verbose_json response format only - */ - String language; - - /** - * Speech duration - * @apiNote verbose_json response format only - */ - Double duration; - - /** - * List of segments - * @apiNote verbose_json response format only - */ - List segments; - -} diff --git a/api/src/main/java/com/theokanning/openai/audio/TranscriptionSegment.java b/api/src/main/java/com/theokanning/openai/audio/TranscriptionSegment.java deleted file mode 100644 index 7f382073..00000000 --- a/api/src/main/java/com/theokanning/openai/audio/TranscriptionSegment.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.theokanning.openai.audio; - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.Data; - -import java.util.List; - -/** - * An object represents transcription segment - * - * https://platform.openai.com/docs/api-reference/audio/create - */ -@Data -public class TranscriptionSegment { - - Integer id; - Integer seek; - Double start; - Double end; - String text; - List tokens; - Double temperature; - @JsonProperty("avg_logprob") - Double averageLogProb; - @JsonProperty("compression_ratio") - Double compressionRatio; - @JsonProperty("no_speech_prob") - Double noSpeechProb; - @JsonProperty("transient") - Boolean transientFlag; - -} diff --git a/api/src/main/java/com/theokanning/openai/audio/TranslationResult.java b/api/src/main/java/com/theokanning/openai/audio/TranslationResult.java deleted file mode 100644 index f1f1c446..00000000 --- a/api/src/main/java/com/theokanning/openai/audio/TranslationResult.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.theokanning.openai.audio; - -import lombok.Data; - -import java.util.List; - -/** - * An object with the English transcription - * - * https://platform.openai.com/docs/api-reference/audio/create - */ -@Data -public class TranslationResult { - - /** - * Translated text. - */ - String text; - - /** - * Task name - * @apiNote verbose_json response format only - */ - String task; - - /** - * Translated language - * @apiNote verbose_json response format only - */ - String language; - - /** - * Speech duration - * @apiNote verbose_json response format only - */ - Double duration; - - /** - * List of segments - * @apiNote verbose_json response format only - */ - List segments; - -} diff --git a/api/src/main/java/com/theokanning/openai/billing/BillingUsage.java b/api/src/main/java/com/theokanning/openai/billing/BillingUsage.java deleted file mode 100644 index 3c6db957..00000000 --- a/api/src/main/java/com/theokanning/openai/billing/BillingUsage.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.theokanning.openai.billing; - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.Data; - -import java.math.BigDecimal; -import java.util.List; - -/** - * Amount consumption information - * - */ -@Data -public class BillingUsage { - - @JsonProperty("object") - private String object; - /** - * Account expenditure details - */ - @JsonProperty("daily_costs") - private List dailyCosts; - /** - * Total usage amount: cents - */ - @JsonProperty("total_usage") - private BigDecimal totalUsage; - -} diff --git a/api/src/main/java/com/theokanning/openai/billing/CreditGrantsResponse.java b/api/src/main/java/com/theokanning/openai/billing/CreditGrantsResponse.java deleted file mode 100644 index 71f681d1..00000000 --- a/api/src/main/java/com/theokanning/openai/billing/CreditGrantsResponse.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.theokanning.openai.billing; - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.Data; - -import java.io.Serializable; -import java.math.BigDecimal; - -/** - * Return value of balance inquiry interface - * - */ -@Data -public class CreditGrantsResponse implements Serializable { - private String object; - /** - * Total amount: US dollars - */ - @JsonProperty("total_granted") - private BigDecimal totalGranted; - /** - * Total usage amount: US dollars - */ - @JsonProperty("total_used") - private BigDecimal totalUsed; - /** - * Total remaining amount: US dollars - */ - @JsonProperty("total_available") - private BigDecimal totalAvailable; - /** - * Balance details - */ - private Grants grants; -} diff --git a/api/src/main/java/com/theokanning/openai/billing/DailyCost.java b/api/src/main/java/com/theokanning/openai/billing/DailyCost.java deleted file mode 100644 index 6aede61c..00000000 --- a/api/src/main/java/com/theokanning/openai/billing/DailyCost.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.theokanning.openai.billing; - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.Data; - -import java.util.List; - -/** - * List of amount consumption - * - */ -@Data -public class DailyCost { - /** - * - */ - @JsonProperty("timestamp") - private long timestamp; - /** - * Model consumption amount details - */ - @JsonProperty("line_items") - private List lineItems; -} diff --git a/api/src/main/java/com/theokanning/openai/billing/Datum.java b/api/src/main/java/com/theokanning/openai/billing/Datum.java deleted file mode 100644 index 2eee7b3f..00000000 --- a/api/src/main/java/com/theokanning/openai/billing/Datum.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.theokanning.openai.billing; - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.Data; - -import java.math.BigDecimal; - -/** - * - * - */ -@Data -public class Datum { - private String object; - private String id; - /** - * Gift amount: US dollars - */ - @JsonProperty("grant_amount") - private BigDecimal grantAmount; - /** - * Usage amount: US dollars - */ - @JsonProperty("used_amount") - private BigDecimal usedAmount; - /** - * Effective timestamp - */ - @JsonProperty("effective_at") - private Long effectiveAt; - /** - * Expiration timestamp - */ - @JsonProperty("expires_at") - private Long expiresAt; -} diff --git a/api/src/main/java/com/theokanning/openai/billing/LineItem.java b/api/src/main/java/com/theokanning/openai/billing/LineItem.java deleted file mode 100644 index e12c4912..00000000 --- a/api/src/main/java/com/theokanning/openai/billing/LineItem.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.theokanning.openai.billing; - -import lombok.Data; - -import java.math.BigDecimal; - -/** - * List of amount consumption - * - */ -@Data -public class LineItem { - /** - * model name - */ - private String name; - /** - * Expenditure amount - */ - private BigDecimal cost; -} diff --git a/api/src/main/java/com/theokanning/openai/billing/Plan.java b/api/src/main/java/com/theokanning/openai/billing/Plan.java deleted file mode 100644 index e3db3dd4..00000000 --- a/api/src/main/java/com/theokanning/openai/billing/Plan.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.theokanning.openai.billing; - -import lombok.Data; - -/** - * - * - */ -@Data -public class Plan { - private String title; - private String id; -} diff --git a/api/src/main/java/com/theokanning/openai/billing/Subscription.java b/api/src/main/java/com/theokanning/openai/billing/Subscription.java deleted file mode 100644 index 541e5af6..00000000 --- a/api/src/main/java/com/theokanning/openai/billing/Subscription.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.theokanning.openai.billing; - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.Data; - -/** - * Account information - * - * - */ -@Data -public class Subscription { - @JsonProperty("object") - private String object; - @JsonProperty("has_payment_method") - private boolean hasPaymentMethod; - @JsonProperty("canceled") - private boolean canceled; - @JsonProperty("canceled_at") - private Object canceledAt; - @JsonProperty("delinquent") - private Object delinquent; - @JsonProperty("access_until") - private long accessUntil; - @JsonProperty("soft_limit") - private long softLimit; - @JsonProperty("hard_limit") - private long hardLimit; - @JsonProperty("system_hard_limit") - private long systemHardLimit; - @JsonProperty("soft_limit_usd") - private double softLimitUsd; - @JsonProperty("hard_limit_usd") - private double hardLimitUsd; - @JsonProperty("system_hard_limit_usd") - private double systemHardLimitUsd; - @JsonProperty("plan") - private Plan plan; - @JsonProperty("account_name") - private String accountName; - @JsonProperty("po_number") - private Object poNumber; - @JsonProperty("billing_email") - private Object billingEmail; - @JsonProperty("tax_ids") - private Object taxIds; - @JsonProperty("billing_address") - private Object billingAddress; - @JsonProperty("business_address") - private Object businessAddress; -} diff --git a/api/src/main/java/com/theokanning/openai/completion/CompletionChoice.java b/api/src/main/java/com/theokanning/openai/completion/CompletionChoice.java deleted file mode 100644 index c24ef7b4..00000000 --- a/api/src/main/java/com/theokanning/openai/completion/CompletionChoice.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.theokanning.openai.completion; - -import lombok.Data; - -/** - * A completion generated by OpenAI - * - * https://beta.openai.com/docs/api-reference/completions/create - */ -@Data -public class CompletionChoice { - /** - * The generated text. Will include the prompt if {@link CompletionRequest#echo } is true - */ - String text; - - /** - * This index of this completion in the returned list. - */ - Integer index; - - /** - * The log probabilities of the chosen tokens and the top {@link CompletionRequest#logprobs} tokens - */ - LogProbResult logprobs; - - /** - * The reason why GPT stopped generating, for example "length". - */ - String finish_reason; -} diff --git a/api/src/main/java/com/theokanning/openai/completion/CompletionChunk.java b/api/src/main/java/com/theokanning/openai/completion/CompletionChunk.java deleted file mode 100644 index 2fa6fd09..00000000 --- a/api/src/main/java/com/theokanning/openai/completion/CompletionChunk.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.theokanning.openai.completion; - -import lombok.Data; -import java.util.List; - -/** - * Object containing a response chunk from the completions streaming api. - * - * https://beta.openai.com/docs/api-reference/completions/create - */ -@Data -public class CompletionChunk { - /** - * A unique id assigned to this completion. - */ - String id; - - /**https://beta.openai.com/docs/api-reference/create-completion - * The type of object returned, should be "text_completion" - */ - String object; - - /** - * The creation time in epoch seconds. - */ - long created; - - /** - * The model used. - */ - String model; - - /** - * A list of generated completions. - */ - List choices; -} diff --git a/api/src/main/java/com/theokanning/openai/completion/CompletionRequest.java b/api/src/main/java/com/theokanning/openai/completion/CompletionRequest.java deleted file mode 100644 index f7bca93c..00000000 --- a/api/src/main/java/com/theokanning/openai/completion/CompletionRequest.java +++ /dev/null @@ -1,140 +0,0 @@ -package com.theokanning.openai.completion; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.util.List; -import java.util.Map; - -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * A request for OpenAi to generate a predicted completion for a prompt. - * All fields are nullable. - * - * https://beta.openai.com/docs/api-reference/completions/create - */ -@Builder -@NoArgsConstructor -@AllArgsConstructor -@Data -public class CompletionRequest { - - /** - * The name of the model to use. - * Required if specifying a fine-tuned model or if using the new v1/completions endpoint. - */ - String model; - - /** - * An optional prompt to complete from - */ - String prompt; - - /** - * The suffix that comes after a completion of inserted text. - */ - String suffix; - - /** - * The maximum number of tokens to generate. - * Requests can use up to 2048 tokens shared between prompt and completion. - * (One token is roughly 4 characters for normal English text) - */ - @JsonProperty("max_tokens") - Integer maxTokens; - - /** - * What sampling temperature to use. Higher values means the model will take more risks. - * Try 0.9 for more creative applications, and 0 (argmax sampling) for ones with a well-defined answer. - * - * We generally recommend using this or {@link CompletionRequest#topP} but not both. - */ - Double temperature; - - /** - * An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of - * the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are - * considered. - * - * We generally recommend using this or {@link CompletionRequest#temperature} but not both. - */ - @JsonProperty("top_p") - Double topP; - - /** - * How many completions to generate for each prompt. - * - * Because this parameter generates many completions, it can quickly consume your token quota. - * Use carefully and ensure that you have reasonable settings for {@link CompletionRequest#maxTokens} and {@link CompletionRequest#stop}. - */ - Integer n; - - /** - * Whether to stream back partial progress. - * If set, tokens will be sent as data-only server-sent events as they become available, - * with the stream terminated by a data: DONE message. - */ - Boolean stream; - - /** - * Include the log probabilities on the logprobs most likely tokens, as well the chosen tokens. - * For example, if logprobs is 10, the API will return a list of the 10 most likely tokens. - * The API will always return the logprob of the sampled token, - * so there may be up to logprobs+1 elements in the response. - */ - Integer logprobs; - - /** - * Echo back the prompt in addition to the completion - */ - Boolean echo; - - /** - * Up to 4 sequences where the API will stop generating further tokens. - * The returned text will not contain the stop sequence. - */ - List stop; - - /** - * Number between 0 and 1 (default 0) that penalizes new tokens based on whether they appear in the text so far. - * Increases the model's likelihood to talk about new topics. - */ - @JsonProperty("presence_penalty") - Double presencePenalty; - - /** - * Number between 0 and 1 (default 0) that penalizes new tokens based on their existing frequency in the text so far. - * Decreases the model's likelihood to repeat the same line verbatim. - */ - @JsonProperty("frequency_penalty") - Double frequencyPenalty; - - /** - * Generates best_of completions server-side and returns the "best" - * (the one with the lowest log probability per token). - * Results cannot be streamed. - * - * When used with {@link CompletionRequest#n}, best_of controls the number of candidate completions and n specifies how many to return, - * best_of must be greater than n. - */ - @JsonProperty("best_of") - Integer bestOf; - - /** - * Modify the likelihood of specified tokens appearing in the completion. - * - * Maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. - * - * https://beta.openai.com/docs/api-reference/completions/create#completions/create-logit_bias - */ - @JsonProperty("logit_bias") - Map logitBias; - - /** - * A unique identifier representing your end-user, which will help OpenAI to monitor and detect abuse. - */ - String user; -} diff --git a/api/src/main/java/com/theokanning/openai/completion/CompletionResult.java b/api/src/main/java/com/theokanning/openai/completion/CompletionResult.java deleted file mode 100644 index d63d5c73..00000000 --- a/api/src/main/java/com/theokanning/openai/completion/CompletionResult.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.theokanning.openai.completion; - -import com.theokanning.openai.Usage; -import lombok.Data; - -import java.util.List; - -/** - * An object containing a response from the completion api - * - * https://beta.openai.com/docs/api-reference/completions/create - */ -@Data -public class CompletionResult { - /** - * A unique id assigned to this completion. - */ - String id; - - /**https://beta.openai.com/docs/api-reference/create-completion - * The type of object returned, should be "text_completion" - */ - String object; - - /** - * The creation time in epoch seconds. - */ - long created; - - /** - * The GPT model used. - */ - String model; - - /** - * A list of generated completions. - */ - List choices; - - /** - * The API usage for this request - */ - Usage usage; -} diff --git a/api/src/main/java/com/theokanning/openai/completion/LogProbResult.java b/api/src/main/java/com/theokanning/openai/completion/LogProbResult.java deleted file mode 100644 index a631dada..00000000 --- a/api/src/main/java/com/theokanning/openai/completion/LogProbResult.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.theokanning.openai.completion; - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.Data; - -import java.util.List; -import java.util.Map; - -/** - * Log probabilities of different token options - * Returned if {@link CompletionRequest#logprobs} is greater than zero - * - * https://beta.openai.com/docs/api-reference/create-completion - */ -@Data -public class LogProbResult { - - /** - * The tokens chosen by the completion api - */ - List tokens; - - /** - * The log probability of each token in {@link tokens} - */ - @JsonProperty("token_logprobs") - List tokenLogprobs; - - /** - * A map for each index in the completion result. - * The map contains the top {@link CompletionRequest#logprobs} tokens and their probabilities - */ - @JsonProperty("top_logprobs") - List> topLogprobs; - - /** - * The character offset from the start of the returned text for each of the chosen tokens. - */ - List textOffset; -} diff --git a/api/src/main/java/com/theokanning/openai/completion/chat/ChatCompletionChoice.java b/api/src/main/java/com/theokanning/openai/completion/chat/ChatCompletionChoice.java deleted file mode 100644 index 7bb88698..00000000 --- a/api/src/main/java/com/theokanning/openai/completion/chat/ChatCompletionChoice.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.theokanning.openai.completion.chat; -import com.fasterxml.jackson.annotation.JsonAlias; -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.Data; - -/** - * A chat completion generated by OpenAI - */ -@Data -public class ChatCompletionChoice { - - /** - * This index of this completion in the returned list. - */ - Integer index; - - /** - * The {@link ChatMessageRole#assistant} message or delta (when streaming) which was generated - */ - @JsonAlias("delta") - ChatMessage message; - - /** - * The reason why GPT stopped generating, for example "length". - */ - @JsonProperty("finish_reason") - String finishReason; -} diff --git a/api/src/main/java/com/theokanning/openai/completion/chat/ChatCompletionChunk.java b/api/src/main/java/com/theokanning/openai/completion/chat/ChatCompletionChunk.java deleted file mode 100644 index 4bbab2b9..00000000 --- a/api/src/main/java/com/theokanning/openai/completion/chat/ChatCompletionChunk.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.theokanning.openai.completion.chat; -import lombok.Data; - -import java.util.List; - -/** - * Object containing a response chunk from the chat completions streaming api. - */ -@Data -public class ChatCompletionChunk { - /** - * Unique id assigned to this chat completion. - */ - String id; - - /** - * The type of object returned, should be "chat.completion.chunk" - */ - String object; - - /** - * The creation time in epoch seconds. - */ - long created; - - /** - * The model used. - */ - String model; - - /** - * A list of all generated completions. - */ - List choices; -} \ No newline at end of file diff --git a/api/src/main/java/com/theokanning/openai/completion/chat/ChatCompletionRequest.java b/api/src/main/java/com/theokanning/openai/completion/chat/ChatCompletionRequest.java deleted file mode 100644 index e4479ff3..00000000 --- a/api/src/main/java/com/theokanning/openai/completion/chat/ChatCompletionRequest.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.theokanning.openai.completion.chat; - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.util.List; -import java.util.Map; - -@Data -@Builder -@AllArgsConstructor -@NoArgsConstructor -public class ChatCompletionRequest { - - /** - * ID of the model to use. - */ - String model; - - /** - * The messages to generate chat completions for, in the chat format.
- * see {@link ChatMessage} - */ - List messages; - - /** - * 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.
- * We generally recommend altering this or top_p but not both. - */ - Double temperature; - - /** - * An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens - * with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.
- * We generally recommend altering this or temperature but not both. - */ - @JsonProperty("top_p") - Double topP; - - /** - * How many chat completion chatCompletionChoices to generate for each input message. - */ - Integer n; - - /** - * If set, partial message deltas will be sent, like in ChatGPT. Tokens will be sent as data-only server-sent - * events as they become available, with the stream terminated by a data: [DONE] message. - */ - Boolean stream; - - /** - * Up to 4 sequences where the API will stop generating further tokens. - */ - List stop; - - /** - * The maximum number of tokens allowed for the generated answer. By default, the number of tokens the model can return will - * be (4096 - prompt tokens). - */ - @JsonProperty("max_tokens") - Integer maxTokens; - - /** - * Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, - * increasing the model's likelihood to talk about new topics. - */ - @JsonProperty("presence_penalty") - Double presencePenalty; - - /** - * Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, - * decreasing the model's likelihood to repeat the same line verbatim. - */ - @JsonProperty("frequency_penalty") - Double frequencyPenalty; - - /** - * Accepts a json object that maps tokens (specified by their token ID in the tokenizer) to an associated bias value from -100 - * to 100. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will - * vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 - * should result in a ban or exclusive selection of the relevant token. - */ - @JsonProperty("logit_bias") - Map logitBias; - - - /** - * A unique identifier representing your end-user, which will help OpenAI to monitor and detect abuse. - */ - String user; - - /** - * A list of the available functions. - */ - List functions; - - /** - * Controls how the model responds to function calls, as specified in the OpenAI documentation. - */ - @JsonProperty("function_call") - ChatCompletionRequestFunctionCall functionCall; - - @Data - @Builder - @AllArgsConstructor - @NoArgsConstructor - public static class ChatCompletionRequestFunctionCall { - String name; - - public static ChatCompletionRequestFunctionCall of(String name) { - return new ChatCompletionRequestFunctionCall(name); - } - - } -} diff --git a/api/src/main/java/com/theokanning/openai/completion/chat/ChatCompletionResult.java b/api/src/main/java/com/theokanning/openai/completion/chat/ChatCompletionResult.java deleted file mode 100644 index 11b4071a..00000000 --- a/api/src/main/java/com/theokanning/openai/completion/chat/ChatCompletionResult.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.theokanning.openai.completion.chat; -import com.theokanning.openai.Usage; -import lombok.Data; - -import java.util.List; - -/** - * Object containing a response from the chat completions api. - */ -@Data -public class ChatCompletionResult { - - /** - * Unique id assigned to this chat completion. - */ - String id; - - /** - * The type of object returned, should be "chat.completion" - */ - String object; - - /** - * The creation time in epoch seconds. - */ - long created; - - /** - * The GPT model used. - */ - String model; - - /** - * A list of all generated completions. - */ - List choices; - - /** - * The API usage for this request. - */ - Usage usage; - -} diff --git a/api/src/main/java/com/theokanning/openai/completion/chat/ChatFunction.java b/api/src/main/java/com/theokanning/openai/completion/chat/ChatFunction.java deleted file mode 100644 index 820f4bd6..00000000 --- a/api/src/main/java/com/theokanning/openai/completion/chat/ChatFunction.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.theokanning.openai.completion.chat; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.NonNull; - -import java.util.function.Function; - -@Data -@NoArgsConstructor -public class ChatFunction { - - /** - * The name of the function being called. - */ - @NonNull - private String name; - - /** - * A description of what the function does, used by the model to choose when and how to call the function. - */ - private String description; - - /** - * The parameters the functions accepts. - */ - @JsonProperty("parameters") - private Class parametersClass; - - @JsonIgnore - private Function executor; - - public static Builder builder() { - return new Builder(); - } - - public static class Builder { - private String name; - private String description; - private Class parameters; - private Function executor; - - public Builder name(String name) { - this.name = name; - return this; - } - - public Builder description(String description) { - this.description = description; - return this; - } - - public Builder executor(Class requestClass, Function executor) { - this.parameters = requestClass; - this.executor = (Function) executor; - return this; - } - - public ChatFunction build() { - ChatFunction chatFunction = new ChatFunction(); - chatFunction.setName(name); - chatFunction.setDescription(description); - chatFunction.setParametersClass(parameters); - chatFunction.setExecutor(executor); - return chatFunction; - } - } -} \ No newline at end of file diff --git a/api/src/main/java/com/theokanning/openai/completion/chat/ChatFunctionCall.java b/api/src/main/java/com/theokanning/openai/completion/chat/ChatFunctionCall.java deleted file mode 100644 index 962fbe12..00000000 --- a/api/src/main/java/com/theokanning/openai/completion/chat/ChatFunctionCall.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.theokanning.openai.completion.chat; - -import com.fasterxml.jackson.databind.JsonNode; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -@Data -@AllArgsConstructor -@NoArgsConstructor -public class ChatFunctionCall { - - /** - * The name of the function being called - */ - String name; - - /** - * The arguments of the call produced by the model, represented as a JsonNode for easy manipulation. - */ - JsonNode arguments; - -} diff --git a/api/src/main/java/com/theokanning/openai/completion/chat/ChatFunctionDynamic.java b/api/src/main/java/com/theokanning/openai/completion/chat/ChatFunctionDynamic.java deleted file mode 100644 index 9b4f2070..00000000 --- a/api/src/main/java/com/theokanning/openai/completion/chat/ChatFunctionDynamic.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.theokanning.openai.completion.chat; - -import lombok.Data; -import lombok.NonNull; - - -@Data -public class ChatFunctionDynamic { - - /** - * The name of the function being called. - */ - @NonNull - private String name; - - /** - * A description of what the function does, used by the model to choose when and how to call the function. - */ - private String description; - - /** - * The parameters the functions accepts. - */ - private ChatFunctionParameters parameters; - - public static Builder builder() { - return new Builder(); - } - - public static class Builder { - private String name; - private String description; - private ChatFunctionParameters parameters = new ChatFunctionParameters(); - - public Builder name(String name) { - this.name = name; - return this; - } - - public Builder description(String description) { - this.description = description; - return this; - } - - public Builder parameters(ChatFunctionParameters parameters) { - this.parameters = parameters; - return this; - } - - public Builder addProperty(ChatFunctionProperty property) { - this.parameters.addProperty(property); - return this; - } - - public ChatFunctionDynamic build() { - ChatFunctionDynamic chatFunction = new ChatFunctionDynamic(name); - chatFunction.setDescription(description); - chatFunction.setParameters(parameters); - return chatFunction; - } - } -} diff --git a/api/src/main/java/com/theokanning/openai/completion/chat/ChatFunctionParameters.java b/api/src/main/java/com/theokanning/openai/completion/chat/ChatFunctionParameters.java deleted file mode 100644 index fee71e8f..00000000 --- a/api/src/main/java/com/theokanning/openai/completion/chat/ChatFunctionParameters.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.theokanning.openai.completion.chat; - -import lombok.Data; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -@Data -public class ChatFunctionParameters { - - private final String type = "object"; - - private final HashMap properties = new HashMap<>(); - - private List required; - - public void addProperty(ChatFunctionProperty property) { - properties.put(property.getName(), property); - if (Boolean.TRUE.equals(property.getRequired())) { - if (this.required == null) { - this.required = new ArrayList<>(); - } - this.required.add(property.getName()); - } - } -} diff --git a/api/src/main/java/com/theokanning/openai/completion/chat/ChatFunctionProperty.java b/api/src/main/java/com/theokanning/openai/completion/chat/ChatFunctionProperty.java deleted file mode 100644 index 3e695933..00000000 --- a/api/src/main/java/com/theokanning/openai/completion/chat/ChatFunctionProperty.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.theokanning.openai.completion.chat; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.Builder; -import lombok.Data; -import lombok.NonNull; - -import java.util.Set; - -@Data -@Builder -public class ChatFunctionProperty { - @NonNull - @JsonIgnore - private String name; - @NonNull - private String type; - @JsonIgnore - private Boolean required; - private String description; - private ChatFunctionProperty items; - @JsonProperty("enum") - private Set enumValues; -} \ No newline at end of file diff --git a/api/src/main/java/com/theokanning/openai/completion/chat/ChatMessageRole.java b/api/src/main/java/com/theokanning/openai/completion/chat/ChatMessageRole.java deleted file mode 100644 index 255641e0..00000000 --- a/api/src/main/java/com/theokanning/openai/completion/chat/ChatMessageRole.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.theokanning.openai.completion.chat; - -/** - * see {@link ChatMessage} documentation. - */ -public enum ChatMessageRole { - SYSTEM("system"), - USER("user"), - ASSISTANT("assistant"), - FUNCTION("function"); - - private final String value; - - ChatMessageRole(final String value) { - this.value = value; - } - - public String value() { - return value; - } -} diff --git a/api/src/main/java/com/theokanning/openai/edit/EditChoice.java b/api/src/main/java/com/theokanning/openai/edit/EditChoice.java deleted file mode 100644 index 98c7c5a9..00000000 --- a/api/src/main/java/com/theokanning/openai/edit/EditChoice.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.theokanning.openai.edit; - -import lombok.Data; - -/** - * An edit generated by OpenAi - * - * https://beta.openai.com/docs/api-reference/edits/create - */ -@Data -public class EditChoice { - - /** - * The edited text. - */ - String text; - - /** - * This index of this completion in the returned list. - */ - Integer index; -} diff --git a/api/src/main/java/com/theokanning/openai/edit/EditRequest.java b/api/src/main/java/com/theokanning/openai/edit/EditRequest.java deleted file mode 100644 index b84ecdc4..00000000 --- a/api/src/main/java/com/theokanning/openai/edit/EditRequest.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.theokanning.openai.edit; - -import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.*; - -/** - * Given a prompt and an instruction, OpenAi will return an edited version of the prompt - * - * https://beta.openai.com/docs/api-reference/edits/create - */ -@Builder -@NoArgsConstructor -@AllArgsConstructor -@Data -public class EditRequest { - - /** - * The name of the model to use. - * Required if using the new v1/edits endpoint. - */ - String model; - - /** - * The input text to use as a starting point for the edit. - */ - String input; - - /** - * The instruction that tells the model how to edit the prompt. - * For example, "Fix the spelling mistakes" - */ - @NonNull - String instruction; - - /** - * How many edits to generate for the input and instruction. - */ - Integer n; - - /** - * What sampling temperature to use. Higher values means the model will take more risks. - * Try 0.9 for more creative applications, and 0 (argmax sampling) for ones with a well-defined answer. - * - * We generally recommend altering this or {@link EditRequest#topP} but not both. - */ - Double temperature; - - /** - * An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of - * the tokens with top_p probability mass.So 0.1 means only the tokens comprising the top 10% probability mass are - * considered. - * - * We generally recommend altering this or {@link EditRequest#temperature} but not both. - */ - @JsonProperty("top_p") - Double topP; -} diff --git a/api/src/main/java/com/theokanning/openai/edit/EditResult.java b/api/src/main/java/com/theokanning/openai/edit/EditResult.java deleted file mode 100644 index 7816ba0e..00000000 --- a/api/src/main/java/com/theokanning/openai/edit/EditResult.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.theokanning.openai.edit; - -import com.theokanning.openai.Usage; -import lombok.Data; - -import java.util.List; - -/** - * A list of edits generated by OpenAI - * - * https://beta.openai.com/docs/api-reference/edits/create - */ -@Data -public class EditResult { - - /** - * The type of object returned, should be "edit" - */ - public String object; - - /** - * The creation time in epoch milliseconds. - */ - public long created; - - /** - * A list of generated edits. - */ - public List choices; - - /** - * The API usage for this request - */ - public Usage usage; -} diff --git a/api/src/main/java/com/theokanning/openai/image/CreateImageRequest.java b/api/src/main/java/com/theokanning/openai/image/CreateImageRequest.java deleted file mode 100644 index 13672c24..00000000 --- a/api/src/main/java/com/theokanning/openai/image/CreateImageRequest.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.theokanning.openai.image; - -import com.fasterxml.jackson.annotation.JsonProperty; - -import lombok.*; - -/** - * A request for OpenAi to create an image based on a prompt - * All fields except prompt are optional - * - * https://beta.openai.com/docs/api-reference/images/create - */ -@Builder -@NoArgsConstructor -@AllArgsConstructor -@Data -public class CreateImageRequest { - - /** - * A text description of the desired image(s). The maximum length is 1000 characters for dall-e-2 and 4000 characters for dall-e-3. - */ - @NonNull - String prompt; - - /** - * The model to use for image generation. Defaults to "dall-e-2". - */ - String model; - - /** - * The number of images to generate. Must be between 1 and 10. For dall-e-3, only n=1 is supported. Defaults to 1. - */ - Integer n; - - /** - * The quality of the image that will be generated. "hd" creates images with finer details and greater consistency across the image. This param is only supported for dall-e-3. Defaults to "standard". - */ - String quality; - - /** - * The size of the generated images. Must be one of 256x256, 512x512, or 1024x1024 for dall-e-2. Must be one of 1024x1024, 1792x1024, or 1024x1792 for dall-e-3 models. Defaults to 1024x1024. - */ - String size; - - /** - * The format in which the generated images are returned. Must be one of url or b64_json. Defaults to url. - */ - @JsonProperty("response_format") - String responseFormat; - - /** - * The style of the generated images. Must be one of vivid or natural. Vivid causes the model to lean towards generating hyper-real and dramatic images. Natural causes the model to produce more natural, less hyper-real looking images. This param is only supported for dall-e-3. Defaults to vivid. - */ - String style; - - /** - * A unique identifier representing your end-user, which will help OpenAI to monitor and detect abuse. - */ - String user; -} diff --git a/api/src/test/java/com/theokanning/openai/JsonTest.java b/api/src/test/java/com/launchableinc/openai/JsonTest.java similarity index 100% rename from api/src/test/java/com/theokanning/openai/JsonTest.java rename to api/src/test/java/com/launchableinc/openai/JsonTest.java diff --git a/api/src/test/java/com/launchableinc/openai/ListSearchParameters.java b/api/src/test/java/com/launchableinc/openai/ListSearchParameters.java new file mode 100644 index 00000000..15b12b07 --- /dev/null +++ b/api/src/test/java/com/launchableinc/openai/ListSearchParameters.java @@ -0,0 +1,52 @@ +package com.launchableinc.openai; + +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * Common options when getting a list of objects + */ +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Data +public class ListSearchParameters { + + /** + * A limit on the number of objects to be returned. Limit can range between 1 and 100, and the + * default is 20 + */ + + Integer limit; + + /** + * Sort order by the 'created_at' timestamp of the objects. 'asc' for ascending order and 'desc' + * for descending order. + */ + Order order; + + /** + * 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 + */ + String after; + + /** + * 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. + */ + String before; + + public enum Order { + @JsonProperty("asc") + ASCENDING, + + @JsonProperty("desc") + DESCENDING + } +} diff --git a/client/src/main/java/com/theokanning/openai/AuthenticationInterceptor.java b/client/src/main/java/com/launchableinc/openai/AuthenticationInterceptor.java similarity index 100% rename from client/src/main/java/com/theokanning/openai/AuthenticationInterceptor.java rename to client/src/main/java/com/launchableinc/openai/AuthenticationInterceptor.java diff --git a/client/src/main/java/com/theokanning/openai/OpenAiApi.java b/client/src/main/java/com/launchableinc/openai/OpenAiApi.java similarity index 100% rename from client/src/main/java/com/theokanning/openai/OpenAiApi.java rename to client/src/main/java/com/launchableinc/openai/OpenAiApi.java diff --git a/client/src/main/java/com/theokanning/openai/client/AuthenticationInterceptor.java b/client/src/main/java/com/launchableinc/openai/client/AuthenticationInterceptor.java similarity index 100% rename from client/src/main/java/com/theokanning/openai/client/AuthenticationInterceptor.java rename to client/src/main/java/com/launchableinc/openai/client/AuthenticationInterceptor.java diff --git a/client/src/main/java/com/theokanning/openai/client/OpenAiApi.java b/client/src/main/java/com/launchableinc/openai/client/OpenAiApi.java similarity index 100% rename from client/src/main/java/com/theokanning/openai/client/OpenAiApi.java rename to client/src/main/java/com/launchableinc/openai/client/OpenAiApi.java diff --git a/service/src/main/java/com/theokanning/openai/service/AuthenticationInterceptor.java b/service/src/main/java/com/launchableinc/openai/service/AuthenticationInterceptor.java similarity index 100% rename from service/src/main/java/com/theokanning/openai/service/AuthenticationInterceptor.java rename to service/src/main/java/com/launchableinc/openai/service/AuthenticationInterceptor.java diff --git a/service/src/main/java/com/theokanning/openai/service/ChatCompletionRequestMixIn.java b/service/src/main/java/com/launchableinc/openai/service/ChatCompletionRequestMixIn.java similarity index 100% rename from service/src/main/java/com/theokanning/openai/service/ChatCompletionRequestMixIn.java rename to service/src/main/java/com/launchableinc/openai/service/ChatCompletionRequestMixIn.java diff --git a/service/src/main/java/com/theokanning/openai/service/ChatCompletionRequestSerializerAndDeserializer.java b/service/src/main/java/com/launchableinc/openai/service/ChatCompletionRequestSerializerAndDeserializer.java similarity index 100% rename from service/src/main/java/com/theokanning/openai/service/ChatCompletionRequestSerializerAndDeserializer.java rename to service/src/main/java/com/launchableinc/openai/service/ChatCompletionRequestSerializerAndDeserializer.java diff --git a/service/src/main/java/com/theokanning/openai/service/ChatFunctionCallArgumentsSerializerAndDeserializer.java b/service/src/main/java/com/launchableinc/openai/service/ChatFunctionCallArgumentsSerializerAndDeserializer.java similarity index 100% rename from service/src/main/java/com/theokanning/openai/service/ChatFunctionCallArgumentsSerializerAndDeserializer.java rename to service/src/main/java/com/launchableinc/openai/service/ChatFunctionCallArgumentsSerializerAndDeserializer.java diff --git a/service/src/main/java/com/theokanning/openai/service/ChatFunctionCallMixIn.java b/service/src/main/java/com/launchableinc/openai/service/ChatFunctionCallMixIn.java similarity index 100% rename from service/src/main/java/com/theokanning/openai/service/ChatFunctionCallMixIn.java rename to service/src/main/java/com/launchableinc/openai/service/ChatFunctionCallMixIn.java diff --git a/service/src/main/java/com/theokanning/openai/service/ChatFunctionMixIn.java b/service/src/main/java/com/launchableinc/openai/service/ChatFunctionMixIn.java similarity index 100% rename from service/src/main/java/com/theokanning/openai/service/ChatFunctionMixIn.java rename to service/src/main/java/com/launchableinc/openai/service/ChatFunctionMixIn.java diff --git a/service/src/main/java/com/theokanning/openai/service/ChatFunctionParametersSerializer.java b/service/src/main/java/com/launchableinc/openai/service/ChatFunctionParametersSerializer.java similarity index 100% rename from service/src/main/java/com/theokanning/openai/service/ChatFunctionParametersSerializer.java rename to service/src/main/java/com/launchableinc/openai/service/ChatFunctionParametersSerializer.java diff --git a/service/src/main/java/com/theokanning/openai/service/ChatMessageAccumulator.java b/service/src/main/java/com/launchableinc/openai/service/ChatMessageAccumulator.java similarity index 100% rename from service/src/main/java/com/theokanning/openai/service/ChatMessageAccumulator.java rename to service/src/main/java/com/launchableinc/openai/service/ChatMessageAccumulator.java diff --git a/service/src/main/java/com/theokanning/openai/service/FunctionExecutor.java b/service/src/main/java/com/launchableinc/openai/service/FunctionExecutor.java similarity index 100% rename from service/src/main/java/com/theokanning/openai/service/FunctionExecutor.java rename to service/src/main/java/com/launchableinc/openai/service/FunctionExecutor.java diff --git a/service/src/main/java/com/theokanning/openai/service/OpenAiService.java b/service/src/main/java/com/launchableinc/openai/service/OpenAiService.java similarity index 100% rename from service/src/main/java/com/theokanning/openai/service/OpenAiService.java rename to service/src/main/java/com/launchableinc/openai/service/OpenAiService.java diff --git a/service/src/main/java/com/theokanning/openai/service/ResponseBodyCallback.java b/service/src/main/java/com/launchableinc/openai/service/ResponseBodyCallback.java similarity index 100% rename from service/src/main/java/com/theokanning/openai/service/ResponseBodyCallback.java rename to service/src/main/java/com/launchableinc/openai/service/ResponseBodyCallback.java diff --git a/service/src/main/java/com/theokanning/openai/service/SSE.java b/service/src/main/java/com/launchableinc/openai/service/SSE.java similarity index 100% rename from service/src/main/java/com/theokanning/openai/service/SSE.java rename to service/src/main/java/com/launchableinc/openai/service/SSE.java diff --git a/service/src/main/java/com/theokanning/openai/service/SSEFormatException.java b/service/src/main/java/com/launchableinc/openai/service/SSEFormatException.java similarity index 100% rename from service/src/main/java/com/theokanning/openai/service/SSEFormatException.java rename to service/src/main/java/com/launchableinc/openai/service/SSEFormatException.java diff --git a/service/src/test/java/com/theokanning/openai/service/AssistantFunctionTest.java b/service/src/test/java/com/launchableinc/openai/service/AssistantFunctionTest.java similarity index 100% rename from service/src/test/java/com/theokanning/openai/service/AssistantFunctionTest.java rename to service/src/test/java/com/launchableinc/openai/service/AssistantFunctionTest.java diff --git a/service/src/test/java/com/theokanning/openai/service/AssistantTest.java b/service/src/test/java/com/launchableinc/openai/service/AssistantTest.java similarity index 100% rename from service/src/test/java/com/theokanning/openai/service/AssistantTest.java rename to service/src/test/java/com/launchableinc/openai/service/AssistantTest.java diff --git a/service/src/test/java/com/theokanning/openai/service/AudioTest.java b/service/src/test/java/com/launchableinc/openai/service/AudioTest.java similarity index 100% rename from service/src/test/java/com/theokanning/openai/service/AudioTest.java rename to service/src/test/java/com/launchableinc/openai/service/AudioTest.java diff --git a/service/src/test/java/com/theokanning/openai/service/ChatCompletionTest.java b/service/src/test/java/com/launchableinc/openai/service/ChatCompletionTest.java similarity index 100% rename from service/src/test/java/com/theokanning/openai/service/ChatCompletionTest.java rename to service/src/test/java/com/launchableinc/openai/service/ChatCompletionTest.java diff --git a/service/src/test/java/com/theokanning/openai/service/CompletionTest.java b/service/src/test/java/com/launchableinc/openai/service/CompletionTest.java similarity index 100% rename from service/src/test/java/com/theokanning/openai/service/CompletionTest.java rename to service/src/test/java/com/launchableinc/openai/service/CompletionTest.java diff --git a/service/src/test/java/com/theokanning/openai/service/EditTest.java b/service/src/test/java/com/launchableinc/openai/service/EditTest.java similarity index 100% rename from service/src/test/java/com/theokanning/openai/service/EditTest.java rename to service/src/test/java/com/launchableinc/openai/service/EditTest.java diff --git a/service/src/test/java/com/theokanning/openai/service/EmbeddingTest.java b/service/src/test/java/com/launchableinc/openai/service/EmbeddingTest.java similarity index 100% rename from service/src/test/java/com/theokanning/openai/service/EmbeddingTest.java rename to service/src/test/java/com/launchableinc/openai/service/EmbeddingTest.java diff --git a/service/src/test/java/com/theokanning/openai/service/FileTest.java b/service/src/test/java/com/launchableinc/openai/service/FileTest.java similarity index 100% rename from service/src/test/java/com/theokanning/openai/service/FileTest.java rename to service/src/test/java/com/launchableinc/openai/service/FileTest.java diff --git a/service/src/test/java/com/theokanning/openai/service/FineTuneTest.java b/service/src/test/java/com/launchableinc/openai/service/FineTuneTest.java similarity index 100% rename from service/src/test/java/com/theokanning/openai/service/FineTuneTest.java rename to service/src/test/java/com/launchableinc/openai/service/FineTuneTest.java diff --git a/service/src/test/java/com/theokanning/openai/service/FineTuningTest.java b/service/src/test/java/com/launchableinc/openai/service/FineTuningTest.java similarity index 100% rename from service/src/test/java/com/theokanning/openai/service/FineTuningTest.java rename to service/src/test/java/com/launchableinc/openai/service/FineTuningTest.java diff --git a/service/src/test/java/com/theokanning/openai/service/ImageTest.java b/service/src/test/java/com/launchableinc/openai/service/ImageTest.java similarity index 100% rename from service/src/test/java/com/theokanning/openai/service/ImageTest.java rename to service/src/test/java/com/launchableinc/openai/service/ImageTest.java diff --git a/service/src/test/java/com/theokanning/openai/service/MessageTest.java b/service/src/test/java/com/launchableinc/openai/service/MessageTest.java similarity index 100% rename from service/src/test/java/com/theokanning/openai/service/MessageTest.java rename to service/src/test/java/com/launchableinc/openai/service/MessageTest.java diff --git a/service/src/test/java/com/theokanning/openai/service/ModelTest.java b/service/src/test/java/com/launchableinc/openai/service/ModelTest.java similarity index 100% rename from service/src/test/java/com/theokanning/openai/service/ModelTest.java rename to service/src/test/java/com/launchableinc/openai/service/ModelTest.java diff --git a/service/src/test/java/com/theokanning/openai/service/ModerationTest.java b/service/src/test/java/com/launchableinc/openai/service/ModerationTest.java similarity index 100% rename from service/src/test/java/com/theokanning/openai/service/ModerationTest.java rename to service/src/test/java/com/launchableinc/openai/service/ModerationTest.java diff --git a/service/src/test/java/com/theokanning/openai/service/OpenAiServiceTest.java b/service/src/test/java/com/launchableinc/openai/service/OpenAiServiceTest.java similarity index 100% rename from service/src/test/java/com/theokanning/openai/service/OpenAiServiceTest.java rename to service/src/test/java/com/launchableinc/openai/service/OpenAiServiceTest.java diff --git a/service/src/test/java/com/theokanning/openai/service/ResponseBodyCallbackTest.java b/service/src/test/java/com/launchableinc/openai/service/ResponseBodyCallbackTest.java similarity index 100% rename from service/src/test/java/com/theokanning/openai/service/ResponseBodyCallbackTest.java rename to service/src/test/java/com/launchableinc/openai/service/ResponseBodyCallbackTest.java diff --git a/service/src/test/java/com/theokanning/openai/service/RunTest.java b/service/src/test/java/com/launchableinc/openai/service/RunTest.java similarity index 100% rename from service/src/test/java/com/theokanning/openai/service/RunTest.java rename to service/src/test/java/com/launchableinc/openai/service/RunTest.java diff --git a/service/src/test/java/com/theokanning/openai/service/ThreadTest.java b/service/src/test/java/com/launchableinc/openai/service/ThreadTest.java similarity index 100% rename from service/src/test/java/com/theokanning/openai/service/ThreadTest.java rename to service/src/test/java/com/launchableinc/openai/service/ThreadTest.java From 472e96a6f89539b489d32477e9cd1f1b4f9dbda2 Mon Sep 17 00:00:00 2001 From: Konboi Date: Fri, 16 Feb 2024 13:51:00 +0900 Subject: [PATCH 05/40] fix package name --- README.md | 181 ++- .../launchableinc/openai/edit/EditUsage.java | 32 +- .../openai/embedding/Embedding.java | 28 +- .../openai/embedding/EmbeddingRequest.java | 42 +- .../openai/embedding/EmbeddingResult.java | 38 +- .../launchableinc/openai/engine/Engine.java | 37 +- .../com/launchableinc/openai/file/File.java | 89 +- .../openai/fine_tuning/FineTuningEvent.java | 65 +- .../openai/fine_tuning/FineTuningJob.java | 156 +- .../fine_tuning/FineTuningJobRequest.java | 59 +- .../openai/fine_tuning/Hyperparameters.java | 17 +- .../openai/finetune/FineTuneEvent.java | 39 +- .../openai/finetune/FineTuneRequest.java | 187 +-- .../openai/finetune/FineTuneResult.java | 151 +- .../openai/finetune/HyperParameters.java | 44 +- .../openai/image/CreateImageEditRequest.java | 73 +- .../image/CreateImageVariationRequest.java | 53 +- .../com/launchableinc/openai/image/Image.java | 33 +- .../openai/image/ImageResult.java | 20 +- .../openai/messages/Message.java | 100 +- .../openai/messages/MessageContent.java | 33 +- .../openai/messages/MessageFile.java | 39 +- .../openai/messages/MessageRequest.java | 53 +- .../openai/messages/ModifyMessageRequest.java | 14 +- .../openai/messages/content/Annotation.java | 57 +- .../openai/messages/content/FileCitation.java | 25 +- .../openai/messages/content/FilePath.java | 15 +- .../openai/messages/content/ImageFile.java | 12 +- .../openai/messages/content/Text.java | 18 +- .../com/launchableinc/openai/model/Model.java | 67 +- .../openai/model/Permission.java | 66 +- .../openai/moderation/Moderation.java | 40 +- .../moderation/ModerationCategories.java | 28 +- .../moderation/ModerationCategoryScores.java | 26 +- .../openai/moderation/ModerationRequest.java | 22 +- .../openai/moderation/ModerationResult.java | 29 +- .../runs/CreateThreadAndRunRequest.java | 26 +- .../openai/runs/MessageCreation.java | 8 +- .../openai/runs/RequiredAction.java | 10 +- .../com/launchableinc/openai/runs/Run.java | 70 +- .../openai/runs/RunCreateRequest.java | 25 +- .../launchableinc/openai/runs/RunImage.java | 6 +- .../launchableinc/openai/runs/RunStep.java | 66 +- .../openai/runs/StepDetails.java | 14 +- .../runs/SubmitToolOutputRequestItem.java | 10 +- .../openai/runs/SubmitToolOutputs.java | 8 +- .../openai/runs/SubmitToolOutputsRequest.java | 8 +- .../launchableinc/openai/runs/ToolCall.java | 20 +- .../openai/runs/ToolCallCodeInterpreter.java | 10 +- .../runs/ToolCallCodeInterpreterOutput.java | 14 +- .../openai/runs/ToolCallFunction.java | 14 +- .../launchableinc/openai/threads/Thread.java | 41 +- .../openai/threads/ThreadRequest.java | 26 +- .../openai/utils/TikTokensUtil.java | 570 ++++---- .../com/launchableinc/openai/JsonTest.java | 111 +- .../openai/AuthenticationInterceptor.java | 15 +- .../com/launchableinc/openai/OpenAiApi.java | 6 +- .../client/AuthenticationInterceptor.java | 26 +- .../openai/client/OpenAiApi.java | 568 ++++---- .../OpenAiApiDynamicFunctionExample.java | 145 +- .../main/java/example/OpenAiApiExample.java | 96 +- .../example/OpenAiApiFunctionsExample.java | 184 +-- .../OpenAiApiFunctionsWithStreamExample.java | 138 +- .../main/java/example/TikTokensExample.java | 21 +- gradle.properties | 20 +- .../service/AuthenticationInterceptor.java | 28 +- .../service/ChatCompletionRequestMixIn.java | 10 +- ...etionRequestSerializerAndDeserializer.java | 60 +- ...allArgumentsSerializerAndDeserializer.java | 83 +- .../openai/service/ChatFunctionCallMixIn.java | 8 +- .../openai/service/ChatFunctionMixIn.java | 6 +- .../ChatFunctionParametersSerializer.java | 37 +- .../service/ChatMessageAccumulator.java | 136 +- .../openai/service/FunctionExecutor.java | 190 +-- .../openai/service/OpenAiService.java | 1276 +++++++++-------- .../openai/service/ResponseBodyCallback.java | 158 +- .../com/launchableinc/openai/service/SSE.java | 33 +- .../openai/service/SSEFormatException.java | 7 +- .../openai/service/AssistantFunctionTest.java | 257 ++-- .../openai/service/AssistantTest.java | 240 ++-- .../openai/service/AudioTest.java | 156 +- .../openai/service/ChatCompletionTest.java | 601 ++++---- .../openai/service/CompletionTest.java | 89 +- .../openai/service/EditTest.java | 32 +- .../openai/service/EmbeddingTest.java | 30 +- .../openai/service/FileTest.java | 85 +- .../openai/service/FineTuneTest.java | 141 +- .../openai/service/FineTuningTest.java | 165 +-- .../openai/service/ImageTest.java | 167 +-- .../openai/service/MessageTest.java | 240 ++-- .../openai/service/ModelTest.java | 30 +- .../openai/service/ModerationTest.java | 28 +- .../openai/service/OpenAiServiceTest.java | 107 +- .../service/ResponseBodyCallbackTest.java | 105 +- .../launchableinc/openai/service/RunTest.java | 95 +- .../openai/service/ThreadTest.java | 96 +- 96 files changed, 4593 insertions(+), 4367 deletions(-) diff --git a/README.md b/README.md index 0ca55a82..4a9ee5d8 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,24 @@ ![Maven Central](https://img.shields.io/maven-central/v/com.theokanning.openai-gpt3-java/client?color=blue) -> ⚠️OpenAI has deprecated all Engine-based APIs. See [Deprecated Endpoints](https://github.com/TheoKanning/openai-java#deprecated-endpoints) below for more info. +> ⚠️OpenAI has deprecated all Engine-based APIs. +> See [Deprecated Endpoints](https://github.com/TheoKanning/openai-java#deprecated-endpoints) below +> for more info. # OpenAI-Java + Java libraries for using OpenAI's GPT apis. Supports GPT-3, ChatGPT, and GPT-4. Includes the following artifacts: + - `api` : request/response POJOs for the GPT APIs. - `client` : a basic retrofit client for the GPT endpoints, includes the `api` module -- `service` : A basic service class that creates and calls the client. This is the easiest way to get started. +- `service` : A basic service class that creates and calls the client. This is the easiest way to + get started. as well as an example project using the service. ## Supported APIs + - [Models](https://platform.openai.com/docs/api-reference/models) - [Completions](https://platform.openai.com/docs/api-reference/completions) - [Chat Completions](https://platform.openai.com/docs/api-reference/chat/create) @@ -26,57 +32,78 @@ as well as an example project using the service. - [Assistants](https://platform.openai.com/docs/api-reference/assistants) #### Deprecated by OpenAI + - [Engines](https://platform.openai.com/docs/api-reference/engines) - [Legacy Fine-Tunes](https://platform.openai.com/docs/guides/legacy-fine-tuning) ## Importing ### Gradle + `implementation 'com.theokanning.openai-gpt3-java::'` ### Maven + ```xml - - com.theokanning.openai-gpt3-java - {api|client|service} - version - + + + com.launchableinc.openai-gpt3-java + {api|client|service} + version + ``` ## Usage + ### Data classes only + If you want to make your own client, just import the POJOs from the `api` module. Your client will need to use snake case to work with the OpenAI API. ### Retrofit client -If you're using retrofit, you can import the `client` module and use the [OpenAiApi](client/src/main/java/com/theokanning/openai/OpenAiApi.java). -You'll have to add your auth token as a header (see [AuthenticationInterceptor](client/src/main/java/com/theokanning/openai/AuthenticationInterceptor.java)) + +If you're using retrofit, you can import the `client` module and use +the [OpenAiApi](client/src/main/java/com/theokanning/openai/OpenAiApi.java). +You'll have to add your auth token as a header ( +see [AuthenticationInterceptor](client/src/main/java/com/theokanning/openai/AuthenticationInterceptor.java)) and set your converter factory to use snake case and only include non-null fields. ### OpenAiService -If you're looking for the fastest solution, import the `service` module and use [OpenAiService](service/src/main/java/com/theokanning/openai/service/OpenAiService.java). -> ⚠️The OpenAiService in the client module is deprecated, please switch to the new version in the service module. +If you're looking for the fastest solution, import the `service` module and +use [OpenAiService](service/src/main/java/com/theokanning/openai/service/OpenAiService.java). + +> ⚠️The OpenAiService in the client module is deprecated, please switch to the new version in the +> service module. + ```java OpenAiService service = new OpenAiService("your_token"); CompletionRequest completionRequest = CompletionRequest.builder() - .prompt("Somebody once told me the world is gonna roll me") - .model("babbage-002"") - .echo(true) - .build(); -service.createCompletion(completionRequest).getChoices().forEach(System.out::println); + .prompt("Somebody once told me the world is gonna roll me") + .model("babbage-002"") + .echo(true) + .build(); +service. + +createCompletion(completionRequest). + +getChoices(). + +forEach(System.out::println); ``` ### Customizing OpenAiService -If you need to customize OpenAiService, create your own Retrofit client and pass it in to the constructor. + +If you need to customize OpenAiService, create your own Retrofit client and pass it in to the +constructor. For example, do the following to add request logging (after adding the logging gradle dependency): ```java ObjectMapper mapper = defaultObjectMapper(); OkHttpClient client = defaultClient(token, timeout) - .newBuilder() - .interceptor(HttpLoggingInterceptor()) - .build(); + .newBuilder() + .interceptor(HttpLoggingInterceptor()) + .build(); Retrofit retrofit = defaultRetrofit(client, mapper); OpenAiApi api = retrofit.create(OpenAiApi.class); @@ -84,23 +111,29 @@ OpenAiService service = new OpenAiService(api); ``` ### Adding a Proxy + To use a proxy, modify the OkHttp client as shown below: + ```java ObjectMapper mapper = defaultObjectMapper(); Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)); OkHttpClient client = defaultClient(token, timeout) - .newBuilder() - .proxy(proxy) - .build(); + .newBuilder() + .proxy(proxy) + .build(); Retrofit retrofit = defaultRetrofit(client, mapper); OpenAiApi api = retrofit.create(OpenAiApi.class); OpenAiService service = new OpenAiService(api); ``` ### Functions -You can create your functions and define their executors easily using the ChatFunction class, along with any of your custom classes that will serve to define their available parameters. You can also process the functions with ease, with the help of an executor called FunctionExecutor. + +You can create your functions and define their executors easily using the ChatFunction class, along +with any of your custom classes that will serve to define their available parameters. You can also +process the functions with ease, with the help of an executor called FunctionExecutor. First we declare our function parameters: + ```java public class Weather { @JsonPropertyDescription("City and state, for example: León, Guanajuato") @@ -122,7 +155,9 @@ public static class WeatherResponse { } ``` -Next, we declare the function itself and associate it with an executor, in this example we will fake a response from some API: +Next, we declare the function itself and associate it with an executor, in this example we will fake +a response from some API: + ```java ChatFunction.builder() .name("get_weather") @@ -131,82 +166,124 @@ ChatFunction.builder() .build() ``` -Then, we employ the FunctionExecutor object from the 'service' module to assist with execution and transformation into an object that is ready for the conversation: +Then, we employ the FunctionExecutor object from the 'service' module to assist with execution and +transformation into an object that is ready for the conversation: + ```java List functionList = // list with functions -FunctionExecutor functionExecutor = new FunctionExecutor(functionList); + FunctionExecutor +functionExecutor =new + +FunctionExecutor(functionList); List messages = new ArrayList<>(); -ChatMessage userMessage = new ChatMessage(ChatMessageRole.USER.value(), "Tell me the weather in Barcelona."); -messages.add(userMessage); +ChatMessage userMessage = new ChatMessage(ChatMessageRole.USER.value(), + "Tell me the weather in Barcelona."); +messages. + +add(userMessage); + ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest - .builder() - .model("gpt-3.5-turbo-0613") - .messages(messages) - .functions(functionExecutor.getFunctions()) - .functionCall(new ChatCompletionRequestFunctionCall("auto")) - .maxTokens(256) - .build(); - -ChatMessage responseMessage = service.createChatCompletion(chatCompletionRequest).getChoices().get(0).getMessage(); + .builder() + .model("gpt-3.5-turbo-0613") + .messages(messages) + .functions(functionExecutor.getFunctions()) + .functionCall(new ChatCompletionRequestFunctionCall("auto")) + .maxTokens(256) + .build(); + +ChatMessage responseMessage = service.createChatCompletion(chatCompletionRequest).getChoices() + .get(0).getMessage(); ChatFunctionCall functionCall = responseMessage.getFunctionCall(); // might be null, but in this case it is certainly a call to our 'get_weather' function. -ChatMessage functionResponseMessage = functionExecutor.executeAndConvertToMessageHandlingExceptions(functionCall); -messages.add(response); +ChatMessage functionResponseMessage = functionExecutor.executeAndConvertToMessageHandlingExceptions( + functionCall); +messages. + +add(response); ``` + > **Note:** The `FunctionExecutor` class is part of the 'service' module. -You can also create your own function executor. The return object of `ChatFunctionCall.getArguments()` is a JsonNode for simplicity and should be able to help you with that. +You can also create your own function executor. The return object +of `ChatFunctionCall.getArguments()` is a JsonNode for simplicity and should be able to help you +with that. -For a more in-depth look, refer to a conversational example that employs functions in: [OpenAiApiFunctionsExample.java](example/src/main/java/example/OpenAiApiFunctionsExample.java). -Or for an example using functions and stream: [OpenAiApiFunctionsWithStreamExample.java](example/src/main/java/example/OpenAiApiFunctionsWithStreamExample.java) +For a more in-depth look, refer to a conversational example that employs functions +in: [OpenAiApiFunctionsExample.java](example/src/main/java/example/OpenAiApiFunctionsExample.java). +Or for an example using functions and +stream: [OpenAiApiFunctionsWithStreamExample.java](example/src/main/java/example/OpenAiApiFunctionsWithStreamExample.java) ### Streaming thread shutdown -If you want to shut down your process immediately after streaming responses, call `OpenAiService.shutdownExecutor()`. + +If you want to shut down your process immediately after streaming responses, +call `OpenAiService.shutdownExecutor()`. This is not necessary for non-streaming calls. ## Running the example project -All the [example](example/src/main/java/example/OpenAiApiExample.java) project requires is your OpenAI api token + +All the [example](example/src/main/java/example/OpenAiApiExample.java) project requires is your +OpenAI api token + ```bash export OPENAI_TOKEN="sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ``` + You can try all the capabilities of this project using: + ```bash ./gradlew runExampleOne ``` + And you can also try the new capability of using functions: + ```bash ./gradlew runExampleTwo ``` + Or functions with 'stream' mode enabled: + ```bash ./gradlew runExampleThree ``` ## FAQ + ### Does this support GPT-4? -Yes! GPT-4 uses the ChatCompletion Api, and you can see the latest model options [here](https://platform.openai.com/docs/models/gpt-4). -GPT-4 is currently in a limited beta (as of 4/1/23), so make sure you have access before trying to use it. + +Yes! GPT-4 uses the ChatCompletion Api, and you can see the latest model +options [here](https://platform.openai.com/docs/models/gpt-4). +GPT-4 is currently in a limited beta (as of 4/1/23), so make sure you have access before trying to +use it. ### Does this support functions? + Absolutely! It is very easy to use your own functions without worrying about doing the dirty work. -As mentioned above, you can refer to [OpenAiApiFunctionsExample.java](example/src/main/java/example/OpenAiApiFunctionsExample.java) or -[OpenAiApiFunctionsWithStreamExample.java](example/src/main/java/example/OpenAiApiFunctionsWithStreamExample.java) projects for an example. +As mentioned above, you can refer +to [OpenAiApiFunctionsExample.java](example/src/main/java/example/OpenAiApiFunctionsExample.java) or +[OpenAiApiFunctionsWithStreamExample.java](example/src/main/java/example/OpenAiApiFunctionsWithStreamExample.java) +projects for an example. ### Why am I getting connection timeouts? + Make sure that OpenAI is available in your country. ### Why doesn't OpenAiService support x configuration option? + Many projects use OpenAiService, and in order to support them best I've kept it extremely simple. You can create your own OpenAiApi instance to customize headers, timeouts, base urls etc. -If you want features like retry logic and async calls, you'll have to make an `OpenAiApi` instance and call it directly instead of using `OpenAiService` +If you want features like retry logic and async calls, you'll have to make an `OpenAiApi` instance +and call it directly instead of using `OpenAiService` ## Deprecated Endpoints -OpenAI has deprecated engine-based endpoints in favor of model-based endpoints. -For example, instead of using `v1/engines/{engine_id}/completions`, switch to `v1/completions` and specify the model in the `CompletionRequest`. + +OpenAI has deprecated engine-based endpoints in favor of model-based endpoints. +For example, instead of using `v1/engines/{engine_id}/completions`, switch to `v1/completions` and +specify the model in the `CompletionRequest`. The code includes upgrade instructions for all deprecated endpoints. I won't remove the old endpoints from this library until OpenAI shuts them down. ## License + Published under the MIT License diff --git a/api/src/main/java/com/launchableinc/openai/edit/EditUsage.java b/api/src/main/java/com/launchableinc/openai/edit/EditUsage.java index 7223890f..c2e77365 100644 --- a/api/src/main/java/com/launchableinc/openai/edit/EditUsage.java +++ b/api/src/main/java/com/launchableinc/openai/edit/EditUsage.java @@ -1,30 +1,30 @@ -package com.theokanning.openai.edit; +package com.launchableinc.openai.edit; import lombok.Data; /** * An object containing the API usage for an edit request - * - * Deprecated, use {@link com.theokanning.openai.Usage} instead - * + *

+ * Deprecated, use {@link com.launchableinc.openai.Usage} instead + *

* https://beta.openai.com/docs/api-reference/edits/create */ @Data @Deprecated public class EditUsage { - /** - * The number of prompt tokens consumed. - */ - String promptTokens; + /** + * The number of prompt tokens consumed. + */ + String promptTokens; - /** - * The number of completion tokens consumed. - */ - String completionTokens; + /** + * The number of completion tokens consumed. + */ + String completionTokens; - /** - * The number of total tokens consumed. - */ - String totalTokens; + /** + * The number of total tokens consumed. + */ + String totalTokens; } diff --git a/api/src/main/java/com/launchableinc/openai/embedding/Embedding.java b/api/src/main/java/com/launchableinc/openai/embedding/Embedding.java index 5fc423f5..c0e29914 100644 --- a/api/src/main/java/com/launchableinc/openai/embedding/Embedding.java +++ b/api/src/main/java/com/launchableinc/openai/embedding/Embedding.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.embedding; +package com.launchableinc.openai.embedding; import lombok.Data; @@ -6,24 +6,24 @@ /** * Represents an embedding returned by the embedding api - * + *

* https://beta.openai.com/docs/api-reference/classifications/create */ @Data public class Embedding { - /** - * The type of object returned, should be "embedding" - */ - String object; + /** + * The type of object returned, should be "embedding" + */ + String object; - /** - * The embedding vector - */ - List embedding; + /** + * The embedding vector + */ + List embedding; - /** - * The position of this embedding in the list - */ - Integer index; + /** + * The position of this embedding in the list + */ + Integer index; } diff --git a/api/src/main/java/com/launchableinc/openai/embedding/EmbeddingRequest.java b/api/src/main/java/com/launchableinc/openai/embedding/EmbeddingRequest.java index 33a5d196..3a8629f4 100644 --- a/api/src/main/java/com/launchableinc/openai/embedding/EmbeddingRequest.java +++ b/api/src/main/java/com/launchableinc/openai/embedding/EmbeddingRequest.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.embedding; +package com.launchableinc.openai.embedding; import lombok.*; @@ -6,7 +6,7 @@ /** * Creates an embedding vector representing the input text. - * + *

* https://beta.openai.com/docs/api-reference/embeddings/create */ @Builder @@ -15,25 +15,25 @@ @Data public class EmbeddingRequest { - /** - * The name of the model to use. - * Required if using the new v1/embeddings endpoint. - */ - String model; + /** + * The name of the model to use. Required if using the new v1/embeddings endpoint. + */ + String model; - /** - * Input text to get embeddings for, encoded as a string or array of tokens. - * To get embeddings for multiple inputs in a single request, pass an array of strings or array of token arrays. - * Each input must not exceed 2048 tokens in length. - *

- * Unless you are embedding code, we suggest replacing newlines (\n) in your input with a single space, - * as we have observed inferior results when newlines are present. - */ - @NonNull - List input; + /** + * Input text to get embeddings for, encoded as a string or array of tokens. To get embeddings for + * multiple inputs in a single request, pass an array of strings or array of token arrays. Each + * input must not exceed 2048 tokens in length. + *

+ * Unless you are embedding code, we suggest replacing newlines (\n) in your input with a single + * space, as we have observed inferior results when newlines are present. + */ + @NonNull + List input; - /** - * A unique identifier representing your end-user, which will help OpenAI to monitor and detect abuse. - */ - String user; + /** + * A unique identifier representing your end-user, which will help OpenAI to monitor and detect + * abuse. + */ + String user; } diff --git a/api/src/main/java/com/launchableinc/openai/embedding/EmbeddingResult.java b/api/src/main/java/com/launchableinc/openai/embedding/EmbeddingResult.java index 41f9208e..413c8d60 100644 --- a/api/src/main/java/com/launchableinc/openai/embedding/EmbeddingResult.java +++ b/api/src/main/java/com/launchableinc/openai/embedding/EmbeddingResult.java @@ -1,35 +1,35 @@ -package com.theokanning.openai.embedding; +package com.launchableinc.openai.embedding; -import com.theokanning.openai.Usage; +import com.launchableinc.openai.Usage; import lombok.Data; import java.util.List; /** * An object containing a response from the answer api - * + *

* https://beta.openai.com/docs/api-reference/embeddings/create */ @Data public class EmbeddingResult { - /** - * The GPTmodel used for generating embeddings - */ - String model; + /** + * The GPTmodel used for generating embeddings + */ + String model; - /** - * The type of object returned, should be "list" - */ - String object; + /** + * The type of object returned, should be "list" + */ + String object; - /** - * A list of the calculated embeddings - */ - List data; + /** + * A list of the calculated embeddings + */ + List data; - /** - * The API usage for this request - */ - Usage usage; + /** + * The API usage for this request + */ + Usage usage; } diff --git a/api/src/main/java/com/launchableinc/openai/engine/Engine.java b/api/src/main/java/com/launchableinc/openai/engine/Engine.java index 1aa542ae..7f0ea2a3 100644 --- a/api/src/main/java/com/launchableinc/openai/engine/Engine.java +++ b/api/src/main/java/com/launchableinc/openai/engine/Engine.java @@ -1,32 +1,33 @@ -package com.theokanning.openai.engine; +package com.launchableinc.openai.engine; import lombok.Data; /** * GPT-3 engine details - * + *

* https://beta.openai.com/docs/api-reference/retrieve-engine */ @Deprecated @Data public class Engine { - /** - * An identifier for this engine, used to specify an engine for completions or searching. - */ - public String id; - /** - * The type of object returned, should be "engine" - */ - public String object; + /** + * An identifier for this engine, used to specify an engine for completions or searching. + */ + public String id; - /** - * The owner of the GPT-3 engine, typically "openai" - */ - public String owner; + /** + * The type of object returned, should be "engine" + */ + public String object; - /** - * Whether the engine is ready to process requests or not - */ - public boolean ready; + /** + * The owner of the GPT-3 engine, typically "openai" + */ + public String owner; + + /** + * Whether the engine is ready to process requests or not + */ + public boolean ready; } diff --git a/api/src/main/java/com/launchableinc/openai/file/File.java b/api/src/main/java/com/launchableinc/openai/file/File.java index 07708f8e..45e0fbe1 100644 --- a/api/src/main/java/com/launchableinc/openai/file/File.java +++ b/api/src/main/java/com/launchableinc/openai/file/File.java @@ -1,56 +1,57 @@ -package com.theokanning.openai.file; +package com.launchableinc.openai.file; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; /** * A file uploaded to OpenAi - * + *

* https://beta.openai.com/docs/api-reference/files */ @Data public class File { - /** - * The unique id of this file. - */ - String id; - - /** - * The type of object returned, should be "file". - */ - String object; - - /** - * File size in bytes. - */ - Long bytes; - - /** - * The creation time in epoch seconds. - */ - @JsonProperty("created_at") - Long createdAt; - - /** - * The name of the file. - */ - String filename; - - /** - * Description of the file's purpose. - */ - String purpose; - - /** - * The current status of the file, which can be either uploaded, processed, pending, error, deleting or deleted. - */ - String status; - - /** - * Additional details about the status of the file. - * If the file is in the error state, this will include a message describing the error. - */ - @JsonProperty("status_details") - String statusDetails; + /** + * The unique id of this file. + */ + String id; + + /** + * The type of object returned, should be "file". + */ + String object; + + /** + * File size in bytes. + */ + Long bytes; + + /** + * The creation time in epoch seconds. + */ + @JsonProperty("created_at") + Long createdAt; + + /** + * The name of the file. + */ + String filename; + + /** + * Description of the file's purpose. + */ + String purpose; + + /** + * The current status of the file, which can be either uploaded, processed, pending, error, + * deleting or deleted. + */ + String status; + + /** + * Additional details about the status of the file. If the file is in the error state, this will + * include a message describing the error. + */ + @JsonProperty("status_details") + String statusDetails; } diff --git a/api/src/main/java/com/launchableinc/openai/fine_tuning/FineTuningEvent.java b/api/src/main/java/com/launchableinc/openai/fine_tuning/FineTuningEvent.java index c653c048..1823a4e5 100644 --- a/api/src/main/java/com/launchableinc/openai/fine_tuning/FineTuningEvent.java +++ b/api/src/main/java/com/launchableinc/openai/fine_tuning/FineTuningEvent.java @@ -1,43 +1,44 @@ -package com.theokanning.openai.fine_tuning; +package com.launchableinc.openai.fine_tuning; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; /** * An object representing an event in the lifecycle of a fine-tuning job - * + *

* https://platform.openai.com/docs/api-reference/fine-tuning/list-events */ @Data public class FineTuningEvent { - /** - * The type of object returned, should be "fine-tuneing.job.event". - */ - String object; - - /** - * The ID of the fine-tuning event. - */ - String id; - - /** - * The creation time in epoch seconds. - */ - @JsonProperty("created_at") - Long createdAt; - - /** - * The log level of this message. - */ - String level; - - /** - * The event message. - */ - String message; - - /** - * The type of event, i.e. "message" - */ - String type; + + /** + * The type of object returned, should be "fine-tuneing.job.event". + */ + String object; + + /** + * The ID of the fine-tuning event. + */ + String id; + + /** + * The creation time in epoch seconds. + */ + @JsonProperty("created_at") + Long createdAt; + + /** + * The log level of this message. + */ + String level; + + /** + * The event message. + */ + String message; + + /** + * The type of event, i.e. "message" + */ + String type; } diff --git a/api/src/main/java/com/launchableinc/openai/fine_tuning/FineTuningJob.java b/api/src/main/java/com/launchableinc/openai/fine_tuning/FineTuningJob.java index 685d751e..dcf11429 100644 --- a/api/src/main/java/com/launchableinc/openai/fine_tuning/FineTuningJob.java +++ b/api/src/main/java/com/launchableinc/openai/fine_tuning/FineTuningJob.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.fine_tuning; +package com.launchableinc.openai.fine_tuning; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; @@ -6,85 +6,83 @@ import java.util.List; /** - * Fine-tuning job - * https://platform.openai.com/docs/api-reference/fine-tuning/object + * Fine-tuning job https://platform.openai.com/docs/api-reference/fine-tuning/object */ @Data public class FineTuningJob { - /** - * The object identifier, which can be referenced in the API endpoints. - */ - String id; - - /** - * The object type, which is always "fine_tuning.job". - */ - String object; - - /** - * The unix timestamp for when the fine-tuning job was created. - */ - @JsonProperty("created_at") - Long createdAt; - - /** - * The unix timestamp for when the fine-tuning job was finished. - */ - @JsonProperty("finished_at") - Long finishedAt; - - /** - * The base model that is being fine-tuned. - */ - String model; - - /** - * The name of the fine-tuned model that is being created. - * Can be null if no fine-tuned model is created yet. - */ - @JsonProperty("fine_tuned_model") - String fineTunedModel; - - /** - * The organization that owns the fine-tuning job. - */ - @JsonProperty("organization_id") - String organizationId; - - /** - * The current status of the fine-tuning job. - * Can be either created, pending, running, succeeded, failed, or cancelled. - */ - String status; - - /** - * The hyperparameters used for the fine-tuning job. - * See the fine-tuning guide for more details. - */ - Hyperparameters hyperparameters; - - /** - * The file ID used for training. - */ - @JsonProperty("training_file") - String trainingFile; - - /** - * The file ID used for validation. - * Can be null if validation is not used. - */ - @JsonProperty("validation_file") - String validationFile; - - /** - * The compiled results files for the fine-tuning job. - */ - @JsonProperty("result_files") - List resultFiles; - - /** - * The total number of billable tokens processed by this fine-tuning job. - */ - @JsonProperty("trained_tokens") - Integer trainedTokens; + + /** + * The object identifier, which can be referenced in the API endpoints. + */ + String id; + + /** + * The object type, which is always "fine_tuning.job". + */ + String object; + + /** + * The unix timestamp for when the fine-tuning job was created. + */ + @JsonProperty("created_at") + Long createdAt; + + /** + * The unix timestamp for when the fine-tuning job was finished. + */ + @JsonProperty("finished_at") + Long finishedAt; + + /** + * The base model that is being fine-tuned. + */ + String model; + + /** + * The name of the fine-tuned model that is being created. Can be null if no fine-tuned model is + * created yet. + */ + @JsonProperty("fine_tuned_model") + String fineTunedModel; + + /** + * The organization that owns the fine-tuning job. + */ + @JsonProperty("organization_id") + String organizationId; + + /** + * The current status of the fine-tuning job. Can be either created, pending, running, succeeded, + * failed, or cancelled. + */ + String status; + + /** + * The hyperparameters used for the fine-tuning job. See the fine-tuning guide for more details. + */ + Hyperparameters hyperparameters; + + /** + * The file ID used for training. + */ + @JsonProperty("training_file") + String trainingFile; + + /** + * The file ID used for validation. Can be null if validation is not used. + */ + @JsonProperty("validation_file") + String validationFile; + + /** + * The compiled results files for the fine-tuning job. + */ + @JsonProperty("result_files") + List resultFiles; + + /** + * The total number of billable tokens processed by this fine-tuning job. + */ + @JsonProperty("trained_tokens") + Integer trainedTokens; } \ No newline at end of file diff --git a/api/src/main/java/com/launchableinc/openai/fine_tuning/FineTuningJobRequest.java b/api/src/main/java/com/launchableinc/openai/fine_tuning/FineTuningJobRequest.java index 44a501c3..c654da16 100644 --- a/api/src/main/java/com/launchableinc/openai/fine_tuning/FineTuningJobRequest.java +++ b/api/src/main/java/com/launchableinc/openai/fine_tuning/FineTuningJobRequest.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.fine_tuning; +package com.launchableinc.openai.fine_tuning; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.*; @@ -14,33 +14,32 @@ @Data public class FineTuningJobRequest { - /** - * The ID of an uploaded file that contains training data. - */ - @NonNull - @JsonProperty("training_file") - String trainingFile; - - /** - * The ID of an uploaded file that contains validation data. - * Optional. - */ - @JsonProperty("validation_file") - String validationFile; - - /** - * The name of the model to fine-tune. - */ - @NonNull - String model; - - /** - * The hyperparameters used for the fine-tuning job. - */ - Hyperparameters hyperparameters; - - /** - * A string of up to 40 characters that will be added to your fine-tuned model name. - */ - String suffix; + /** + * The ID of an uploaded file that contains training data. + */ + @NonNull + @JsonProperty("training_file") + String trainingFile; + + /** + * The ID of an uploaded file that contains validation data. Optional. + */ + @JsonProperty("validation_file") + String validationFile; + + /** + * The name of the model to fine-tune. + */ + @NonNull + String model; + + /** + * The hyperparameters used for the fine-tuning job. + */ + Hyperparameters hyperparameters; + + /** + * A string of up to 40 characters that will be added to your fine-tuned model name. + */ + String suffix; } diff --git a/api/src/main/java/com/launchableinc/openai/fine_tuning/Hyperparameters.java b/api/src/main/java/com/launchableinc/openai/fine_tuning/Hyperparameters.java index 3d59913d..177abfe8 100644 --- a/api/src/main/java/com/launchableinc/openai/fine_tuning/Hyperparameters.java +++ b/api/src/main/java/com/launchableinc/openai/fine_tuning/Hyperparameters.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.fine_tuning; +package com.launchableinc.openai.fine_tuning; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; @@ -17,12 +17,11 @@ @Data public class Hyperparameters { - /** - * The number of epochs to train the model for. - * An epoch refers to one full cycle through the training dataset. - * "Auto" decides the optimal number of epochs based on the size of the dataset. - * If setting the number manually, we support any number between 1 and 50 epochs. - */ - @JsonProperty("n_epochs") - Integer nEpochs; + /** + * The number of epochs to train the model for. An epoch refers to one full cycle through the + * training dataset. "Auto" decides the optimal number of epochs based on the size of the dataset. + * If setting the number manually, we support any number between 1 and 50 epochs. + */ + @JsonProperty("n_epochs") + Integer nEpochs; } diff --git a/api/src/main/java/com/launchableinc/openai/finetune/FineTuneEvent.java b/api/src/main/java/com/launchableinc/openai/finetune/FineTuneEvent.java index 7b8f76c3..25d0fa9c 100644 --- a/api/src/main/java/com/launchableinc/openai/finetune/FineTuneEvent.java +++ b/api/src/main/java/com/launchableinc/openai/finetune/FineTuneEvent.java @@ -1,34 +1,35 @@ -package com.theokanning.openai.finetune; +package com.launchableinc.openai.finetune; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; /** * An object representing an event in the lifecycle of a fine-tuning job - * + *

* https://beta.openai.com/docs/api-reference/fine-tunes */ @Deprecated @Data public class FineTuneEvent { - /** - * The type of object returned, should be "fine-tune-event". - */ - String object; - /** - * The creation time in epoch seconds. - */ - @JsonProperty("created_at") - Long createdAt; + /** + * The type of object returned, should be "fine-tune-event". + */ + String object; - /** - * The log level of this message. - */ - String level; + /** + * The creation time in epoch seconds. + */ + @JsonProperty("created_at") + Long createdAt; - /** - * The event message. - */ - String message; + /** + * The log level of this message. + */ + String level; + + /** + * The event message. + */ + String message; } diff --git a/api/src/main/java/com/launchableinc/openai/finetune/FineTuneRequest.java b/api/src/main/java/com/launchableinc/openai/finetune/FineTuneRequest.java index 2d145aa0..43b60e95 100644 --- a/api/src/main/java/com/launchableinc/openai/finetune/FineTuneRequest.java +++ b/api/src/main/java/com/launchableinc/openai/finetune/FineTuneRequest.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.finetune; +package com.launchableinc.openai.finetune; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.*; @@ -6,9 +6,8 @@ import java.util.List; /** - * A request for OpenAi to create a fine-tuned model - * All fields except trainingFile are nullable. - * + * A request for OpenAi to create a fine-tuned model All fields except trainingFile are nullable. + *

* https://beta.openai.com/docs/api-reference/fine-tunes/create */ @Deprecated @@ -18,104 +17,106 @@ @Data public class FineTuneRequest { - /** - * The ID of an uploaded file that contains training data. - */ - @NonNull - @JsonProperty("training_file") - String trainingFile; + /** + * The ID of an uploaded file that contains training data. + */ + @NonNull + @JsonProperty("training_file") + String trainingFile; - /** - * The ID of an uploaded file that contains validation data. - */ - @JsonProperty("validation_file") - String validationFile; + /** + * The ID of an uploaded file that contains validation data. + */ + @JsonProperty("validation_file") + String validationFile; - /** - * The name of the base model to fine-tune. You can select one of "ada", "babbage", "curie", or "davinci". - * To learn more about these models, see the Engines documentation. - */ - String model; + /** + * The name of the base model to fine-tune. You can select one of "ada", "babbage", "curie", or + * "davinci". To learn more about these models, see the Engines documentation. + */ + String model; - /** - * The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset. - */ - @JsonProperty("n_epochs") - Integer nEpochs; + /** + * The number of epochs to train the model for. An epoch refers to one full cycle through the + * training dataset. + */ + @JsonProperty("n_epochs") + Integer nEpochs; - /** - * The batch size to use for training. - * The batch size is the number of training examples used to train a single forward and backward pass. - * - * By default, the batch size will be dynamically configured to be ~0.2% of the number of examples in the training - * set, capped at 256 - in general, we've found that larger batch sizes tend to work better for larger datasets. - */ - @JsonProperty("batch_size") - Integer batchSize; + /** + * The batch size to use for training. The batch size is the number of training examples used to + * train a single forward and backward pass. + *

+ * By default, the batch size will be dynamically configured to be ~0.2% of the number of examples + * in the training set, capped at 256 - in general, we've found that larger batch sizes tend to + * work better for larger datasets. + */ + @JsonProperty("batch_size") + Integer batchSize; - /** - * The learning rate multiplier to use for training. - * The fine-tuning learning rate is the original learning rate used for pretraining multiplied by this value. - * - * By default, the learning rate multiplier is the 0.05, 0.1, or 0.2 depending on final batch_size - * (larger learning rates tend to perform better with larger batch sizes). - * We recommend experimenting with values in the range 0.02 to 0.2 to see what produces the best results. - */ - @JsonProperty("learning_rate_multiplier") - Double learningRateMultiplier; + /** + * The learning rate multiplier to use for training. The fine-tuning learning rate is the original + * learning rate used for pretraining multiplied by this value. + *

+ * By default, the learning rate multiplier is the 0.05, 0.1, or 0.2 depending on final batch_size + * (larger learning rates tend to perform better with larger batch sizes). We recommend + * experimenting with values in the range 0.02 to 0.2 to see what produces the best results. + */ + @JsonProperty("learning_rate_multiplier") + Double learningRateMultiplier; - /** - * The weight to use for loss on the prompt tokens. - * This controls how much the model tries to learn to generate the prompt - * (as compared to the completion which always has a weight of 1.0), - * and can add a stabilizing effect to training when completions are short. - * - * If prompts are extremely long (relative to completions), it may make sense to reduce this weight so as to - * avoid over-prioritizing learning the prompt. - */ - @JsonProperty("prompt_loss_weight") - Double promptLossWeight; + /** + * The weight to use for loss on the prompt tokens. This controls how much the model tries to + * learn to generate the prompt (as compared to the completion which always has a weight of 1.0), + * and can add a stabilizing effect to training when completions are short. + *

+ * If prompts are extremely long (relative to completions), it may make sense to reduce this + * weight so as to avoid over-prioritizing learning the prompt. + */ + @JsonProperty("prompt_loss_weight") + Double promptLossWeight; - /** - * If set, we calculate classification-specific metrics such as accuracy and F-1 score using the validation set - * at the end of every epoch. These metrics can be viewed in the results file. - * - * In order to compute classification metrics, you must provide a validation_file. - * Additionally, you must specify {@link FineTuneRequest#classificationNClasses} for multiclass - * classification or {@link FineTuneRequest#classificationPositiveClass} for binary classification. - */ - @JsonProperty("compute_classification_metrics") - Boolean computeClassificationMetrics; + /** + * If set, we calculate classification-specific metrics such as accuracy and F-1 score using the + * validation set at the end of every epoch. These metrics can be viewed in the results file. + *

+ * In order to compute classification metrics, you must provide a validation_file. Additionally, + * you must specify {@link FineTuneRequest#classificationNClasses} for multiclass classification + * or {@link FineTuneRequest#classificationPositiveClass} for binary classification. + */ + @JsonProperty("compute_classification_metrics") + Boolean computeClassificationMetrics; - /** - * The number of classes in a classification task. - * - * This parameter is required for multiclass classification. - */ - @JsonProperty("classification_n_classes") - Integer classificationNClasses; + /** + * The number of classes in a classification task. + *

+ * This parameter is required for multiclass classification. + */ + @JsonProperty("classification_n_classes") + Integer classificationNClasses; - /** - * The positive class in binary classification. - * - * This parameter is needed to generate precision, recall, and F1 metrics when doing binary classification. - */ - @JsonProperty("classification_positive_class") - String classificationPositiveClass; + /** + * The positive class in binary classification. + *

+ * This parameter is needed to generate precision, recall, and F1 metrics when doing binary + * classification. + */ + @JsonProperty("classification_positive_class") + String classificationPositiveClass; - /** - * If this is provided, we calculate F-beta scores at the specified beta values. - * The F-beta score is a generalization of F-1 score. This is only used for binary classification. - * - * With a beta of 1 (i.e. the F-1 score), precision and recall are given the same weight. - * A larger beta score puts more weight on recall and less on precision. - * A smaller beta score puts more weight on precision and less on recall. - */ - @JsonProperty("classification_betas") - List classificationBetas; + /** + * If this is provided, we calculate F-beta scores at the specified beta values. The F-beta score + * is a generalization of F-1 score. This is only used for binary classification. + *

+ * With a beta of 1 (i.e. the F-1 score), precision and recall are given the same weight. A larger + * beta score puts more weight on recall and less on precision. A smaller beta score puts more + * weight on precision and less on recall. + */ + @JsonProperty("classification_betas") + List classificationBetas; - /** - * A string of up to 40 characters that will be added to your fine-tuned model name. - */ - String suffix; + /** + * A string of up to 40 characters that will be added to your fine-tuned model name. + */ + String suffix; } diff --git a/api/src/main/java/com/launchableinc/openai/finetune/FineTuneResult.java b/api/src/main/java/com/launchableinc/openai/finetune/FineTuneResult.java index 6cbcce41..94f205cf 100644 --- a/api/src/main/java/com/launchableinc/openai/finetune/FineTuneResult.java +++ b/api/src/main/java/com/launchableinc/openai/finetune/FineTuneResult.java @@ -1,89 +1,90 @@ -package com.theokanning.openai.finetune; +package com.launchableinc.openai.finetune; import com.fasterxml.jackson.annotation.JsonProperty; -import com.theokanning.openai.file.File; +import com.launchableinc.openai.file.File; import lombok.Data; import java.util.List; /** * An object describing a fine-tuned model. Returned by multiple fine-tune requests. - * + *

* https://beta.openai.com/docs/api-reference/fine-tunes */ @Deprecated @Data public class FineTuneResult { - /** - * The ID of the fine-tuning job. - */ - String id; - - /** - * The type of object returned, should be "fine-tune". - */ - String object; - - /** - * The name of the base model. - */ - String model; - - /** - * The creation time in epoch seconds. - */ - @JsonProperty("created_at") - Long createdAt; - - /** - * List of events in this job's lifecycle. Null when getting a list of fine-tune jobs. - */ - List events; - - /** - * The ID of the fine-tuned model, null if tuning job is not finished. - * This is the id used to call the model. - */ - @JsonProperty("fine_tuned_model") - String fineTunedModel; - - /** - * The specified hyper-parameters for the tuning job. - */ - HyperParameters hyperparams; - - /** - * The ID of the organization this model belongs to. - */ - @JsonProperty("organization_id") - String organizationId; - - /** - * Result files for this fine-tune job. - */ - @JsonProperty("result_files") - List resultFiles; - - /** - * The status os the fine-tune job. "pending", "succeeded", or "cancelled" - */ - String status; - - /** - * Training files for this fine-tune job. - */ - @JsonProperty("training_files") - List trainingFiles; - - /** - * The last update time in epoch seconds. - */ - @JsonProperty("updated_at") - Long updatedAt; - - /** - * Validation files for this fine-tune job. - */ - @JsonProperty("validation_files") - List validationFiles; + + /** + * The ID of the fine-tuning job. + */ + String id; + + /** + * The type of object returned, should be "fine-tune". + */ + String object; + + /** + * The name of the base model. + */ + String model; + + /** + * The creation time in epoch seconds. + */ + @JsonProperty("created_at") + Long createdAt; + + /** + * List of events in this job's lifecycle. Null when getting a list of fine-tune jobs. + */ + List events; + + /** + * The ID of the fine-tuned model, null if tuning job is not finished. This is the id used to call + * the model. + */ + @JsonProperty("fine_tuned_model") + String fineTunedModel; + + /** + * The specified hyper-parameters for the tuning job. + */ + HyperParameters hyperparams; + + /** + * The ID of the organization this model belongs to. + */ + @JsonProperty("organization_id") + String organizationId; + + /** + * Result files for this fine-tune job. + */ + @JsonProperty("result_files") + List resultFiles; + + /** + * The status os the fine-tune job. "pending", "succeeded", or "cancelled" + */ + String status; + + /** + * Training files for this fine-tune job. + */ + @JsonProperty("training_files") + List trainingFiles; + + /** + * The last update time in epoch seconds. + */ + @JsonProperty("updated_at") + Long updatedAt; + + /** + * Validation files for this fine-tune job. + */ + @JsonProperty("validation_files") + List validationFiles; } diff --git a/api/src/main/java/com/launchableinc/openai/finetune/HyperParameters.java b/api/src/main/java/com/launchableinc/openai/finetune/HyperParameters.java index d1d383ed..b476d8ee 100644 --- a/api/src/main/java/com/launchableinc/openai/finetune/HyperParameters.java +++ b/api/src/main/java/com/launchableinc/openai/finetune/HyperParameters.java @@ -1,38 +1,38 @@ -package com.theokanning.openai.finetune; +package com.launchableinc.openai.finetune; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; /** * Fine-tuning job hyperparameters - * + *

* https://beta.openai.com/docs/api-reference/fine-tunes */ @Deprecated @Data public class HyperParameters { - /** - * The batch size to use for training. - */ - @JsonProperty("batch_size") - Integer batchSize; + /** + * The batch size to use for training. + */ + @JsonProperty("batch_size") + Integer batchSize; - /** - * The learning rate multiplier to use for training. - */ - @JsonProperty("learning_rate_multiplier") - Double learningRateMultiplier; + /** + * The learning rate multiplier to use for training. + */ + @JsonProperty("learning_rate_multiplier") + Double learningRateMultiplier; - /** - * The number of epochs to train the model for. - */ - @JsonProperty("n_epochs") - Integer nEpochs; + /** + * The number of epochs to train the model for. + */ + @JsonProperty("n_epochs") + Integer nEpochs; - /** - * The weight to use for loss on the prompt tokens. - */ - @JsonProperty("prompt_loss_weight") - Double promptLossWeight; + /** + * The weight to use for loss on the prompt tokens. + */ + @JsonProperty("prompt_loss_weight") + Double promptLossWeight; } diff --git a/api/src/main/java/com/launchableinc/openai/image/CreateImageEditRequest.java b/api/src/main/java/com/launchableinc/openai/image/CreateImageEditRequest.java index 7d37f689..a800ac9e 100644 --- a/api/src/main/java/com/launchableinc/openai/image/CreateImageEditRequest.java +++ b/api/src/main/java/com/launchableinc/openai/image/CreateImageEditRequest.java @@ -1,12 +1,11 @@ -package com.theokanning.openai.image; +package com.launchableinc.openai.image; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.*; /** - * A request for OpenAi to edit an image based on a prompt - * All fields except prompt are optional - * + * A request for OpenAi to edit an image based on a prompt All fields except prompt are optional + *

* https://beta.openai.com/docs/api-reference/images/create-edit */ @Builder @@ -15,35 +14,39 @@ @Data public class CreateImageEditRequest { - /** - * A text description of the desired image(s). The maximum length in 1000 characters. - */ - @NonNull - String prompt; - - /** - * The model to use for image generation. Only dall-e-2 is supported at this time. Defaults to dall-e-2. - */ - String model; - - /** - * The number of images to generate. Must be between 1 and 10. Defaults to 1. - */ - Integer n; - - /** - * The size of the generated images. Must be one of "256x256", "512x512", or "1024x1024". Defaults to "1024x1024". - */ - String size; - - /** - * The format in which the generated images are returned. Must be one of url or b64_json. Defaults to url. - */ - @JsonProperty("response_format") - String responseFormat; - - /** - * A unique identifier representing your end-user, which will help OpenAI to monitor and detect abuse. - */ - String user; + /** + * A text description of the desired image(s). The maximum length in 1000 characters. + */ + @NonNull + String prompt; + + /** + * The model to use for image generation. Only dall-e-2 is supported at this time. Defaults to + * dall-e-2. + */ + String model; + + /** + * The number of images to generate. Must be between 1 and 10. Defaults to 1. + */ + Integer n; + + /** + * The size of the generated images. Must be one of "256x256", "512x512", or "1024x1024". Defaults + * to "1024x1024". + */ + String size; + + /** + * The format in which the generated images are returned. Must be one of url or b64_json. Defaults + * to url. + */ + @JsonProperty("response_format") + String responseFormat; + + /** + * A unique identifier representing your end-user, which will help OpenAI to monitor and detect + * abuse. + */ + String user; } diff --git a/api/src/main/java/com/launchableinc/openai/image/CreateImageVariationRequest.java b/api/src/main/java/com/launchableinc/openai/image/CreateImageVariationRequest.java index f16f613d..c2888ceb 100644 --- a/api/src/main/java/com/launchableinc/openai/image/CreateImageVariationRequest.java +++ b/api/src/main/java/com/launchableinc/openai/image/CreateImageVariationRequest.java @@ -1,12 +1,11 @@ -package com.theokanning.openai.image; +package com.launchableinc.openai.image; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.*; /** - * A request for OpenAi to create a variation of an image - * All fields are optional - * + * A request for OpenAi to create a variation of an image All fields are optional + *

* https://beta.openai.com/docs/api-reference/images/create-variation */ @Builder @@ -15,29 +14,33 @@ @Data public class CreateImageVariationRequest { - /** - * The number of images to generate. Must be between 1 and 10. Defaults to 1. - */ - Integer n; + /** + * The number of images to generate. Must be between 1 and 10. Defaults to 1. + */ + Integer n; - /** - * The model to use for image generation. Only dall-e-2 is supported at this time. Defaults to dall-e-2. - */ - String model; + /** + * The model to use for image generation. Only dall-e-2 is supported at this time. Defaults to + * dall-e-2. + */ + String model; - /** - * The size of the generated images. Must be one of "256x256", "512x512", or "1024x1024". Defaults to "1024x1024". - */ - String size; + /** + * The size of the generated images. Must be one of "256x256", "512x512", or "1024x1024". Defaults + * to "1024x1024". + */ + String size; - /** - * The format in which the generated images are returned. Must be one of url or b64_json. Defaults to url. - */ - @JsonProperty("response_format") - String responseFormat; + /** + * The format in which the generated images are returned. Must be one of url or b64_json. Defaults + * to url. + */ + @JsonProperty("response_format") + String responseFormat; - /** - * A unique identifier representing your end-user, which will help OpenAI to monitor and detect abuse. - */ - String user; + /** + * A unique identifier representing your end-user, which will help OpenAI to monitor and detect + * abuse. + */ + String user; } diff --git a/api/src/main/java/com/launchableinc/openai/image/Image.java b/api/src/main/java/com/launchableinc/openai/image/Image.java index 6b8391ed..ad27d0a0 100644 --- a/api/src/main/java/com/launchableinc/openai/image/Image.java +++ b/api/src/main/java/com/launchableinc/openai/image/Image.java @@ -1,30 +1,31 @@ -package com.theokanning.openai.image; +package com.launchableinc.openai.image; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; /** * An object containing either a URL or a base 64 encoded image. - * + *

* https://beta.openai.com/docs/api-reference/images */ @Data public class Image { - /** - * The URL where the image can be accessed. - */ - String url; + /** + * The URL where the image can be accessed. + */ + String url; - /** - * Base64 encoded image string. - */ - @JsonProperty("b64_json") - String b64Json; - /** - * The prompt that was used to generate the image, if there was any revision to the prompt. - */ - @JsonProperty("revised_prompt") - String revisedPrompt; + /** + * Base64 encoded image string. + */ + @JsonProperty("b64_json") + String b64Json; + + /** + * The prompt that was used to generate the image, if there was any revision to the prompt. + */ + @JsonProperty("revised_prompt") + String revisedPrompt; } diff --git a/api/src/main/java/com/launchableinc/openai/image/ImageResult.java b/api/src/main/java/com/launchableinc/openai/image/ImageResult.java index 9576dbfd..6bc3e2ad 100644 --- a/api/src/main/java/com/launchableinc/openai/image/ImageResult.java +++ b/api/src/main/java/com/launchableinc/openai/image/ImageResult.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.image; +package com.launchableinc.openai.image; import lombok.Data; @@ -6,19 +6,19 @@ /** * An object with a list of image results. - * + *

* https://beta.openai.com/docs/api-reference/images */ @Data public class ImageResult { - /** - * The creation time in epoch seconds. - */ - Long created; + /** + * The creation time in epoch seconds. + */ + Long created; - /** - * List of image results. - */ - List data; + /** + * List of image results. + */ + List data; } diff --git a/api/src/main/java/com/launchableinc/openai/messages/Message.java b/api/src/main/java/com/launchableinc/openai/messages/Message.java index 44144780..0589ea22 100644 --- a/api/src/main/java/com/launchableinc/openai/messages/Message.java +++ b/api/src/main/java/com/launchableinc/openai/messages/Message.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.messages; +package com.launchableinc.openai.messages; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; @@ -20,62 +20,62 @@ @AllArgsConstructor @Data public class Message { - /** - * The identifier, which can be referenced in API endpoints. - */ - String id; - /** - * The object type, which is always thread.message. - */ - String object; + /** + * The identifier, which can be referenced in API endpoints. + */ + String id; - /** - * The Unix timestamp (in seconds) for when the message was created. - */ - @JsonProperty("created_at") - int createdAt; + /** + * The object type, which is always thread.message. + */ + String object; - /** - * The thread ID that this message belongs to. - */ - @JsonProperty("thread_id") - String threadId; + /** + * The Unix timestamp (in seconds) for when the message was created. + */ + @JsonProperty("created_at") + int createdAt; - /** - * The entity that produced the message. One of user or assistant. - */ - String role; + /** + * The thread ID that this message belongs to. + */ + @JsonProperty("thread_id") + String threadId; - /** - * The content of the message in an array of text and/or images. - */ - List content; + /** + * The entity that produced the message. One of user or assistant. + */ + String role; - /** - * If applicable, the ID of the assistant that authored this message. - */ - @JsonProperty("assistant_id") - String assistantId; + /** + * The content of the message in an array of text and/or images. + */ + List content; - /** - * If applicable, the ID of the run associated with the authoring of this message. - */ - @JsonProperty("run_id") - String runId; + /** + * If applicable, the ID of the assistant that authored this message. + */ + @JsonProperty("assistant_id") + String assistantId; - /** - * 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. - */ - @JsonProperty("file_ids") - List fileIds; + /** + * If applicable, the ID of the run associated with the authoring of this message. + */ + @JsonProperty("run_id") + String runId; - /** - * 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. - */ - Map metadata; + /** + * 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. + */ + @JsonProperty("file_ids") + List fileIds; + + /** + * 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. + */ + Map metadata; } \ No newline at end of file diff --git a/api/src/main/java/com/launchableinc/openai/messages/MessageContent.java b/api/src/main/java/com/launchableinc/openai/messages/MessageContent.java index a9ff489e..a8e638a7 100644 --- a/api/src/main/java/com/launchableinc/openai/messages/MessageContent.java +++ b/api/src/main/java/com/launchableinc/openai/messages/MessageContent.java @@ -1,8 +1,8 @@ -package com.theokanning.openai.messages; +package com.launchableinc.openai.messages; import com.fasterxml.jackson.annotation.JsonProperty; -import com.theokanning.openai.messages.content.ImageFile; -import com.theokanning.openai.messages.content.Text; +import com.launchableinc.openai.messages.content.ImageFile; +import com.launchableinc.openai.messages.content.Text; import lombok.Data; @@ -13,19 +13,20 @@ */ @Data public class MessageContent { - /** - * The content type, either "text" or "image_file" - */ - String type; - /** - * Text content of the message. Only present if type == text - */ - Text text; + /** + * The content type, either "text" or "image_file" + */ + String type; - /** - * The image content of a message. Only present if type == image_file - */ - @JsonProperty("image_file") - ImageFile imageFile; + /** + * Text content of the message. Only present if type == text + */ + Text text; + + /** + * The image content of a message. Only present if type == image_file + */ + @JsonProperty("image_file") + ImageFile imageFile; } diff --git a/api/src/main/java/com/launchableinc/openai/messages/MessageFile.java b/api/src/main/java/com/launchableinc/openai/messages/MessageFile.java index 7a0dd3bd..610e38de 100644 --- a/api/src/main/java/com/launchableinc/openai/messages/MessageFile.java +++ b/api/src/main/java/com/launchableinc/openai/messages/MessageFile.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.messages; +package com.launchableinc.openai.messages; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; @@ -14,25 +14,26 @@ @AllArgsConstructor @Data public class MessageFile { - /** - * The identifier, which can be referenced in API endpoints. - */ - String id; - /** - * The object type, which is always thread.message.file. - */ - String object; + /** + * The identifier, which can be referenced in API endpoints. + */ + String id; - /** - * The Unix timestamp (in seconds) for when the message file was created. - */ - @JsonProperty("created_at") - int createdAt; + /** + * The object type, which is always thread.message.file. + */ + String object; - /** - * The ID of the message that the File is attached to. - */ - @JsonProperty("message_id") - String messageId; + /** + * The Unix timestamp (in seconds) for when the message file was created. + */ + @JsonProperty("created_at") + int createdAt; + + /** + * The ID of the message that the File is attached to. + */ + @JsonProperty("message_id") + String messageId; } diff --git a/api/src/main/java/com/launchableinc/openai/messages/MessageRequest.java b/api/src/main/java/com/launchableinc/openai/messages/MessageRequest.java index 6c49a110..301603fc 100644 --- a/api/src/main/java/com/launchableinc/openai/messages/MessageRequest.java +++ b/api/src/main/java/com/launchableinc/openai/messages/MessageRequest.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.messages; +package com.launchableinc.openai.messages; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.*; @@ -16,33 +16,32 @@ @AllArgsConstructor @Data public class MessageRequest { - /** - * The role of the entity that is creating the message. - * Currently only "user" is supported. - */ - @NonNull - @Builder.Default - String role = "user"; - /** - * The content of the message. - */ - @NonNull - String content; + /** + * The role of the entity that is creating the message. Currently only "user" is supported. + */ + @NonNull + @Builder.Default + String role = "user"; - /** - * A list of File IDs that the message should use. - * Defaults to an empty list. - * 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. - */ - @JsonProperty("file_ids") - List fileIds; + /** + * The content of the message. + */ + @NonNull + String content; - /** - * 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. - */ - Map metadata; + /** + * A list of File IDs that the message should use. Defaults to an empty list. 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. + */ + @JsonProperty("file_ids") + List fileIds; + + /** + * 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. + */ + Map metadata; } diff --git a/api/src/main/java/com/launchableinc/openai/messages/ModifyMessageRequest.java b/api/src/main/java/com/launchableinc/openai/messages/ModifyMessageRequest.java index 32344c96..288573da 100644 --- a/api/src/main/java/com/launchableinc/openai/messages/ModifyMessageRequest.java +++ b/api/src/main/java/com/launchableinc/openai/messages/ModifyMessageRequest.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.messages; +package com.launchableinc.openai.messages; import lombok.AllArgsConstructor; import lombok.Builder; @@ -18,10 +18,10 @@ @Data public class ModifyMessageRequest { - /** - * Set of 16 key-value pairs that can be attached to an object. - * This can be useful for storing additional information about the object in a structured format. - * Keys can be a maximum of 64 characters long, and values can be a maximum of 512 characters long. - */ - Map metadata; + /** + * 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. + */ + Map metadata; } diff --git a/api/src/main/java/com/launchableinc/openai/messages/content/Annotation.java b/api/src/main/java/com/launchableinc/openai/messages/content/Annotation.java index 473a5dfc..575470f8 100644 --- a/api/src/main/java/com/launchableinc/openai/messages/content/Annotation.java +++ b/api/src/main/java/com/launchableinc/openai/messages/content/Annotation.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.messages.content; +package com.launchableinc.openai.messages.content; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; @@ -14,31 +14,32 @@ @NoArgsConstructor @AllArgsConstructor public class Annotation { - /** - * The type of annotation, either file_citation or file_path - */ - String type; - - /** - * The text in the message content that needs to be replaced - */ - String text; - - /** - * File citation details, only present when type == file_citation - */ - @JsonProperty("file_citation") - FileCitation fileCitation; - - /** - * File path details, only present when type == file_path - */ - @JsonProperty("file_path") - FilePath filePath; - - @JsonProperty("start_index") - int startIndex; - - @JsonProperty("end_index") - int endIndex; + + /** + * The type of annotation, either file_citation or file_path + */ + String type; + + /** + * The text in the message content that needs to be replaced + */ + String text; + + /** + * File citation details, only present when type == file_citation + */ + @JsonProperty("file_citation") + FileCitation fileCitation; + + /** + * File path details, only present when type == file_path + */ + @JsonProperty("file_path") + FilePath filePath; + + @JsonProperty("start_index") + int startIndex; + + @JsonProperty("end_index") + int endIndex; } diff --git a/api/src/main/java/com/launchableinc/openai/messages/content/FileCitation.java b/api/src/main/java/com/launchableinc/openai/messages/content/FileCitation.java index ff486d55..cc293bb5 100644 --- a/api/src/main/java/com/launchableinc/openai/messages/content/FileCitation.java +++ b/api/src/main/java/com/launchableinc/openai/messages/content/FileCitation.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.messages.content; +package com.launchableinc.openai.messages.content; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; @@ -6,8 +6,9 @@ import lombok.NoArgsConstructor; /** - * A citation within the message that points to a specific quote from a specific File associated with the - * assistant or the message. Generated when the assistant uses the "retrieval" tool to search files. + * A citation within the message that points to a specific quote from a specific File associated + * with the assistant or the message. Generated when the assistant uses the "retrieval" tool to + * search files. *

* https://platform.openai.com/docs/api-reference/messages/object */ @@ -16,14 +17,14 @@ @AllArgsConstructor public class FileCitation { - /** - * The ID of the specific File the citation is from. - */ - @JsonProperty("file_id") - String fileId; + /** + * The ID of the specific File the citation is from. + */ + @JsonProperty("file_id") + String fileId; - /** - * The specific quote in the file. - */ - String quote; + /** + * The specific quote in the file. + */ + String quote; } diff --git a/api/src/main/java/com/launchableinc/openai/messages/content/FilePath.java b/api/src/main/java/com/launchableinc/openai/messages/content/FilePath.java index b11cc1af..81533620 100644 --- a/api/src/main/java/com/launchableinc/openai/messages/content/FilePath.java +++ b/api/src/main/java/com/launchableinc/openai/messages/content/FilePath.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.messages.content; +package com.launchableinc.openai.messages.content; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; @@ -6,7 +6,8 @@ import lombok.NoArgsConstructor; /** - * A URL for the file that's generated when the assistant used the code_interpreter tool to generate a file. + * A URL for the file that's generated when the assistant used the code_interpreter tool to generate + * a file. *

* https://platform.openai.com/docs/api-reference/messages/object */ @@ -15,9 +16,9 @@ @AllArgsConstructor public class FilePath { - /** - * The ID of the file that was generated - */ - @JsonProperty("file_id") - String fileId; + /** + * The ID of the file that was generated + */ + @JsonProperty("file_id") + String fileId; } diff --git a/api/src/main/java/com/launchableinc/openai/messages/content/ImageFile.java b/api/src/main/java/com/launchableinc/openai/messages/content/ImageFile.java index 2a43fa02..c8158b81 100644 --- a/api/src/main/java/com/launchableinc/openai/messages/content/ImageFile.java +++ b/api/src/main/java/com/launchableinc/openai/messages/content/ImageFile.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.messages.content; +package com.launchableinc.openai.messages.content; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; @@ -15,9 +15,9 @@ @AllArgsConstructor public class ImageFile { - /** - * The File ID of the image in the message content. - */ - @JsonProperty("file_id") - String fileId; + /** + * The File ID of the image in the message content. + */ + @JsonProperty("file_id") + String fileId; } diff --git a/api/src/main/java/com/launchableinc/openai/messages/content/Text.java b/api/src/main/java/com/launchableinc/openai/messages/content/Text.java index 6efa28bf..85371be8 100644 --- a/api/src/main/java/com/launchableinc/openai/messages/content/Text.java +++ b/api/src/main/java/com/launchableinc/openai/messages/content/Text.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.messages.content; +package com.launchableinc.openai.messages.content; import lombok.AllArgsConstructor; import lombok.Data; @@ -16,13 +16,13 @@ @AllArgsConstructor public class Text { - /** - * The data that makes up the text. - */ - String value; + /** + * The data that makes up the text. + */ + String value; - /** - * Text annotations that show additional details - */ - List annotations; + /** + * Text annotations that show additional details + */ + List annotations; } diff --git a/api/src/main/java/com/launchableinc/openai/model/Model.java b/api/src/main/java/com/launchableinc/openai/model/Model.java index 2add679d..216c2367 100644 --- a/api/src/main/java/com/launchableinc/openai/model/Model.java +++ b/api/src/main/java/com/launchableinc/openai/model/Model.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.model; +package com.launchableinc.openai.model; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; @@ -7,40 +7,41 @@ /** * GPT model details - * + *

* https://beta.openai.com/docs/api-reference/models */ @Data public class Model { - /** - * An identifier for this model, used to specify the model when making completions, etc - */ - public String id; - - /** - * The type of object returned, should be "model" - */ - public String object; - - /** - * The owner of the model, typically "openai" - */ - @JsonProperty("owned_by") - public String ownedBy; - - /** - * List of permissions for this model. No longer returned by OpenAI - */ - @Deprecated - public List permission; - - /** - * The root model that this and its parent (if applicable) are based on - */ - public String root; - - /** - * The parent model that this is based on - */ - public String parent; + + /** + * An identifier for this model, used to specify the model when making completions, etc + */ + public String id; + + /** + * The type of object returned, should be "model" + */ + public String object; + + /** + * The owner of the model, typically "openai" + */ + @JsonProperty("owned_by") + public String ownedBy; + + /** + * List of permissions for this model. No longer returned by OpenAI + */ + @Deprecated + public List permission; + + /** + * The root model that this and its parent (if applicable) are based on + */ + public String root; + + /** + * The parent model that this is based on + */ + public String parent; } diff --git a/api/src/main/java/com/launchableinc/openai/model/Permission.java b/api/src/main/java/com/launchableinc/openai/model/Permission.java index 475f053f..bbfd4ff2 100644 --- a/api/src/main/java/com/launchableinc/openai/model/Permission.java +++ b/api/src/main/java/com/launchableinc/openai/model/Permission.java @@ -1,55 +1,55 @@ -package com.theokanning.openai.model; +package com.launchableinc.openai.model; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; /** - * Model permissions - * I couldn't find documentation for the specific permissions, and I've elected to leave them undocumented rather than - * write something incorrect. - * + * Model permissions I couldn't find documentation for the specific permissions, and I've elected to + * leave them undocumented rather than write something incorrect. + *

* https://beta.openai.com/docs/api-reference/models */ @Data public class Permission { - /** - * An identifier for this model permission - */ - public String id; - /** - * The type of object returned, should be "model_permission" - */ - public String object; + /** + * An identifier for this model permission + */ + public String id; - /** - * The creation time in epoch seconds. - */ - public long created; + /** + * The type of object returned, should be "model_permission" + */ + public String object; - @JsonProperty("allow_create_engine") - public boolean allowCreateEngine; + /** + * The creation time in epoch seconds. + */ + public long created; - @JsonProperty("allow_sampling") - public boolean allowSampling; + @JsonProperty("allow_create_engine") + public boolean allowCreateEngine; - @JsonProperty("allow_log_probs") - public boolean allowLogProbs; + @JsonProperty("allow_sampling") + public boolean allowSampling; - @JsonProperty("allow_search_indices") - public boolean allowSearchIndices; + @JsonProperty("allow_log_probs") + public boolean allowLogProbs; - @JsonProperty("allow_view") - public boolean allowView; + @JsonProperty("allow_search_indices") + public boolean allowSearchIndices; - @JsonProperty("allow_fine_tuning") - public boolean allowFineTuning; + @JsonProperty("allow_view") + public boolean allowView; - public String organization; + @JsonProperty("allow_fine_tuning") + public boolean allowFineTuning; - public String group; + public String organization; - @JsonProperty("is_blocking") - public boolean isBlocking; + public String group; + + @JsonProperty("is_blocking") + public boolean isBlocking; } diff --git a/api/src/main/java/com/launchableinc/openai/moderation/Moderation.java b/api/src/main/java/com/launchableinc/openai/moderation/Moderation.java index 4d7de8b5..87447dad 100644 --- a/api/src/main/java/com/launchableinc/openai/moderation/Moderation.java +++ b/api/src/main/java/com/launchableinc/openai/moderation/Moderation.java @@ -1,32 +1,34 @@ -package com.theokanning.openai.moderation; +package com.launchableinc.openai.moderation; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; /** * An object containing the moderation data for a single input string - * + *

* https://beta.openai.com/docs/api-reference/moderations/create */ @Data public class Moderation { - /** - * Set to true if the model classifies the content as violating OpenAI's content policy, false otherwise - */ - public boolean flagged; - /** - * Object containing per-category binary content policy violation flags. - * For each category, the value is true if the model flags the corresponding category as violated, false otherwise. - */ - public ModerationCategories categories; + /** + * Set to true if the model classifies the content as violating OpenAI's content policy, false + * otherwise + */ + public boolean flagged; - /** - * Object containing per-category raw scores output by the model, denoting the model's confidence that the - * input violates the OpenAI's policy for the category. - * The value is between 0 and 1, where higher values denote higher confidence. - * The scores should not be interpreted as probabilities. - */ - @JsonProperty("category_scores") - public ModerationCategoryScores categoryScores; + /** + * Object containing per-category binary content policy violation flags. For each category, the + * value is true if the model flags the corresponding category as violated, false otherwise. + */ + public ModerationCategories categories; + + /** + * Object containing per-category raw scores output by the model, denoting the model's confidence + * that the input violates the OpenAI's policy for the category. The value is between 0 and 1, + * where higher values denote higher confidence. The scores should not be interpreted as + * probabilities. + */ + @JsonProperty("category_scores") + public ModerationCategoryScores categoryScores; } diff --git a/api/src/main/java/com/launchableinc/openai/moderation/ModerationCategories.java b/api/src/main/java/com/launchableinc/openai/moderation/ModerationCategories.java index 238d0a05..a258cf15 100644 --- a/api/src/main/java/com/launchableinc/openai/moderation/ModerationCategories.java +++ b/api/src/main/java/com/launchableinc/openai/moderation/ModerationCategories.java @@ -1,33 +1,31 @@ -package com.theokanning.openai.moderation; +package com.launchableinc.openai.moderation; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; -import java.util.List; - /** * An object containing the flags for each moderation category - * + *

* https://beta.openai.com/docs/api-reference/moderations/create */ @Data public class ModerationCategories { - public boolean hate; + public boolean hate; - @JsonProperty("hate/threatening") - public boolean hateThreatening; + @JsonProperty("hate/threatening") + public boolean hateThreatening; - @JsonProperty("self-harm") - public boolean selfHarm; + @JsonProperty("self-harm") + public boolean selfHarm; - public boolean sexual; + public boolean sexual; - @JsonProperty("sexual/minors") - public boolean sexualMinors; + @JsonProperty("sexual/minors") + public boolean sexualMinors; - public boolean violence; + public boolean violence; - @JsonProperty("violence/graphic") - public boolean violenceGraphic; + @JsonProperty("violence/graphic") + public boolean violenceGraphic; } diff --git a/api/src/main/java/com/launchableinc/openai/moderation/ModerationCategoryScores.java b/api/src/main/java/com/launchableinc/openai/moderation/ModerationCategoryScores.java index 94e056a9..10ac2d6e 100644 --- a/api/src/main/java/com/launchableinc/openai/moderation/ModerationCategoryScores.java +++ b/api/src/main/java/com/launchableinc/openai/moderation/ModerationCategoryScores.java @@ -1,31 +1,31 @@ -package com.theokanning.openai.moderation; +package com.launchableinc.openai.moderation; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; /** * An object containing the scores for each moderation category - * + *

* https://beta.openai.com/docs/api-reference/moderations/create */ @Data public class ModerationCategoryScores { - public double hate; + public double hate; - @JsonProperty("hate/threatening") - public double hateThreatening; + @JsonProperty("hate/threatening") + public double hateThreatening; - @JsonProperty("self-harm") - public double selfHarm; + @JsonProperty("self-harm") + public double selfHarm; - public double sexual; + public double sexual; - @JsonProperty("sexual/minors") - public double sexualMinors; + @JsonProperty("sexual/minors") + public double sexualMinors; - public double violence; + public double violence; - @JsonProperty("violence/graphic") - public double violenceGraphic; + @JsonProperty("violence/graphic") + public double violenceGraphic; } diff --git a/api/src/main/java/com/launchableinc/openai/moderation/ModerationRequest.java b/api/src/main/java/com/launchableinc/openai/moderation/ModerationRequest.java index 08513420..9b8b4ba4 100644 --- a/api/src/main/java/com/launchableinc/openai/moderation/ModerationRequest.java +++ b/api/src/main/java/com/launchableinc/openai/moderation/ModerationRequest.java @@ -1,10 +1,10 @@ -package com.theokanning.openai.moderation; +package com.launchableinc.openai.moderation; import lombok.*; /** * A request for OpenAi to detect if text violates OpenAi's content policy. - * + *

* https://beta.openai.com/docs/api-reference/moderations/create */ @Builder @@ -13,14 +13,14 @@ @Data public class ModerationRequest { - /** - * The input text to classify. - */ - @NonNull - String input; + /** + * The input text to classify. + */ + @NonNull + String input; - /** - * The name of the model to use, defaults to text-moderation-stable. - */ - String model; + /** + * The name of the model to use, defaults to text-moderation-stable. + */ + String model; } diff --git a/api/src/main/java/com/launchableinc/openai/moderation/ModerationResult.java b/api/src/main/java/com/launchableinc/openai/moderation/ModerationResult.java index f8b432c2..d766f789 100644 --- a/api/src/main/java/com/launchableinc/openai/moderation/ModerationResult.java +++ b/api/src/main/java/com/launchableinc/openai/moderation/ModerationResult.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.moderation; +package com.launchableinc.openai.moderation; import lombok.Data; @@ -6,23 +6,24 @@ /** * An object containing a response from the moderation api - * + *

* https://beta.openai.com/docs/api-reference/moderations/create */ @Data public class ModerationResult { - /** - * A unique id assigned to this moderation. - */ - public String id; - /** - * The model used. - */ - public String model; + /** + * A unique id assigned to this moderation. + */ + public String id; - /** - * A list of moderation scores. - */ - public List results; + /** + * The model used. + */ + public String model; + + /** + * A list of moderation scores. + */ + public List results; } diff --git a/api/src/main/java/com/launchableinc/openai/runs/CreateThreadAndRunRequest.java b/api/src/main/java/com/launchableinc/openai/runs/CreateThreadAndRunRequest.java index b27de696..43437dbf 100644 --- a/api/src/main/java/com/launchableinc/openai/runs/CreateThreadAndRunRequest.java +++ b/api/src/main/java/com/launchableinc/openai/runs/CreateThreadAndRunRequest.java @@ -1,8 +1,8 @@ -package com.theokanning.openai.runs; +package com.launchableinc.openai.runs; import com.fasterxml.jackson.annotation.JsonProperty; -import com.theokanning.openai.assistants.Tool; -import com.theokanning.openai.threads.ThreadRequest; +import com.launchableinc.openai.assistants.Tool; +import com.launchableinc.openai.threads.ThreadRequest; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -23,17 +23,17 @@ @NoArgsConstructor @AllArgsConstructor public class CreateThreadAndRunRequest { - - @JsonProperty("assistant_id") - private String assistantId; - - private ThreadRequest thread; - private String model; - - private String instructions; + @JsonProperty("assistant_id") + private String assistantId; - private List tools; + private ThreadRequest thread; - private Map metadata; + private String model; + + private String instructions; + + private List tools; + + private Map metadata; } diff --git a/api/src/main/java/com/launchableinc/openai/runs/MessageCreation.java b/api/src/main/java/com/launchableinc/openai/runs/MessageCreation.java index 535fd7e2..86b6c8fd 100644 --- a/api/src/main/java/com/launchableinc/openai/runs/MessageCreation.java +++ b/api/src/main/java/com/launchableinc/openai/runs/MessageCreation.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.runs; +package com.launchableinc.openai.runs; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; @@ -11,7 +11,7 @@ @NoArgsConstructor @AllArgsConstructor public class MessageCreation { - - @JsonProperty("message_id") - String messageId; + + @JsonProperty("message_id") + String messageId; } diff --git a/api/src/main/java/com/launchableinc/openai/runs/RequiredAction.java b/api/src/main/java/com/launchableinc/openai/runs/RequiredAction.java index 959b89dc..a2c9e76c 100644 --- a/api/src/main/java/com/launchableinc/openai/runs/RequiredAction.java +++ b/api/src/main/java/com/launchableinc/openai/runs/RequiredAction.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.runs; +package com.launchableinc.openai.runs; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; @@ -18,9 +18,9 @@ @NoArgsConstructor @AllArgsConstructor public class RequiredAction { - - private String type; - @JsonProperty("submit_tool_outputs") - private SubmitToolOutputs submitToolOutputs; + private String type; + + @JsonProperty("submit_tool_outputs") + private SubmitToolOutputs submitToolOutputs; } diff --git a/api/src/main/java/com/launchableinc/openai/runs/Run.java b/api/src/main/java/com/launchableinc/openai/runs/Run.java index 1da9ec95..6981ab2f 100644 --- a/api/src/main/java/com/launchableinc/openai/runs/Run.java +++ b/api/src/main/java/com/launchableinc/openai/runs/Run.java @@ -1,8 +1,8 @@ -package com.theokanning.openai.runs; +package com.launchableinc.openai.runs; import com.fasterxml.jackson.annotation.JsonProperty; -import com.theokanning.openai.assistants.Tool; -import com.theokanning.openai.common.LastError; +import com.launchableinc.openai.assistants.Tool; +import com.launchableinc.openai.common.LastError; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -17,50 +17,50 @@ @AllArgsConstructor public class Run { - private String id; + private String id; - private String object; + private String object; - @JsonProperty("created_at") - private Integer createdAt; + @JsonProperty("created_at") + private Integer createdAt; - @JsonProperty("thread_id") - private String threadId; + @JsonProperty("thread_id") + private String threadId; - @JsonProperty("assistant_id") - private String assistantId; + @JsonProperty("assistant_id") + private String assistantId; - private String status; + private String status; - @JsonProperty("required_action") - private RequiredAction requiredAction; + @JsonProperty("required_action") + private RequiredAction requiredAction; - @JsonProperty("last_error") - private LastError lastError; + @JsonProperty("last_error") + private LastError lastError; - @JsonProperty("expires_at") - private Integer expiresAt; + @JsonProperty("expires_at") + private Integer expiresAt; - @JsonProperty("started_at") - private Integer startedAt; - - @JsonProperty("cancelled_at") - private Integer cancelledAt; + @JsonProperty("started_at") + private Integer startedAt; - @JsonProperty("failed_at") - private Integer failedAt; - - @JsonProperty("completed_at") - private Integer completedAt; + @JsonProperty("cancelled_at") + private Integer cancelledAt; - private String model; + @JsonProperty("failed_at") + private Integer failedAt; - private String instructions; + @JsonProperty("completed_at") + private Integer completedAt; - private List tools; - - @JsonProperty("file_ids") - private List fileIds; + private String model; - private Map metadata; + private String instructions; + + private List tools; + + @JsonProperty("file_ids") + private List fileIds; + + private Map metadata; } diff --git a/api/src/main/java/com/launchableinc/openai/runs/RunCreateRequest.java b/api/src/main/java/com/launchableinc/openai/runs/RunCreateRequest.java index cba5f283..157260ab 100644 --- a/api/src/main/java/com/launchableinc/openai/runs/RunCreateRequest.java +++ b/api/src/main/java/com/launchableinc/openai/runs/RunCreateRequest.java @@ -1,6 +1,6 @@ -package com.theokanning.openai.runs; +package com.launchableinc.openai.runs; -import com.theokanning.openai.assistants.Tool; +import com.launchableinc.openai.assistants.Tool; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -14,14 +14,15 @@ @AllArgsConstructor @Data public class RunCreateRequest { - String assistantId; - - // Optional - String model; - - String instructions; - - List tools; - - Map metadata; + + String assistantId; + + // Optional + String model; + + String instructions; + + List tools; + + Map metadata; } diff --git a/api/src/main/java/com/launchableinc/openai/runs/RunImage.java b/api/src/main/java/com/launchableinc/openai/runs/RunImage.java index 18135187..3cc3e187 100644 --- a/api/src/main/java/com/launchableinc/openai/runs/RunImage.java +++ b/api/src/main/java/com/launchableinc/openai/runs/RunImage.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.runs; +package com.launchableinc.openai.runs; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; @@ -19,6 +19,6 @@ @AllArgsConstructor public class RunImage { - @JsonProperty("file_id") - private String fileId; + @JsonProperty("file_id") + private String fileId; } diff --git a/api/src/main/java/com/launchableinc/openai/runs/RunStep.java b/api/src/main/java/com/launchableinc/openai/runs/RunStep.java index 7cd39342..cc26a49d 100644 --- a/api/src/main/java/com/launchableinc/openai/runs/RunStep.java +++ b/api/src/main/java/com/launchableinc/openai/runs/RunStep.java @@ -1,7 +1,7 @@ -package com.theokanning.openai.runs; +package com.launchableinc.openai.runs; import com.fasterxml.jackson.annotation.JsonProperty; -import com.theokanning.openai.common.LastError; +import com.launchableinc.openai.common.LastError; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -15,44 +15,44 @@ @Data public class RunStep { - private String id; + private String id; - private String object; + private String object; - @JsonProperty("created_at") - private Integer createdAt; - - @JsonProperty("assistant_id") - private String assistantId; + @JsonProperty("created_at") + private Integer createdAt; - @JsonProperty("thread_id") - private String threadId; + @JsonProperty("assistant_id") + private String assistantId; - @JsonProperty("run_id") - private String runId; + @JsonProperty("thread_id") + private String threadId; - private String type; - - private String status; + @JsonProperty("run_id") + private String runId; - @JsonProperty("step_details") - private StepDetails stepDetails; + private String type; - @JsonProperty("last_error") - private LastError lastError; + private String status; - @JsonProperty("expired_at") - private Integer expiredAt; - - @JsonProperty("cancelled_at") - private Integer cancelledAt; + @JsonProperty("step_details") + private StepDetails stepDetails; + + @JsonProperty("last_error") + private LastError lastError; + + @JsonProperty("expired_at") + private Integer expiredAt; + + @JsonProperty("cancelled_at") + private Integer cancelledAt; + + @JsonProperty("failed_at") + private Integer failedAt; + + @JsonProperty("completed_at") + private Integer completedAt; + + private Map metadata; - @JsonProperty("failed_at") - private Integer failedAt; - - @JsonProperty("completed_at") - private Integer completedAt; - - private Map metadata; - } diff --git a/api/src/main/java/com/launchableinc/openai/runs/StepDetails.java b/api/src/main/java/com/launchableinc/openai/runs/StepDetails.java index 08972623..37e14993 100644 --- a/api/src/main/java/com/launchableinc/openai/runs/StepDetails.java +++ b/api/src/main/java/com/launchableinc/openai/runs/StepDetails.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.runs; +package com.launchableinc.openai.runs; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; @@ -14,12 +14,12 @@ @AllArgsConstructor public class StepDetails { - - private String type; - @JsonProperty("message_creation") - private MessageCreation messageCreation; + private String type; - @JsonProperty("tool_calls") - private List toolCalls; + @JsonProperty("message_creation") + private MessageCreation messageCreation; + + @JsonProperty("tool_calls") + private List toolCalls; } diff --git a/api/src/main/java/com/launchableinc/openai/runs/SubmitToolOutputRequestItem.java b/api/src/main/java/com/launchableinc/openai/runs/SubmitToolOutputRequestItem.java index ec2b346a..d525af7d 100644 --- a/api/src/main/java/com/launchableinc/openai/runs/SubmitToolOutputRequestItem.java +++ b/api/src/main/java/com/launchableinc/openai/runs/SubmitToolOutputRequestItem.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.runs; +package com.launchableinc.openai.runs; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; @@ -19,8 +19,8 @@ @AllArgsConstructor public class SubmitToolOutputRequestItem { - @JsonProperty("tool_call_id") - private String toolCallId; - - private String output; + @JsonProperty("tool_call_id") + private String toolCallId; + + private String output; } diff --git a/api/src/main/java/com/launchableinc/openai/runs/SubmitToolOutputs.java b/api/src/main/java/com/launchableinc/openai/runs/SubmitToolOutputs.java index e0aca757..4ee15633 100644 --- a/api/src/main/java/com/launchableinc/openai/runs/SubmitToolOutputs.java +++ b/api/src/main/java/com/launchableinc/openai/runs/SubmitToolOutputs.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.runs; +package com.launchableinc.openai.runs; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; @@ -20,7 +20,7 @@ @NoArgsConstructor @AllArgsConstructor public class SubmitToolOutputs { - - @JsonProperty("tool_calls") - List toolCalls; + + @JsonProperty("tool_calls") + List toolCalls; } diff --git a/api/src/main/java/com/launchableinc/openai/runs/SubmitToolOutputsRequest.java b/api/src/main/java/com/launchableinc/openai/runs/SubmitToolOutputsRequest.java index f892f168..1e48ed78 100644 --- a/api/src/main/java/com/launchableinc/openai/runs/SubmitToolOutputsRequest.java +++ b/api/src/main/java/com/launchableinc/openai/runs/SubmitToolOutputsRequest.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.runs; +package com.launchableinc.openai.runs; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; @@ -20,7 +20,7 @@ @NoArgsConstructor @AllArgsConstructor public class SubmitToolOutputsRequest { - - @JsonProperty("tool_outputs") - private List toolOutputs; + + @JsonProperty("tool_outputs") + private List toolOutputs; } diff --git a/api/src/main/java/com/launchableinc/openai/runs/ToolCall.java b/api/src/main/java/com/launchableinc/openai/runs/ToolCall.java index 8aa6c26c..94d08aa6 100644 --- a/api/src/main/java/com/launchableinc/openai/runs/ToolCall.java +++ b/api/src/main/java/com/launchableinc/openai/runs/ToolCall.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.runs; +package com.launchableinc.openai.runs; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; @@ -20,15 +20,15 @@ @NoArgsConstructor @AllArgsConstructor public class ToolCall { - - private String id; - - private String type; - - @JsonProperty("code_interpreter") - private ToolCallCodeInterpreter codeInterpreter; - private Map retrieval; + private String id; - private ToolCallFunction function; + private String type; + + @JsonProperty("code_interpreter") + private ToolCallCodeInterpreter codeInterpreter; + + private Map retrieval; + + private ToolCallFunction function; } diff --git a/api/src/main/java/com/launchableinc/openai/runs/ToolCallCodeInterpreter.java b/api/src/main/java/com/launchableinc/openai/runs/ToolCallCodeInterpreter.java index c2a3a446..a6a58b51 100644 --- a/api/src/main/java/com/launchableinc/openai/runs/ToolCallCodeInterpreter.java +++ b/api/src/main/java/com/launchableinc/openai/runs/ToolCallCodeInterpreter.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.runs; +package com.launchableinc.openai.runs; import lombok.AllArgsConstructor; import lombok.Builder; @@ -19,8 +19,8 @@ @NoArgsConstructor @AllArgsConstructor public class ToolCallCodeInterpreter { - - private String input; - - private List outputs; + + private String input; + + private List outputs; } diff --git a/api/src/main/java/com/launchableinc/openai/runs/ToolCallCodeInterpreterOutput.java b/api/src/main/java/com/launchableinc/openai/runs/ToolCallCodeInterpreterOutput.java index 179ef2f1..cfae2444 100644 --- a/api/src/main/java/com/launchableinc/openai/runs/ToolCallCodeInterpreterOutput.java +++ b/api/src/main/java/com/launchableinc/openai/runs/ToolCallCodeInterpreterOutput.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.runs; +package com.launchableinc.openai.runs; import lombok.AllArgsConstructor; import lombok.Builder; @@ -17,10 +17,10 @@ @NoArgsConstructor @AllArgsConstructor public class ToolCallCodeInterpreterOutput { - - private String type; - - private String logs; - - private RunImage image; + + private String type; + + private String logs; + + private RunImage image; } diff --git a/api/src/main/java/com/launchableinc/openai/runs/ToolCallFunction.java b/api/src/main/java/com/launchableinc/openai/runs/ToolCallFunction.java index 34de58d1..de3e40f5 100644 --- a/api/src/main/java/com/launchableinc/openai/runs/ToolCallFunction.java +++ b/api/src/main/java/com/launchableinc/openai/runs/ToolCallFunction.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.runs; +package com.launchableinc.openai.runs; import lombok.AllArgsConstructor; import lombok.Builder; @@ -16,10 +16,10 @@ @NoArgsConstructor @AllArgsConstructor public class ToolCallFunction { - - private String name; - - private String arguments; - - private String output; + + private String name; + + private String arguments; + + private String output; } diff --git a/api/src/main/java/com/launchableinc/openai/threads/Thread.java b/api/src/main/java/com/launchableinc/openai/threads/Thread.java index 24adb73f..083d7b62 100644 --- a/api/src/main/java/com/launchableinc/openai/threads/Thread.java +++ b/api/src/main/java/com/launchableinc/openai/threads/Thread.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.threads; +package com.launchableinc.openai.threads; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; @@ -16,26 +16,27 @@ @AllArgsConstructor @Data public class Thread { - /** - * The identifier, which can be referenced in API endpoints. - */ - String id; - /** - * The object type, which is always thread. - */ - String object; + /** + * The identifier, which can be referenced in API endpoints. + */ + String id; - /** - * The Unix timestamp (in seconds) for when the thread was created. - */ - @JsonProperty("created_at") - int createdAt; + /** + * The object type, which is always thread. + */ + String object; - /** - * 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. - */ - Map metadata; + /** + * The Unix timestamp (in seconds) for when the thread was created. + */ + @JsonProperty("created_at") + int createdAt; + + /** + * 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. + */ + Map metadata; } diff --git a/api/src/main/java/com/launchableinc/openai/threads/ThreadRequest.java b/api/src/main/java/com/launchableinc/openai/threads/ThreadRequest.java index 35fd888a..f15ab951 100644 --- a/api/src/main/java/com/launchableinc/openai/threads/ThreadRequest.java +++ b/api/src/main/java/com/launchableinc/openai/threads/ThreadRequest.java @@ -1,7 +1,6 @@ -package com.theokanning.openai.threads; +package com.launchableinc.openai.threads; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.theokanning.openai.messages.MessageRequest; +import com.launchableinc.openai.messages.MessageRequest; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -20,15 +19,16 @@ @AllArgsConstructor @Data public class ThreadRequest { - /** - * A list of messages to start the thread with. Optional. - */ - List messages; - /** - * 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. - */ - Map metadata; + /** + * A list of messages to start the thread with. Optional. + */ + List messages; + + /** + * 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. + */ + Map metadata; } diff --git a/api/src/main/java/com/launchableinc/openai/utils/TikTokensUtil.java b/api/src/main/java/com/launchableinc/openai/utils/TikTokensUtil.java index 0a50907e..3b714b9f 100644 --- a/api/src/main/java/com/launchableinc/openai/utils/TikTokensUtil.java +++ b/api/src/main/java/com/launchableinc/openai/utils/TikTokensUtil.java @@ -1,11 +1,11 @@ -package com.theokanning.openai.utils; +package com.launchableinc.openai.utils; import com.knuddels.jtokkit.Encodings; import com.knuddels.jtokkit.api.Encoding; import com.knuddels.jtokkit.api.EncodingRegistry; import com.knuddels.jtokkit.api.EncodingType; import com.knuddels.jtokkit.api.ModelType; -import com.theokanning.openai.completion.chat.ChatMessage; +import com.launchableinc.openai.completion.chat.ChatMessage; import lombok.AllArgsConstructor; import lombok.Getter; @@ -15,286 +15,290 @@ * Token calculation tool class */ public class TikTokensUtil { - /** - * Model name corresponds to Encoding - */ - private static final Map modelMap = new HashMap<>(); - /** - * Registry instance - */ - private static final EncodingRegistry registry = Encodings.newDefaultEncodingRegistry(); - - static { - for (ModelType modelType : ModelType.values()) { - modelMap.put(modelType.getName(), registry.getEncodingForModel(modelType)); - } - modelMap.put(ModelEnum.GPT_3_5_TURBO_0301.getName(), registry.getEncodingForModel(ModelType.GPT_3_5_TURBO)); - modelMap.put(ModelEnum.GPT_4_32K.getName(), registry.getEncodingForModel(ModelType.GPT_4)); - modelMap.put(ModelEnum.GPT_4_32K_0314.getName(), registry.getEncodingForModel(ModelType.GPT_4)); - modelMap.put(ModelEnum.GPT_4_0314.getName(), registry.getEncodingForModel(ModelType.GPT_4)); - modelMap.put(ModelEnum.GPT_4_1106_preview.getName(), registry.getEncodingForModel(ModelType.GPT_4)); - } - - /** - * Get encoding array through Encoding and text. - * - * @param enc Encoding type - * @param text Text information - * @return Encoding array - */ - public static List encode(Encoding enc, String text) { - return isBlank(text) ? new ArrayList<>() : enc.encode(text); - } - - /** - * Calculate tokens of text information through Encoding. - * - * @param enc Encoding type - * @param text Text information - * @return Number of tokens - */ - public static int tokens(Encoding enc, String text) { - return encode(enc, text).size(); - } - - - /** - * Reverse calculate text information through Encoding and encoded array - * - * @param enc Encoding - * @param encoded Encoding array - * @return Text information corresponding to the encoding array. - */ - public static String decode(Encoding enc, List encoded) { - return enc.decode(encoded); - } - - /** - * Get an Encoding object by Encoding type - * - * @param encodingType - * @return Encoding - */ - public static Encoding getEncoding(EncodingType encodingType) { - Encoding enc = registry.getEncoding(encodingType); - return enc; - } - - /** - * Obtain the encoding array by encoding; - * - * @param text - * @return Encoding array - */ - public static List encode(EncodingType encodingType, String text) { - if (isBlank(text)) { - return new ArrayList<>(); - } - Encoding enc = getEncoding(encodingType); - List encoded = enc.encode(text); - return encoded; - } - - /** - * Compute the tokens of the specified string through EncodingType. - * - * @param encodingType - * @param text - * @return Number of tokens - */ - public static int tokens(EncodingType encodingType, String text) { - return encode(encodingType, text).size(); - } - - - /** - * Reverse the encoded array to get the string text using EncodingType and the encoded array. - * - * @param encodingType - * @param encoded - * @return The string corresponding to the encoding array. - */ - public static String decode(EncodingType encodingType, List encoded) { - Encoding enc = getEncoding(encodingType); - return enc.decode(encoded); - } - - - /** - * Get an Encoding object by model name. - * - * @param modelName - * @return Encoding - */ - public static Encoding getEncoding(String modelName) { - return modelMap.get(modelName); - } - - /** - * Get the encoded array by model name using encode. - * - * @param text Text information - * @return Encoding array - */ - public static List encode(String modelName, String text) { - if (isBlank(text)) { - return new ArrayList<>(); - } - Encoding enc = getEncoding(modelName); - if (Objects.isNull(enc)) { - return new ArrayList<>(); - } - List encoded = enc.encode(text); - return encoded; - } - - /** - * Calculate the tokens of a specified string by model name. - * - * @param modelName - * @param text - * @return Number of tokens - */ - public static int tokens(String modelName, String text) { - return encode(modelName, text).size(); - } - - - /** - * Calculate the encoded array for messages by model name. - * Refer to the official processing logic: - * https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb - * - * @param modelName - * @param messages - * @return Number of tokens - */ - public static int tokens(String modelName, List messages) { - Encoding encoding = getEncoding(modelName); - int tokensPerMessage = 0; - int tokensPerName = 0; - //3.5统一处理 - if (modelName.equals("gpt-3.5-turbo-0301") || modelName.equals("gpt-3.5-turbo")) { - tokensPerMessage = 4; - tokensPerName = -1; - } - //4.0统一处理 - if (modelName.equals("gpt-4") || modelName.equals("gpt-4-0314")) { - tokensPerMessage = 3; - tokensPerName = 1; - } - int sum = 0; - for (ChatMessage msg : messages) { - sum += tokensPerMessage; - sum += tokens(encoding, msg.getContent()); - sum += tokens(encoding, msg.getRole()); - sum += tokens(encoding, msg.getName()); - if (isNotBlank(msg.getName())) { - sum += tokensPerName; - } - } - sum += 3; - return sum; - } - - /** - * Reverse the string text through the model name and the encoded array. - * - * @param modelName - * @param encoded - * @return - */ - public static String decode(String modelName, List encoded) { - Encoding enc = getEncoding(modelName); - return enc.decode(encoded); - } - - - /** - * Obtain the modelType. - * - * @param name - * @return - */ - public static ModelType getModelTypeByName(String name) { - if (ModelEnum.GPT_3_5_TURBO_0301.getName().equals(name)) { - return ModelType.GPT_3_5_TURBO; - } - if (ModelEnum.GPT_4.getName().equals(name) - || ModelEnum.GPT_4_32K.getName().equals(name) - || ModelEnum.GPT_4_32K_0314.getName().equals(name) - || ModelEnum.GPT_4_0314.getName().equals(name)) { - return ModelType.GPT_4; - } - - for (ModelType modelType : ModelType.values()) { - if (modelType.getName().equals(name)) { - return modelType; - } - } - return null; - } - - @Getter - @AllArgsConstructor - public enum ModelEnum { - /** - * gpt-3.5-turbo - */ - GPT_3_5_TURBO("gpt-3.5-turbo"), - /** - * Temporary model, not recommended for use. - */ - GPT_3_5_TURBO_0301("gpt-3.5-turbo-0301"), - /** - * GPT4.0 - */ - GPT_4("gpt-4"), - /** - * Temporary model, not recommended for use. - */ - GPT_4_0314("gpt-4-0314"), - /** - * GPT4.0 超长上下文 - */ - GPT_4_32K("gpt-4-32k"), - /** - * Temporary model, not recommended for use. - */ - GPT_4_32K_0314("gpt-4-32k-0314"), - - /** - * Temporary model, not recommended for use. - */ - GPT_4_1106_preview("gpt-4-1106-preview"); - private String name; - } - - public static boolean isBlankChar(int c) { - return Character.isWhitespace(c) || Character.isSpaceChar(c) || c == 65279 || c == 8234 || c == 0 || c == 12644 || c == 10240 || c == 6158; - } - - public static boolean isBlankChar(char c) { - return isBlankChar((int) c); - } - - public static boolean isNotBlank(CharSequence str) { - return !isBlank(str); - } - - public static boolean isBlank(CharSequence str) { - int length; - if (str != null && (length = str.length()) != 0) { - for (int i = 0; i < length; ++i) { - if (!isBlankChar(str.charAt(i))) { - return false; - } - } - - return true; - } else { - return true; - } - } + + /** + * Model name corresponds to Encoding + */ + private static final Map modelMap = new HashMap<>(); + /** + * Registry instance + */ + private static final EncodingRegistry registry = Encodings.newDefaultEncodingRegistry(); + + static { + for (ModelType modelType : ModelType.values()) { + modelMap.put(modelType.getName(), registry.getEncodingForModel(modelType)); + } + modelMap.put(ModelEnum.GPT_3_5_TURBO_0301.getName(), + registry.getEncodingForModel(ModelType.GPT_3_5_TURBO)); + modelMap.put(ModelEnum.GPT_4_32K.getName(), registry.getEncodingForModel(ModelType.GPT_4)); + modelMap.put(ModelEnum.GPT_4_32K_0314.getName(), registry.getEncodingForModel(ModelType.GPT_4)); + modelMap.put(ModelEnum.GPT_4_0314.getName(), registry.getEncodingForModel(ModelType.GPT_4)); + modelMap.put(ModelEnum.GPT_4_1106_preview.getName(), + registry.getEncodingForModel(ModelType.GPT_4)); + } + + /** + * Get encoding array through Encoding and text. + * + * @param enc Encoding type + * @param text Text information + * @return Encoding array + */ + public static List encode(Encoding enc, String text) { + return isBlank(text) ? new ArrayList<>() : enc.encode(text); + } + + /** + * Calculate tokens of text information through Encoding. + * + * @param enc Encoding type + * @param text Text information + * @return Number of tokens + */ + public static int tokens(Encoding enc, String text) { + return encode(enc, text).size(); + } + + + /** + * Reverse calculate text information through Encoding and encoded array + * + * @param enc Encoding + * @param encoded Encoding array + * @return Text information corresponding to the encoding array. + */ + public static String decode(Encoding enc, List encoded) { + return enc.decode(encoded); + } + + /** + * Get an Encoding object by Encoding type + * + * @param encodingType + * @return Encoding + */ + public static Encoding getEncoding(EncodingType encodingType) { + Encoding enc = registry.getEncoding(encodingType); + return enc; + } + + /** + * Obtain the encoding array by encoding; + * + * @param text + * @return Encoding array + */ + public static List encode(EncodingType encodingType, String text) { + if (isBlank(text)) { + return new ArrayList<>(); + } + Encoding enc = getEncoding(encodingType); + List encoded = enc.encode(text); + return encoded; + } + + /** + * Compute the tokens of the specified string through EncodingType. + * + * @param encodingType + * @param text + * @return Number of tokens + */ + public static int tokens(EncodingType encodingType, String text) { + return encode(encodingType, text).size(); + } + + + /** + * Reverse the encoded array to get the string text using EncodingType and the encoded array. + * + * @param encodingType + * @param encoded + * @return The string corresponding to the encoding array. + */ + public static String decode(EncodingType encodingType, List encoded) { + Encoding enc = getEncoding(encodingType); + return enc.decode(encoded); + } + + + /** + * Get an Encoding object by model name. + * + * @param modelName + * @return Encoding + */ + public static Encoding getEncoding(String modelName) { + return modelMap.get(modelName); + } + + /** + * Get the encoded array by model name using encode. + * + * @param text Text information + * @return Encoding array + */ + public static List encode(String modelName, String text) { + if (isBlank(text)) { + return new ArrayList<>(); + } + Encoding enc = getEncoding(modelName); + if (Objects.isNull(enc)) { + return new ArrayList<>(); + } + List encoded = enc.encode(text); + return encoded; + } + + /** + * Calculate the tokens of a specified string by model name. + * + * @param modelName + * @param text + * @return Number of tokens + */ + public static int tokens(String modelName, String text) { + return encode(modelName, text).size(); + } + + + /** + * Calculate the encoded array for messages by model name. Refer to the official processing logic: + * https://github.com/openai/openai-cookbook/blob/main/examples/How_to_count_tokens_with_tiktoken.ipynb + * + * @param modelName + * @param messages + * @return Number of tokens + */ + public static int tokens(String modelName, List messages) { + Encoding encoding = getEncoding(modelName); + int tokensPerMessage = 0; + int tokensPerName = 0; + //3.5统一处理 + if (modelName.equals("gpt-3.5-turbo-0301") || modelName.equals("gpt-3.5-turbo")) { + tokensPerMessage = 4; + tokensPerName = -1; + } + //4.0统一处理 + if (modelName.equals("gpt-4") || modelName.equals("gpt-4-0314")) { + tokensPerMessage = 3; + tokensPerName = 1; + } + int sum = 0; + for (ChatMessage msg : messages) { + sum += tokensPerMessage; + sum += tokens(encoding, msg.getContent()); + sum += tokens(encoding, msg.getRole()); + sum += tokens(encoding, msg.getName()); + if (isNotBlank(msg.getName())) { + sum += tokensPerName; + } + } + sum += 3; + return sum; + } + + /** + * Reverse the string text through the model name and the encoded array. + * + * @param modelName + * @param encoded + * @return + */ + public static String decode(String modelName, List encoded) { + Encoding enc = getEncoding(modelName); + return enc.decode(encoded); + } + + + /** + * Obtain the modelType. + * + * @param name + * @return + */ + public static ModelType getModelTypeByName(String name) { + if (ModelEnum.GPT_3_5_TURBO_0301.getName().equals(name)) { + return ModelType.GPT_3_5_TURBO; + } + if (ModelEnum.GPT_4.getName().equals(name) + || ModelEnum.GPT_4_32K.getName().equals(name) + || ModelEnum.GPT_4_32K_0314.getName().equals(name) + || ModelEnum.GPT_4_0314.getName().equals(name)) { + return ModelType.GPT_4; + } + + for (ModelType modelType : ModelType.values()) { + if (modelType.getName().equals(name)) { + return modelType; + } + } + return null; + } + + @Getter + @AllArgsConstructor + public enum ModelEnum { + /** + * gpt-3.5-turbo + */ + GPT_3_5_TURBO("gpt-3.5-turbo"), + /** + * Temporary model, not recommended for use. + */ + GPT_3_5_TURBO_0301("gpt-3.5-turbo-0301"), + /** + * GPT4.0 + */ + GPT_4("gpt-4"), + /** + * Temporary model, not recommended for use. + */ + GPT_4_0314("gpt-4-0314"), + /** + * GPT4.0 超长上下文 + */ + GPT_4_32K("gpt-4-32k"), + /** + * Temporary model, not recommended for use. + */ + GPT_4_32K_0314("gpt-4-32k-0314"), + + /** + * Temporary model, not recommended for use. + */ + GPT_4_1106_preview("gpt-4-1106-preview"); + private String name; + } + + public static boolean isBlankChar(int c) { + return Character.isWhitespace(c) || Character.isSpaceChar(c) || c == 65279 || c == 8234 + || c == 0 || c == 12644 || c == 10240 || c == 6158; + } + + public static boolean isBlankChar(char c) { + return isBlankChar((int) c); + } + + public static boolean isNotBlank(CharSequence str) { + return !isBlank(str); + } + + public static boolean isBlank(CharSequence str) { + int length; + if (str != null && (length = str.length()) != 0) { + for (int i = 0; i < length; ++i) { + if (!isBlankChar(str.charAt(i))) { + return false; + } + } + + return true; + } else { + return true; + } + } } diff --git a/api/src/test/java/com/launchableinc/openai/JsonTest.java b/api/src/test/java/com/launchableinc/openai/JsonTest.java index 58b5c5f2..e9d7da1e 100644 --- a/api/src/test/java/com/launchableinc/openai/JsonTest.java +++ b/api/src/test/java/com/launchableinc/openai/JsonTest.java @@ -1,72 +1,73 @@ -package com.theokanning.openai; +package com.launchableinc.openai; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.*; -import com.theokanning.openai.audio.TranscriptionResult; -import com.theokanning.openai.audio.TranslationResult; -import com.theokanning.openai.completion.chat.ChatCompletionRequest; -import com.theokanning.openai.completion.chat.ChatCompletionResult; -import com.theokanning.openai.edit.EditRequest; -import com.theokanning.openai.edit.EditResult; -import com.theokanning.openai.embedding.EmbeddingRequest; -import com.theokanning.openai.embedding.EmbeddingResult; -import com.theokanning.openai.engine.Engine; -import com.theokanning.openai.file.File; -import com.theokanning.openai.fine_tuning.FineTuningEvent; -import com.theokanning.openai.fine_tuning.FineTuningJob; -import com.theokanning.openai.fine_tuning.FineTuningJobRequest; -import com.theokanning.openai.finetune.FineTuneEvent; -import com.theokanning.openai.finetune.FineTuneResult; -import com.theokanning.openai.image.ImageResult; -import com.theokanning.openai.messages.Message; -import com.theokanning.openai.model.Model; -import com.theokanning.openai.moderation.ModerationRequest; -import com.theokanning.openai.moderation.ModerationResult; +import com.launchableinc.openai.audio.TranscriptionResult; +import com.launchableinc.openai.audio.TranslationResult; +import com.launchableinc.openai.completion.chat.ChatCompletionRequest; +import com.launchableinc.openai.completion.chat.ChatCompletionResult; +import com.launchableinc.openai.edit.EditRequest; +import com.launchableinc.openai.edit.EditResult; +import com.launchableinc.openai.embedding.EmbeddingRequest; +import com.launchableinc.openai.embedding.EmbeddingResult; +import com.launchableinc.openai.engine.Engine; +import com.launchableinc.openai.file.File; +import com.launchableinc.openai.fine_tuning.FineTuningEvent; +import com.launchableinc.openai.fine_tuning.FineTuningJob; +import com.launchableinc.openai.fine_tuning.FineTuningJobRequest; +import com.launchableinc.openai.finetune.FineTuneEvent; +import com.launchableinc.openai.finetune.FineTuneResult; +import com.launchableinc.openai.image.ImageResult; +import com.launchableinc.openai.messages.Message; +import com.launchableinc.openai.model.Model; +import com.launchableinc.openai.moderation.ModerationRequest; +import com.launchableinc.openai.moderation.ModerationResult; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; + import static org.junit.jupiter.api.Assertions.*; public class JsonTest { - @ParameterizedTest - @ValueSource(classes = { - ChatCompletionRequest.class, - ChatCompletionResult.class, - DeleteResult.class, - EditRequest.class, - EditResult.class, - EmbeddingRequest.class, - EmbeddingResult.class, - Engine.class, - File.class, - FineTuneEvent.class, - FineTuneResult.class, - FineTuningEvent.class, - FineTuningJob.class, - FineTuningJobRequest.class, - ImageResult.class, - TranscriptionResult.class, - TranslationResult.class, - Message.class, - Model.class, - ModerationRequest.class, - ModerationResult.class - }) - void objectMatchesJson(Class clazz) throws IOException { - ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + @ParameterizedTest + @ValueSource(classes = { + ChatCompletionRequest.class, + ChatCompletionResult.class, + DeleteResult.class, + EditRequest.class, + EditResult.class, + EmbeddingRequest.class, + EmbeddingResult.class, + Engine.class, + File.class, + FineTuneEvent.class, + FineTuneResult.class, + FineTuningEvent.class, + FineTuningJob.class, + FineTuningJobRequest.class, + ImageResult.class, + TranscriptionResult.class, + TranslationResult.class, + Message.class, + Model.class, + ModerationRequest.class, + ModerationResult.class + }) + void objectMatchesJson(Class clazz) throws IOException { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - String path = "src/test/resources/fixtures/" + clazz.getSimpleName() + ".json"; - byte[] bytes = Files.readAllBytes(Paths.get(path)); - String json = new String(bytes); + String path = "src/test/resources/fixtures/" + clazz.getSimpleName() + ".json"; + byte[] bytes = Files.readAllBytes(Paths.get(path)); + String json = new String(bytes); - String actual = mapper.writeValueAsString(mapper.readValue(json, clazz)); + String actual = mapper.writeValueAsString(mapper.readValue(json, clazz)); - // Convert to JsonNodes to avoid any json formatting differences - assertEquals(mapper.readTree(json), mapper.readTree(actual)); - } + // Convert to JsonNodes to avoid any json formatting differences + assertEquals(mapper.readTree(json), mapper.readTree(actual)); + } } diff --git a/client/src/main/java/com/launchableinc/openai/AuthenticationInterceptor.java b/client/src/main/java/com/launchableinc/openai/AuthenticationInterceptor.java index fbe9a5b4..b8169fd0 100644 --- a/client/src/main/java/com/launchableinc/openai/AuthenticationInterceptor.java +++ b/client/src/main/java/com/launchableinc/openai/AuthenticationInterceptor.java @@ -1,15 +1,16 @@ -package com.theokanning.openai; +package com.launchableinc.openai; /** * OkHttp Interceptor that adds an authorization token header - * - * @deprecated Use {@link com.theokanning.openai.client.AuthenticationInterceptor} + * + * @deprecated Use {@link com.launchableinc.openai.client.AuthenticationInterceptor} */ @Deprecated -public class AuthenticationInterceptor extends com.theokanning.openai.client.AuthenticationInterceptor { +public class AuthenticationInterceptor extends + com.launchableinc.openai.client.AuthenticationInterceptor { - AuthenticationInterceptor(String token) { - super(token); - } + AuthenticationInterceptor(String token) { + super(token); + } } diff --git a/client/src/main/java/com/launchableinc/openai/OpenAiApi.java b/client/src/main/java/com/launchableinc/openai/OpenAiApi.java index feb2f6fc..96c6ae36 100644 --- a/client/src/main/java/com/launchableinc/openai/OpenAiApi.java +++ b/client/src/main/java/com/launchableinc/openai/OpenAiApi.java @@ -1,9 +1,9 @@ -package com.theokanning.openai; +package com.launchableinc.openai; /** - * @deprecated Use {@link com.theokanning.openai.client.OpenAiApi} + * @deprecated Use {@link com.launchableinc.openai.client.OpenAiApi} */ @Deprecated -public interface OpenAiApi extends com.theokanning.openai.client.OpenAiApi { +public interface OpenAiApi extends com.launchableinc.openai.client.OpenAiApi { // For legacy compatibility only. } diff --git a/client/src/main/java/com/launchableinc/openai/client/AuthenticationInterceptor.java b/client/src/main/java/com/launchableinc/openai/client/AuthenticationInterceptor.java index d89c36f1..1ac29936 100644 --- a/client/src/main/java/com/launchableinc/openai/client/AuthenticationInterceptor.java +++ b/client/src/main/java/com/launchableinc/openai/client/AuthenticationInterceptor.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.client; +package com.launchableinc.openai.client; import java.io.IOException; @@ -11,18 +11,18 @@ */ public class AuthenticationInterceptor implements Interceptor { - private final String token; + private final String token; - protected AuthenticationInterceptor(String token) { - this.token = token; - } + protected AuthenticationInterceptor(String token) { + this.token = token; + } - @Override - public Response intercept(Chain chain) throws IOException { - Request request = chain.request() - .newBuilder() - .header("Authorization", "Bearer " + token) - .build(); - return chain.proceed(request); - } + @Override + public Response intercept(Chain chain) throws IOException { + Request request = chain.request() + .newBuilder() + .header("Authorization", "Bearer " + token) + .build(); + return chain.proceed(request); + } } diff --git a/client/src/main/java/com/launchableinc/openai/client/OpenAiApi.java b/client/src/main/java/com/launchableinc/openai/client/OpenAiApi.java index 7342e953..46987beb 100644 --- a/client/src/main/java/com/launchableinc/openai/client/OpenAiApi.java +++ b/client/src/main/java/com/launchableinc/openai/client/OpenAiApi.java @@ -1,46 +1,45 @@ -package com.theokanning.openai.client; - -import com.theokanning.openai.DeleteResult; -import com.theokanning.openai.ListSearchParameters; -import com.theokanning.openai.OpenAiResponse; -import com.theokanning.openai.assistants.*; -import com.theokanning.openai.audio.CreateSpeechRequest; -import com.theokanning.openai.audio.TranscriptionResult; -import com.theokanning.openai.audio.TranslationResult; -import com.theokanning.openai.billing.BillingUsage; -import com.theokanning.openai.billing.Subscription; -import com.theokanning.openai.completion.CompletionRequest; -import com.theokanning.openai.completion.CompletionResult; -import com.theokanning.openai.completion.chat.ChatCompletionRequest; -import com.theokanning.openai.completion.chat.ChatCompletionResult; -import com.theokanning.openai.edit.EditRequest; -import com.theokanning.openai.edit.EditResult; -import com.theokanning.openai.embedding.EmbeddingRequest; -import com.theokanning.openai.embedding.EmbeddingResult; -import com.theokanning.openai.engine.Engine; -import com.theokanning.openai.file.File; -import com.theokanning.openai.fine_tuning.FineTuningEvent; -import com.theokanning.openai.fine_tuning.FineTuningJob; -import com.theokanning.openai.fine_tuning.FineTuningJobRequest; -import com.theokanning.openai.finetune.FineTuneEvent; -import com.theokanning.openai.finetune.FineTuneRequest; -import com.theokanning.openai.finetune.FineTuneResult; -import com.theokanning.openai.image.CreateImageRequest; -import com.theokanning.openai.image.ImageResult; -import com.theokanning.openai.messages.Message; -import com.theokanning.openai.messages.MessageFile; -import com.theokanning.openai.messages.MessageRequest; -import com.theokanning.openai.messages.ModifyMessageRequest; -import com.theokanning.openai.model.Model; -import com.theokanning.openai.moderation.ModerationRequest; -import com.theokanning.openai.moderation.ModerationResult; -import com.theokanning.openai.runs.CreateThreadAndRunRequest; -import com.theokanning.openai.runs.Run; -import com.theokanning.openai.runs.RunCreateRequest; -import com.theokanning.openai.runs.RunStep; -import com.theokanning.openai.runs.SubmitToolOutputsRequest; -import com.theokanning.openai.threads.Thread; -import com.theokanning.openai.threads.ThreadRequest; +package com.launchableinc.openai.client; + +import com.launchableinc.openai.DeleteResult; +import com.launchableinc.openai.OpenAiResponse; +import com.launchableinc.openai.assistants.*; +import com.launchableinc.openai.audio.CreateSpeechRequest; +import com.launchableinc.openai.audio.TranscriptionResult; +import com.launchableinc.openai.audio.TranslationResult; +import com.launchableinc.openai.billing.BillingUsage; +import com.launchableinc.openai.billing.Subscription; +import com.launchableinc.openai.completion.CompletionRequest; +import com.launchableinc.openai.completion.CompletionResult; +import com.launchableinc.openai.completion.chat.ChatCompletionRequest; +import com.launchableinc.openai.completion.chat.ChatCompletionResult; +import com.launchableinc.openai.edit.EditRequest; +import com.launchableinc.openai.edit.EditResult; +import com.launchableinc.openai.embedding.EmbeddingRequest; +import com.launchableinc.openai.embedding.EmbeddingResult; +import com.launchableinc.openai.engine.Engine; +import com.launchableinc.openai.file.File; +import com.launchableinc.openai.fine_tuning.FineTuningEvent; +import com.launchableinc.openai.fine_tuning.FineTuningJob; +import com.launchableinc.openai.fine_tuning.FineTuningJobRequest; +import com.launchableinc.openai.finetune.FineTuneEvent; +import com.launchableinc.openai.finetune.FineTuneRequest; +import com.launchableinc.openai.finetune.FineTuneResult; +import com.launchableinc.openai.image.CreateImageRequest; +import com.launchableinc.openai.image.ImageResult; +import com.launchableinc.openai.messages.Message; +import com.launchableinc.openai.messages.MessageFile; +import com.launchableinc.openai.messages.MessageRequest; +import com.launchableinc.openai.messages.ModifyMessageRequest; +import com.launchableinc.openai.model.Model; +import com.launchableinc.openai.moderation.ModerationRequest; +import com.launchableinc.openai.moderation.ModerationResult; +import com.launchableinc.openai.runs.CreateThreadAndRunRequest; +import com.launchableinc.openai.runs.Run; +import com.launchableinc.openai.runs.RunCreateRequest; +import com.launchableinc.openai.runs.RunStep; +import com.launchableinc.openai.runs.SubmitToolOutputsRequest; +import com.launchableinc.openai.threads.Thread; +import com.launchableinc.openai.threads.ThreadRequest; import io.reactivex.Single; import okhttp3.MultipartBody; import okhttp3.RequestBody; @@ -53,272 +52,293 @@ public interface OpenAiApi { - @GET("v1/models") - Single> listModels(); + @GET("v1/models") + Single> listModels(); - @GET("/v1/models/{model_id}") - Single getModel(@Path("model_id") String modelId); + @GET("/v1/models/{model_id}") + Single getModel(@Path("model_id") String modelId); - @POST("/v1/completions") - Single createCompletion(@Body CompletionRequest request); + @POST("/v1/completions") + Single createCompletion(@Body CompletionRequest request); - @Streaming - @POST("/v1/completions") - Call createCompletionStream(@Body CompletionRequest request); + @Streaming + @POST("/v1/completions") + Call createCompletionStream(@Body CompletionRequest request); - @POST("/v1/chat/completions") - Single createChatCompletion(@Body ChatCompletionRequest request); + @POST("/v1/chat/completions") + Single createChatCompletion(@Body ChatCompletionRequest request); - @Streaming - @POST("/v1/chat/completions") - Call createChatCompletionStream(@Body ChatCompletionRequest request); + @Streaming + @POST("/v1/chat/completions") + Call createChatCompletionStream(@Body ChatCompletionRequest request); - @Deprecated - @POST("/v1/engines/{engine_id}/completions") - Single createCompletion(@Path("engine_id") String engineId, @Body CompletionRequest request); + @Deprecated + @POST("/v1/engines/{engine_id}/completions") + Single createCompletion(@Path("engine_id") String engineId, + @Body CompletionRequest request); - @POST("/v1/edits") - Single createEdit(@Body EditRequest request); + @POST("/v1/edits") + Single createEdit(@Body EditRequest request); - @Deprecated - @POST("/v1/engines/{engine_id}/edits") - Single createEdit(@Path("engine_id") String engineId, @Body EditRequest request); + @Deprecated + @POST("/v1/engines/{engine_id}/edits") + Single createEdit(@Path("engine_id") String engineId, @Body EditRequest request); - @POST("/v1/embeddings") - Single createEmbeddings(@Body EmbeddingRequest request); + @POST("/v1/embeddings") + Single createEmbeddings(@Body EmbeddingRequest request); - @Deprecated - @POST("/v1/engines/{engine_id}/embeddings") - Single createEmbeddings(@Path("engine_id") String engineId, @Body EmbeddingRequest request); + @Deprecated + @POST("/v1/engines/{engine_id}/embeddings") + Single createEmbeddings(@Path("engine_id") String engineId, + @Body EmbeddingRequest request); - @GET("/v1/files") - Single> listFiles(); + @GET("/v1/files") + Single> listFiles(); - @Multipart - @POST("/v1/files") - Single uploadFile(@Part("purpose") RequestBody purpose, @Part MultipartBody.Part file); + @Multipart + @POST("/v1/files") + Single uploadFile(@Part("purpose") RequestBody purpose, @Part MultipartBody.Part file); - @DELETE("/v1/files/{file_id}") - Single deleteFile(@Path("file_id") String fileId); + @DELETE("/v1/files/{file_id}") + Single deleteFile(@Path("file_id") String fileId); - @GET("/v1/files/{file_id}") - Single retrieveFile(@Path("file_id") String fileId); + @GET("/v1/files/{file_id}") + Single retrieveFile(@Path("file_id") String fileId); - @Streaming - @GET("/v1/files/{file_id}/content") - Single retrieveFileContent(@Path("file_id") String fileId); + @Streaming + @GET("/v1/files/{file_id}/content") + Single retrieveFileContent(@Path("file_id") String fileId); - @POST("/v1/fine_tuning/jobs") - Single createFineTuningJob(@Body FineTuningJobRequest request); + @POST("/v1/fine_tuning/jobs") + Single createFineTuningJob(@Body FineTuningJobRequest request); - @GET("/v1/fine_tuning/jobs") - Single> listFineTuningJobs(); + @GET("/v1/fine_tuning/jobs") + Single> listFineTuningJobs(); - @GET("/v1/fine_tuning/jobs/{fine_tuning_job_id}") - Single retrieveFineTuningJob(@Path("fine_tuning_job_id") String fineTuningJobId); + @GET("/v1/fine_tuning/jobs/{fine_tuning_job_id}") + Single retrieveFineTuningJob(@Path("fine_tuning_job_id") String fineTuningJobId); - @POST("/v1/fine_tuning/jobs/{fine_tuning_job_id}/cancel") - Single cancelFineTuningJob(@Path("fine_tuning_job_id") String fineTuningJobId); + @POST("/v1/fine_tuning/jobs/{fine_tuning_job_id}/cancel") + Single cancelFineTuningJob(@Path("fine_tuning_job_id") String fineTuningJobId); - @GET("/v1/fine_tuning/jobs/{fine_tuning_job_id}/events") - Single> listFineTuningJobEvents(@Path("fine_tuning_job_id") String fineTuningJobId); + @GET("/v1/fine_tuning/jobs/{fine_tuning_job_id}/events") + Single> listFineTuningJobEvents( + @Path("fine_tuning_job_id") String fineTuningJobId); - @Deprecated - @POST("/v1/fine-tunes") - Single createFineTune(@Body FineTuneRequest request); + @Deprecated + @POST("/v1/fine-tunes") + Single createFineTune(@Body FineTuneRequest request); - @POST("/v1/completions") - Single createFineTuneCompletion(@Body CompletionRequest request); + @POST("/v1/completions") + Single createFineTuneCompletion(@Body CompletionRequest request); - @Deprecated - @GET("/v1/fine-tunes") - Single> listFineTunes(); + @Deprecated + @GET("/v1/fine-tunes") + Single> listFineTunes(); - @Deprecated - @GET("/v1/fine-tunes/{fine_tune_id}") - Single retrieveFineTune(@Path("fine_tune_id") String fineTuneId); + @Deprecated + @GET("/v1/fine-tunes/{fine_tune_id}") + Single retrieveFineTune(@Path("fine_tune_id") String fineTuneId); - @Deprecated - @POST("/v1/fine-tunes/{fine_tune_id}/cancel") - Single cancelFineTune(@Path("fine_tune_id") String fineTuneId); + @Deprecated + @POST("/v1/fine-tunes/{fine_tune_id}/cancel") + Single cancelFineTune(@Path("fine_tune_id") String fineTuneId); - @Deprecated - @GET("/v1/fine-tunes/{fine_tune_id}/events") - Single> listFineTuneEvents(@Path("fine_tune_id") String fineTuneId); + @Deprecated + @GET("/v1/fine-tunes/{fine_tune_id}/events") + Single> listFineTuneEvents(@Path("fine_tune_id") String fineTuneId); - @DELETE("/v1/models/{fine_tune_id}") - Single deleteFineTune(@Path("fine_tune_id") String fineTuneId); + @DELETE("/v1/models/{fine_tune_id}") + Single deleteFineTune(@Path("fine_tune_id") String fineTuneId); - @POST("/v1/images/generations") - Single createImage(@Body CreateImageRequest request); + @POST("/v1/images/generations") + Single createImage(@Body CreateImageRequest request); - @POST("/v1/images/edits") - Single createImageEdit(@Body RequestBody requestBody); + @POST("/v1/images/edits") + Single createImageEdit(@Body RequestBody requestBody); - @POST("/v1/images/variations") - Single createImageVariation(@Body RequestBody requestBody); + @POST("/v1/images/variations") + Single createImageVariation(@Body RequestBody requestBody); - @POST("/v1/audio/transcriptions") - Single createTranscription(@Body RequestBody requestBody); + @POST("/v1/audio/transcriptions") + Single createTranscription(@Body RequestBody requestBody); - @POST("/v1/audio/translations") - Single createTranslation(@Body RequestBody requestBody); + @POST("/v1/audio/translations") + Single createTranslation(@Body RequestBody requestBody); - @POST("/v1/audio/speech") - Single createSpeech(@Body CreateSpeechRequest requestBody); + @POST("/v1/audio/speech") + Single createSpeech(@Body CreateSpeechRequest requestBody); - @POST("/v1/moderations") - Single createModeration(@Body ModerationRequest request); + @POST("/v1/moderations") + Single createModeration(@Body ModerationRequest request); - @Deprecated - @GET("v1/engines") - Single> getEngines(); + @Deprecated + @GET("v1/engines") + Single> getEngines(); - @Deprecated - @GET("/v1/engines/{engine_id}") - Single getEngine(@Path("engine_id") String engineId); + @Deprecated + @GET("/v1/engines/{engine_id}") + Single getEngine(@Path("engine_id") String engineId); - /** - * Account information inquiry: It contains total amount (in US dollars) and other information. - * - * @return - */ - @Deprecated - @GET("v1/dashboard/billing/subscription") - Single subscription(); - - /** - * Account call interface consumption amount inquiry. - * totalUsage = Total amount used by the account (in US cents). - * - * @param starDate - * @param endDate - * @return Consumption amount information. - */ - @Deprecated - @GET("v1/dashboard/billing/usage") - Single billingUsage(@Query("start_date") LocalDate starDate, @Query("end_date") LocalDate endDate); - - @Headers({"OpenAI-Beta: assistants=v1"}) - @POST("/v1/assistants") - Single createAssistant(@Body AssistantRequest request); - - @Headers({"OpenAI-Beta: assistants=v1"}) - @GET("/v1/assistants/{assistant_id}") - Single retrieveAssistant(@Path("assistant_id") String assistantId); - - @Headers({"OpenAI-Beta: assistants=v1"}) - @POST("/v1/assistants/{assistant_id}") - Single modifyAssistant(@Path("assistant_id") String assistantId, @Body ModifyAssistantRequest request); - - @Headers({"OpenAI-Beta: assistants=v1"}) - @DELETE("/v1/assistants/{assistant_id}") - Single deleteAssistant(@Path("assistant_id") String assistantId); - - @Headers({"OpenAI-Beta: assistants=v1"}) - @GET("/v1/assistants") - Single> listAssistants(@QueryMap Map filterRequest); - - @Headers({"OpenAI-Beta: assistants=v1"}) - @POST("/v1/assistants/{assistant_id}/files") - Single createAssistantFile(@Path("assistant_id") String assistantId, @Body AssistantFileRequest fileRequest); - - @Headers({"OpenAI-Beta: assistants=v1"}) - @GET("/v1/assistants/{assistant_id}/files/{file_id}") - Single retrieveAssistantFile(@Path("assistant_id") String assistantId, @Path("file_id") String fileId); - - @Headers({"OpenAI-Beta: assistants=v1"}) - @DELETE("/v1/assistants/{assistant_id}/files/{file_id}") - Single deleteAssistantFile(@Path("assistant_id") String assistantId, @Path("file_id") String fileId); - - @Headers({"OpenAI-Beta: assistants=v1"}) - @GET("/v1/assistants/{assistant_id}/files") - Single> listAssistantFiles(@Path("assistant_id") String assistantId, @QueryMap Map filterRequest); - - @Headers({"OpenAI-Beta: assistants=v1"}) - @POST("/v1/threads") - Single createThread(@Body ThreadRequest request); - - @Headers({"OpenAI-Beta: assistants=v1"}) - @GET("/v1/threads/{thread_id}") - Single retrieveThread(@Path("thread_id") String threadId); - - @Headers({"OpenAI-Beta: assistants=v1"}) - @POST("/v1/threads/{thread_id}") - Single modifyThread(@Path("thread_id") String threadId, @Body ThreadRequest request); - - @Headers({"OpenAI-Beta: assistants=v1"}) - @DELETE("/v1/threads/{thread_id}") - Single deleteThread(@Path("thread_id") String threadId); - - - @Headers({"OpenAI-Beta: assistants=v1"}) - @POST("/v1/threads/{thread_id}/messages") - Single createMessage(@Path("thread_id") String threadId, @Body MessageRequest request); - - @Headers({"OpenAI-Beta: assistants=v1"}) - @GET("/v1/threads/{thread_id}/messages/{message_id}") - Single retrieveMessage(@Path("thread_id") String threadId, @Path("message_id") String messageId); - - @Headers({"OpenAI-Beta: assistants=v1"}) - @POST("/v1/threads/{thread_id}/messages/{message_id}") - Single modifyMessage(@Path("thread_id") String threadId, @Path("message_id") String messageId, @Body ModifyMessageRequest request); - - @Headers({"OpenAI-Beta: assistants=v1"}) - @GET("/v1/threads/{thread_id}/messages") - Single> listMessages(@Path("thread_id") String threadId); - - @Headers({"OpenAI-Beta: assistants=v1"}) - @GET("/v1/threads/{thread_id}/messages") - Single> listMessages(@Path("thread_id") String threadId, @QueryMap Map filterRequest); - - @Headers({"OpenAI-Beta: assistants=v1"}) - @GET("/v1/threads/{thread_id}/messages/{message_id}/files/{file_id}") - Single retrieveMessageFile(@Path("thread_id") String threadId, @Path("message_id") String messageId, @Path("file_id") String fileId); - - @Headers({"OpenAI-Beta: assistants=v1"}) - @GET("/v1/threads/{thread_id}/messages/{message_id}/files") - Single> listMessageFiles(@Path("thread_id") String threadId, @Path("message_id") String messageId); - - @Headers({"OpenAI-Beta: assistants=v1"}) - @GET("/v1/threads/{thread_id}/messages/{message_id}/files") - Single> listMessageFiles(@Path("thread_id") String threadId, @Path("message_id") String messageId, @QueryMap Map filterRequest); - - @Headers("OpenAI-Beta: assistants=v1") - @POST("/v1/threads/{thread_id}/runs") - Single createRun(@Path("thread_id") String threadId, @Body RunCreateRequest runCreateRequest); - - @Headers("OpenAI-Beta: assistants=v1") - @GET("/v1/threads/{thread_id}/runs/{run_id}") - Single retrieveRun(@Path("thread_id") String threadId, @Path("run_id") String runId); - - @Headers("OpenAI-Beta: assistants=v1") - @POST("/v1/threads/{thread_id}/runs/{run_id}") - Single modifyRun(@Path("thread_id") String threadId, @Path("run_id") String runId, @Body Map metadata); - - @Headers("OpenAI-Beta: assistants=v1") - @GET("/v1/threads/{thread_id}/runs") - Single> listRuns(@Path("thread_id") String threadId, @QueryMap Map listSearchParameters); - - - @Headers("OpenAI-Beta: assistants=v1") - @POST("/v1/threads/{thread_id}/runs/{run_id}/submit_tool_outputs") - Single submitToolOutputs(@Path("thread_id") String threadId, @Path("run_id") String runId, @Body SubmitToolOutputsRequest submitToolOutputsRequest); - - - @Headers("OpenAI-Beta: assistants=v1") - @POST("/v1/threads/{thread_id}/runs/{run_id}/cancel") - Single cancelRun(@Path("thread_id") String threadId, @Path("run_id") String runId); - - @Headers("OpenAI-Beta: assistants=v1") - @POST("/v1/threads/runs") - Single createThreadAndRun(@Body CreateThreadAndRunRequest createThreadAndRunRequest); - - @Headers("OpenAI-Beta: assistants=v1") - @GET("/v1/threads/{thread_id}/runs/{run_id}/steps/{step_id}") - Single retrieveRunStep(@Path("thread_id") String threadId, @Path("run_id") String runId, @Path("step_id") String stepId); - - @Headers("OpenAI-Beta: assistants=v1") - @GET("/v1/threads/{thread_id}/runs/{run_id}/steps") - Single> listRunSteps(@Path("thread_id") String threadId, @Path("run_id") String runId, @QueryMap Map listSearchParameters); + /** + * Account information inquiry: It contains total amount (in US dollars) and other information. + * + * @return + */ + @Deprecated + @GET("v1/dashboard/billing/subscription") + Single subscription(); + + /** + * Account call interface consumption amount inquiry. totalUsage = Total amount used by the + * account (in US cents). + * + * @param starDate + * @param endDate + * @return Consumption amount information. + */ + @Deprecated + @GET("v1/dashboard/billing/usage") + Single billingUsage(@Query("start_date") LocalDate starDate, + @Query("end_date") LocalDate endDate); + + @Headers({"OpenAI-Beta: assistants=v1"}) + @POST("/v1/assistants") + Single createAssistant(@Body AssistantRequest request); + + @Headers({"OpenAI-Beta: assistants=v1"}) + @GET("/v1/assistants/{assistant_id}") + Single retrieveAssistant(@Path("assistant_id") String assistantId); + + @Headers({"OpenAI-Beta: assistants=v1"}) + @POST("/v1/assistants/{assistant_id}") + Single modifyAssistant(@Path("assistant_id") String assistantId, + @Body ModifyAssistantRequest request); + + @Headers({"OpenAI-Beta: assistants=v1"}) + @DELETE("/v1/assistants/{assistant_id}") + Single deleteAssistant(@Path("assistant_id") String assistantId); + + @Headers({"OpenAI-Beta: assistants=v1"}) + @GET("/v1/assistants") + Single> listAssistants(@QueryMap Map filterRequest); + + @Headers({"OpenAI-Beta: assistants=v1"}) + @POST("/v1/assistants/{assistant_id}/files") + Single createAssistantFile(@Path("assistant_id") String assistantId, + @Body AssistantFileRequest fileRequest); + + @Headers({"OpenAI-Beta: assistants=v1"}) + @GET("/v1/assistants/{assistant_id}/files/{file_id}") + Single retrieveAssistantFile(@Path("assistant_id") String assistantId, + @Path("file_id") String fileId); + + @Headers({"OpenAI-Beta: assistants=v1"}) + @DELETE("/v1/assistants/{assistant_id}/files/{file_id}") + Single deleteAssistantFile(@Path("assistant_id") String assistantId, + @Path("file_id") String fileId); + + @Headers({"OpenAI-Beta: assistants=v1"}) + @GET("/v1/assistants/{assistant_id}/files") + Single> listAssistantFiles(@Path("assistant_id") String assistantId, + @QueryMap Map filterRequest); + + @Headers({"OpenAI-Beta: assistants=v1"}) + @POST("/v1/threads") + Single createThread(@Body ThreadRequest request); + + @Headers({"OpenAI-Beta: assistants=v1"}) + @GET("/v1/threads/{thread_id}") + Single retrieveThread(@Path("thread_id") String threadId); + + @Headers({"OpenAI-Beta: assistants=v1"}) + @POST("/v1/threads/{thread_id}") + Single modifyThread(@Path("thread_id") String threadId, @Body ThreadRequest request); + + @Headers({"OpenAI-Beta: assistants=v1"}) + @DELETE("/v1/threads/{thread_id}") + Single deleteThread(@Path("thread_id") String threadId); + + + @Headers({"OpenAI-Beta: assistants=v1"}) + @POST("/v1/threads/{thread_id}/messages") + Single createMessage(@Path("thread_id") String threadId, @Body MessageRequest request); + + @Headers({"OpenAI-Beta: assistants=v1"}) + @GET("/v1/threads/{thread_id}/messages/{message_id}") + Single retrieveMessage(@Path("thread_id") String threadId, + @Path("message_id") String messageId); + + @Headers({"OpenAI-Beta: assistants=v1"}) + @POST("/v1/threads/{thread_id}/messages/{message_id}") + Single modifyMessage(@Path("thread_id") String threadId, + @Path("message_id") String messageId, @Body ModifyMessageRequest request); + + @Headers({"OpenAI-Beta: assistants=v1"}) + @GET("/v1/threads/{thread_id}/messages") + Single> listMessages(@Path("thread_id") String threadId); + + @Headers({"OpenAI-Beta: assistants=v1"}) + @GET("/v1/threads/{thread_id}/messages") + Single> listMessages(@Path("thread_id") String threadId, + @QueryMap Map filterRequest); + + @Headers({"OpenAI-Beta: assistants=v1"}) + @GET("/v1/threads/{thread_id}/messages/{message_id}/files/{file_id}") + Single retrieveMessageFile(@Path("thread_id") String threadId, + @Path("message_id") String messageId, @Path("file_id") String fileId); + + @Headers({"OpenAI-Beta: assistants=v1"}) + @GET("/v1/threads/{thread_id}/messages/{message_id}/files") + Single> listMessageFiles(@Path("thread_id") String threadId, + @Path("message_id") String messageId); + + @Headers({"OpenAI-Beta: assistants=v1"}) + @GET("/v1/threads/{thread_id}/messages/{message_id}/files") + Single> listMessageFiles(@Path("thread_id") String threadId, + @Path("message_id") String messageId, @QueryMap Map filterRequest); + + @Headers("OpenAI-Beta: assistants=v1") + @POST("/v1/threads/{thread_id}/runs") + Single createRun(@Path("thread_id") String threadId, + @Body RunCreateRequest runCreateRequest); + + @Headers("OpenAI-Beta: assistants=v1") + @GET("/v1/threads/{thread_id}/runs/{run_id}") + Single retrieveRun(@Path("thread_id") String threadId, @Path("run_id") String runId); + + @Headers("OpenAI-Beta: assistants=v1") + @POST("/v1/threads/{thread_id}/runs/{run_id}") + Single modifyRun(@Path("thread_id") String threadId, @Path("run_id") String runId, + @Body Map metadata); + + @Headers("OpenAI-Beta: assistants=v1") + @GET("/v1/threads/{thread_id}/runs") + Single> listRuns(@Path("thread_id") String threadId, + @QueryMap Map listSearchParameters); + + + @Headers("OpenAI-Beta: assistants=v1") + @POST("/v1/threads/{thread_id}/runs/{run_id}/submit_tool_outputs") + Single submitToolOutputs(@Path("thread_id") String threadId, @Path("run_id") String runId, + @Body SubmitToolOutputsRequest submitToolOutputsRequest); + + + @Headers("OpenAI-Beta: assistants=v1") + @POST("/v1/threads/{thread_id}/runs/{run_id}/cancel") + Single cancelRun(@Path("thread_id") String threadId, @Path("run_id") String runId); + + @Headers("OpenAI-Beta: assistants=v1") + @POST("/v1/threads/runs") + Single createThreadAndRun(@Body CreateThreadAndRunRequest createThreadAndRunRequest); + + @Headers("OpenAI-Beta: assistants=v1") + @GET("/v1/threads/{thread_id}/runs/{run_id}/steps/{step_id}") + Single retrieveRunStep(@Path("thread_id") String threadId, @Path("run_id") String runId, + @Path("step_id") String stepId); + + @Headers("OpenAI-Beta: assistants=v1") + @GET("/v1/threads/{thread_id}/runs/{run_id}/steps") + Single> listRunSteps(@Path("thread_id") String threadId, + @Path("run_id") String runId, @QueryMap Map listSearchParameters); } diff --git a/example/src/main/java/example/OpenAiApiDynamicFunctionExample.java b/example/src/main/java/example/OpenAiApiDynamicFunctionExample.java index 75f9b8e2..a6c552d5 100644 --- a/example/src/main/java/example/OpenAiApiDynamicFunctionExample.java +++ b/example/src/main/java/example/OpenAiApiDynamicFunctionExample.java @@ -3,88 +3,91 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; -import com.theokanning.openai.completion.chat.*; -import com.theokanning.openai.service.OpenAiService; +import com.launchableinc.openai.completion.chat.*; +import com.launchableinc.openai.service.OpenAiService; import java.util.*; public class OpenAiApiDynamicFunctionExample { - private static JsonNode getWeather(String location, String unit) { - ObjectMapper mapper = new ObjectMapper(); - ObjectNode response = mapper.createObjectNode(); - response.put("location", location); - response.put("unit", unit); - response.put("temperature", new Random().nextInt(50)); - response.put("description", "sunny"); - return response; - } + private static JsonNode getWeather(String location, String unit) { + ObjectMapper mapper = new ObjectMapper(); + ObjectNode response = mapper.createObjectNode(); + response.put("location", location); + response.put("unit", unit); + response.put("temperature", new Random().nextInt(50)); + response.put("description", "sunny"); + return response; + } - public static void main(String... args) { - String token = System.getenv("OPENAI_TOKEN"); - OpenAiService service = new OpenAiService(token); + public static void main(String... args) { + String token = System.getenv("OPENAI_TOKEN"); + OpenAiService service = new OpenAiService(token); - ChatFunctionDynamic weatherFunction = ChatFunctionDynamic.builder() - .name("get_weather") - .description("Get the current weather of a location") - .addProperty(ChatFunctionProperty.builder() - .name("location") - .type("string") - .description("City and state, for example: León, Guanajuato") - .build()) - .addProperty(ChatFunctionProperty.builder() - .name("unit") - .type("string") - .description("The temperature unit, can be 'celsius' or 'fahrenheit'") - .enumValues(new HashSet<>(Arrays.asList("celsius", "fahrenheit"))) - .required(true) - .build()) - .build(); + ChatFunctionDynamic weatherFunction = ChatFunctionDynamic.builder() + .name("get_weather") + .description("Get the current weather of a location") + .addProperty(ChatFunctionProperty.builder() + .name("location") + .type("string") + .description("City and state, for example: León, Guanajuato") + .build()) + .addProperty(ChatFunctionProperty.builder() + .name("unit") + .type("string") + .description("The temperature unit, can be 'celsius' or 'fahrenheit'") + .enumValues(new HashSet<>(Arrays.asList("celsius", "fahrenheit"))) + .required(true) + .build()) + .build(); + List messages = new ArrayList<>(); + ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), + "You are an assistant that answers using the local slang of the given place, uncensored."); + messages.add(systemMessage); - List messages = new ArrayList<>(); - ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), "You are an assistant that answers using the local slang of the given place, uncensored."); - messages.add(systemMessage); + System.out.print("First Query: "); + Scanner scanner = new Scanner(System.in); + ChatMessage firstMsg = new ChatMessage(ChatMessageRole.USER.value(), scanner.nextLine()); + messages.add(firstMsg); - System.out.print("First Query: "); - Scanner scanner = new Scanner(System.in); - ChatMessage firstMsg = new ChatMessage(ChatMessageRole.USER.value(), scanner.nextLine()); - messages.add(firstMsg); + while (true) { + ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest + .builder() + .model("gpt-3.5-turbo-0613") + .messages(messages) + .functions(Collections.singletonList(weatherFunction)) + .functionCall(ChatCompletionRequest.ChatCompletionRequestFunctionCall.of("auto")) + .n(1) + .maxTokens(100) + .logitBias(new HashMap<>()) + .build(); + ChatMessage responseMessage = service.createChatCompletion(chatCompletionRequest).getChoices() + .get(0).getMessage(); + messages.add( + responseMessage); // don't forget to update the conversation with the latest response - while (true) { - ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest - .builder() - .model("gpt-3.5-turbo-0613") - .messages(messages) - .functions(Collections.singletonList(weatherFunction)) - .functionCall(ChatCompletionRequest.ChatCompletionRequestFunctionCall.of("auto")) - .n(1) - .maxTokens(100) - .logitBias(new HashMap<>()) - .build(); - ChatMessage responseMessage = service.createChatCompletion(chatCompletionRequest).getChoices().get(0).getMessage(); - messages.add(responseMessage); // don't forget to update the conversation with the latest response + ChatFunctionCall functionCall = responseMessage.getFunctionCall(); + if (functionCall != null) { + if (functionCall.getName().equals("get_weather")) { + String location = functionCall.getArguments().get("location").asText(); + String unit = functionCall.getArguments().get("unit").asText(); + JsonNode weather = getWeather(location, unit); + ChatMessage weatherMessage = new ChatMessage(ChatMessageRole.FUNCTION.value(), + weather.toString(), "get_weather"); + messages.add(weatherMessage); + continue; + } + } - ChatFunctionCall functionCall = responseMessage.getFunctionCall(); - if (functionCall != null) { - if (functionCall.getName().equals("get_weather")) { - String location = functionCall.getArguments().get("location").asText(); - String unit = functionCall.getArguments().get("unit").asText(); - JsonNode weather = getWeather(location, unit); - ChatMessage weatherMessage = new ChatMessage(ChatMessageRole.FUNCTION.value(), weather.toString(), "get_weather"); - messages.add(weatherMessage); - continue; - } - } - - System.out.println("Response: " + responseMessage.getContent()); - System.out.print("Next Query: "); - String nextLine = scanner.nextLine(); - if (nextLine.equalsIgnoreCase("exit")) { - System.exit(0); - } - messages.add(new ChatMessage(ChatMessageRole.USER.value(), nextLine)); - } - } + System.out.println("Response: " + responseMessage.getContent()); + System.out.print("Next Query: "); + String nextLine = scanner.nextLine(); + if (nextLine.equalsIgnoreCase("exit")) { + System.exit(0); + } + messages.add(new ChatMessage(ChatMessageRole.USER.value(), nextLine)); + } + } } diff --git a/example/src/main/java/example/OpenAiApiExample.java b/example/src/main/java/example/OpenAiApiExample.java index 52ae1ccf..1774bed5 100644 --- a/example/src/main/java/example/OpenAiApiExample.java +++ b/example/src/main/java/example/OpenAiApiExample.java @@ -1,11 +1,11 @@ package example; -import com.theokanning.openai.completion.chat.ChatCompletionRequest; -import com.theokanning.openai.completion.chat.ChatMessage; -import com.theokanning.openai.completion.chat.ChatMessageRole; -import com.theokanning.openai.service.OpenAiService; -import com.theokanning.openai.completion.CompletionRequest; -import com.theokanning.openai.image.CreateImageRequest; +import com.launchableinc.openai.completion.chat.ChatCompletionRequest; +import com.launchableinc.openai.completion.chat.ChatMessage; +import com.launchableinc.openai.completion.chat.ChatMessageRole; +import com.launchableinc.openai.service.OpenAiService; +import com.launchableinc.openai.completion.CompletionRequest; +import com.launchableinc.openai.image.CreateImageRequest; import java.time.Duration; import java.util.ArrayList; @@ -13,45 +13,47 @@ import java.util.List; class OpenAiApiExample { - public static void main(String... args) { - String token = System.getenv("OPENAI_TOKEN"); - OpenAiService service = new OpenAiService(token, Duration.ofSeconds(30)); - - System.out.println("\nCreating completion..."); - CompletionRequest completionRequest = CompletionRequest.builder() - .model("babbage-002") - .prompt("Somebody once told me the world is gonna roll me") - .echo(true) - .user("testing") - .n(3) - .build(); - service.createCompletion(completionRequest).getChoices().forEach(System.out::println); - - System.out.println("\nCreating Image..."); - CreateImageRequest request = CreateImageRequest.builder() - .prompt("A cow breakdancing with a turtle") - .build(); - - System.out.println("\nImage is located at:"); - System.out.println(service.createImage(request).getData().get(0).getUrl()); - - System.out.println("Streaming chat completion..."); - final List messages = new ArrayList<>(); - final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), "You are a dog and will speak as such."); - messages.add(systemMessage); - ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest - .builder() - .model("gpt-3.5-turbo") - .messages(messages) - .n(1) - .maxTokens(50) - .logitBias(new HashMap<>()) - .build(); - - service.streamChatCompletion(chatCompletionRequest) - .doOnError(Throwable::printStackTrace) - .blockingForEach(System.out::println); - - service.shutdownExecutor(); - } + + public static void main(String... args) { + String token = System.getenv("OPENAI_TOKEN"); + OpenAiService service = new OpenAiService(token, Duration.ofSeconds(30)); + + System.out.println("\nCreating completion..."); + CompletionRequest completionRequest = CompletionRequest.builder() + .model("babbage-002") + .prompt("Somebody once told me the world is gonna roll me") + .echo(true) + .user("testing") + .n(3) + .build(); + service.createCompletion(completionRequest).getChoices().forEach(System.out::println); + + System.out.println("\nCreating Image..."); + CreateImageRequest request = CreateImageRequest.builder() + .prompt("A cow breakdancing with a turtle") + .build(); + + System.out.println("\nImage is located at:"); + System.out.println(service.createImage(request).getData().get(0).getUrl()); + + System.out.println("Streaming chat completion..."); + final List messages = new ArrayList<>(); + final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), + "You are a dog and will speak as such."); + messages.add(systemMessage); + ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest + .builder() + .model("gpt-3.5-turbo") + .messages(messages) + .n(1) + .maxTokens(50) + .logitBias(new HashMap<>()) + .build(); + + service.streamChatCompletion(chatCompletionRequest) + .doOnError(Throwable::printStackTrace) + .blockingForEach(System.out::println); + + service.shutdownExecutor(); + } } diff --git a/example/src/main/java/example/OpenAiApiFunctionsExample.java b/example/src/main/java/example/OpenAiApiFunctionsExample.java index 954b9104..6bd21835 100644 --- a/example/src/main/java/example/OpenAiApiFunctionsExample.java +++ b/example/src/main/java/example/OpenAiApiFunctionsExample.java @@ -2,108 +2,116 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyDescription; -import com.theokanning.openai.completion.chat.*; -import com.theokanning.openai.completion.chat.ChatCompletionRequest.ChatCompletionRequestFunctionCall; -import com.theokanning.openai.service.FunctionExecutor; -import com.theokanning.openai.service.OpenAiService; +import com.launchableinc.openai.completion.chat.*; +import com.launchableinc.openai.completion.chat.ChatCompletionRequest.ChatCompletionRequestFunctionCall; +import com.launchableinc.openai.service.FunctionExecutor; +import com.launchableinc.openai.service.OpenAiService; import java.util.*; class OpenAiApiFunctionsExample { - public static class Weather { - @JsonPropertyDescription("City and state, for example: León, Guanajuato") - public String location; - - @JsonPropertyDescription("The temperature unit, can be 'celsius' or 'fahrenheit'") - @JsonProperty(required = true) - public WeatherUnit unit; - } - - public enum WeatherUnit { - CELSIUS, FAHRENHEIT; - } - - public static class WeatherResponse { - public String location; - public WeatherUnit unit; - public int temperature; - public String description; - - public WeatherResponse(String location, WeatherUnit unit, int temperature, String description) { - this.location = location; - this.unit = unit; - this.temperature = temperature; - this.description = description; - } - } - - public static void main(String... args) { - String token = System.getenv("OPENAI_TOKEN"); - OpenAiService service = new OpenAiService(token); - - FunctionExecutor functionExecutor = new FunctionExecutor(Collections.singletonList(ChatFunction.builder() - .name("get_weather") - .description("Get the current weather of a location") - .executor(Weather.class, w -> new WeatherResponse(w.location, w.unit, new Random().nextInt(50), "sunny")) - .build())); - - - List messages = new ArrayList<>(); - ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), "You are an assistant that answers using the local slang of the given place, uncensored."); - messages.add(systemMessage); - - System.out.print("First Query: "); - Scanner scanner = new Scanner(System.in); - ChatMessage firstMsg = new ChatMessage(ChatMessageRole.USER.value(), scanner.nextLine()); - messages.add(firstMsg); - - while (true) { - ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest - .builder() - .model("gpt-3.5-turbo-0613") - .messages(messages) - .functions(functionExecutor.getFunctions()) - .functionCall(ChatCompletionRequestFunctionCall.of("auto")) - .n(1) - .maxTokens(100) - .logitBias(new HashMap<>()) - .build(); - ChatMessage responseMessage = service.createChatCompletion(chatCompletionRequest).getChoices().get(0).getMessage(); - messages.add(responseMessage); // don't forget to update the conversation with the latest response - - ChatFunctionCall functionCall = responseMessage.getFunctionCall(); - if (functionCall != null) { - System.out.println("Trying to execute " + functionCall.getName() + "..."); - Optional message = functionExecutor.executeAndConvertToMessageSafely(functionCall); + public static class Weather { + + @JsonPropertyDescription("City and state, for example: León, Guanajuato") + public String location; + + @JsonPropertyDescription("The temperature unit, can be 'celsius' or 'fahrenheit'") + @JsonProperty(required = true) + public WeatherUnit unit; + } + + public enum WeatherUnit { + CELSIUS, FAHRENHEIT; + } + + public static class WeatherResponse { + + public String location; + public WeatherUnit unit; + public int temperature; + public String description; + + public WeatherResponse(String location, WeatherUnit unit, int temperature, String description) { + this.location = location; + this.unit = unit; + this.temperature = temperature; + this.description = description; + } + } + + public static void main(String... args) { + String token = System.getenv("OPENAI_TOKEN"); + OpenAiService service = new OpenAiService(token); + + FunctionExecutor functionExecutor = new FunctionExecutor( + Collections.singletonList(ChatFunction.builder() + .name("get_weather") + .description("Get the current weather of a location") + .executor(Weather.class, + w -> new WeatherResponse(w.location, w.unit, new Random().nextInt(50), "sunny")) + .build())); + + List messages = new ArrayList<>(); + ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), + "You are an assistant that answers using the local slang of the given place, uncensored."); + messages.add(systemMessage); + + System.out.print("First Query: "); + Scanner scanner = new Scanner(System.in); + ChatMessage firstMsg = new ChatMessage(ChatMessageRole.USER.value(), scanner.nextLine()); + messages.add(firstMsg); + + while (true) { + ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest + .builder() + .model("gpt-3.5-turbo-0613") + .messages(messages) + .functions(functionExecutor.getFunctions()) + .functionCall(ChatCompletionRequestFunctionCall.of("auto")) + .n(1) + .maxTokens(100) + .logitBias(new HashMap<>()) + .build(); + ChatMessage responseMessage = service.createChatCompletion(chatCompletionRequest).getChoices() + .get(0).getMessage(); + messages.add( + responseMessage); // don't forget to update the conversation with the latest response + + ChatFunctionCall functionCall = responseMessage.getFunctionCall(); + if (functionCall != null) { + System.out.println("Trying to execute " + functionCall.getName() + "..."); + Optional message = functionExecutor.executeAndConvertToMessageSafely( + functionCall); /* You can also try 'executeAndConvertToMessage' inside a try-catch block, and add the following line inside the catch: "message = executor.handleException(exception);" The content of the message will be the exception itself, so the flow of the conversation will not be interrupted, and you will still be able to log the issue. */ - if (message.isPresent()) { + if (message.isPresent()) { /* At this point: 1. The function requested was found 2. The request was converted to its specified object for execution (Weather.class in this case) 3. It was executed 4. The response was finally converted to a ChatMessage object. */ - System.out.println("Executed " + functionCall.getName() + "."); - messages.add(message.get()); - continue; - } else { - System.out.println("Something went wrong with the execution of " + functionCall.getName() + "..."); - break; - } - } - - System.out.println("Response: " + responseMessage.getContent()); - System.out.print("Next Query: "); - String nextLine = scanner.nextLine(); - if (nextLine.equalsIgnoreCase("exit")) { - System.exit(0); - } - messages.add(new ChatMessage(ChatMessageRole.USER.value(), nextLine)); - } - } + System.out.println("Executed " + functionCall.getName() + "."); + messages.add(message.get()); + continue; + } else { + System.out.println( + "Something went wrong with the execution of " + functionCall.getName() + "..."); + break; + } + } + + System.out.println("Response: " + responseMessage.getContent()); + System.out.print("Next Query: "); + String nextLine = scanner.nextLine(); + if (nextLine.equalsIgnoreCase("exit")) { + System.exit(0); + } + messages.add(new ChatMessage(ChatMessageRole.USER.value(), nextLine)); + } + } } diff --git a/example/src/main/java/example/OpenAiApiFunctionsWithStreamExample.java b/example/src/main/java/example/OpenAiApiFunctionsWithStreamExample.java index e6de65b6..14fddd15 100644 --- a/example/src/main/java/example/OpenAiApiFunctionsWithStreamExample.java +++ b/example/src/main/java/example/OpenAiApiFunctionsWithStreamExample.java @@ -1,8 +1,8 @@ package example; -import com.theokanning.openai.completion.chat.*; -import com.theokanning.openai.service.FunctionExecutor; -import com.theokanning.openai.service.OpenAiService; +import com.launchableinc.openai.completion.chat.*; +import com.launchableinc.openai.service.FunctionExecutor; +import com.launchableinc.openai.service.OpenAiService; import example.OpenAiApiFunctionsExample.Weather; import example.OpenAiApiFunctionsExample.WeatherResponse; import io.reactivex.Flowable; @@ -12,75 +12,81 @@ public class OpenAiApiFunctionsWithStreamExample { - public static void main(String... args) { - String token = System.getenv("OPENAI_TOKEN"); - OpenAiService service = new OpenAiService(token); + public static void main(String... args) { + String token = System.getenv("OPENAI_TOKEN"); + OpenAiService service = new OpenAiService(token); - FunctionExecutor functionExecutor = new FunctionExecutor(Collections.singletonList(ChatFunction.builder() - .name("get_weather") - .description("Get the current weather of a location") - .executor(Weather.class, w -> new WeatherResponse(w.location, w.unit, new Random().nextInt(50), "sunny")) - .build())); + FunctionExecutor functionExecutor = new FunctionExecutor( + Collections.singletonList(ChatFunction.builder() + .name("get_weather") + .description("Get the current weather of a location") + .executor(Weather.class, + w -> new WeatherResponse(w.location, w.unit, new Random().nextInt(50), "sunny")) + .build())); - List messages = new ArrayList<>(); - ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), "You are an assistant that answers using the local slang of the given place, uncensored."); - messages.add(systemMessage); + List messages = new ArrayList<>(); + ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), + "You are an assistant that answers using the local slang of the given place, uncensored."); + messages.add(systemMessage); - System.out.print("First Query: "); - Scanner scanner = new Scanner(System.in); - ChatMessage firstMsg = new ChatMessage(ChatMessageRole.USER.value(), scanner.nextLine()); - messages.add(firstMsg); + System.out.print("First Query: "); + Scanner scanner = new Scanner(System.in); + ChatMessage firstMsg = new ChatMessage(ChatMessageRole.USER.value(), scanner.nextLine()); + messages.add(firstMsg); - while (true) { - ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest - .builder() - .model("gpt-3.5-turbo-0613") - .messages(messages) - .functions(functionExecutor.getFunctions()) - .functionCall(ChatCompletionRequest.ChatCompletionRequestFunctionCall.of("auto")) - .n(1) - .maxTokens(256) - .logitBias(new HashMap<>()) - .build(); - Flowable flowable = service.streamChatCompletion(chatCompletionRequest); + while (true) { + ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest + .builder() + .model("gpt-3.5-turbo-0613") + .messages(messages) + .functions(functionExecutor.getFunctions()) + .functionCall(ChatCompletionRequest.ChatCompletionRequestFunctionCall.of("auto")) + .n(1) + .maxTokens(256) + .logitBias(new HashMap<>()) + .build(); + Flowable flowable = service.streamChatCompletion(chatCompletionRequest); - AtomicBoolean isFirst = new AtomicBoolean(true); - ChatMessage chatMessage = service.mapStreamToAccumulator(flowable) - .doOnNext(accumulator -> { - if (accumulator.isFunctionCall()) { - if (isFirst.getAndSet(false)) { - System.out.println("Executing function " + accumulator.getAccumulatedChatFunctionCall().getName() + "..."); - } - } else { - if (isFirst.getAndSet(false)) { - System.out.print("Response: "); - } - if (accumulator.getMessageChunk().getContent() != null) { - System.out.print(accumulator.getMessageChunk().getContent()); - } - } - }) - .doOnComplete(System.out::println) - .lastElement() - .blockingGet() - .getAccumulatedMessage(); - messages.add(chatMessage); // don't forget to update the conversation with the latest response + AtomicBoolean isFirst = new AtomicBoolean(true); + ChatMessage chatMessage = service.mapStreamToAccumulator(flowable) + .doOnNext(accumulator -> { + if (accumulator.isFunctionCall()) { + if (isFirst.getAndSet(false)) { + System.out.println( + "Executing function " + accumulator.getAccumulatedChatFunctionCall().getName() + + "..."); + } + } else { + if (isFirst.getAndSet(false)) { + System.out.print("Response: "); + } + if (accumulator.getMessageChunk().getContent() != null) { + System.out.print(accumulator.getMessageChunk().getContent()); + } + } + }) + .doOnComplete(System.out::println) + .lastElement() + .blockingGet() + .getAccumulatedMessage(); + messages.add(chatMessage); // don't forget to update the conversation with the latest response - if (chatMessage.getFunctionCall() != null) { - System.out.println("Trying to execute " + chatMessage.getFunctionCall().getName() + "..."); - ChatMessage functionResponse = functionExecutor.executeAndConvertToMessageHandlingExceptions(chatMessage.getFunctionCall()); - System.out.println("Executed " + chatMessage.getFunctionCall().getName() + "."); - messages.add(functionResponse); - continue; - } + if (chatMessage.getFunctionCall() != null) { + System.out.println("Trying to execute " + chatMessage.getFunctionCall().getName() + "..."); + ChatMessage functionResponse = functionExecutor.executeAndConvertToMessageHandlingExceptions( + chatMessage.getFunctionCall()); + System.out.println("Executed " + chatMessage.getFunctionCall().getName() + "."); + messages.add(functionResponse); + continue; + } - System.out.print("Next Query: "); - String nextLine = scanner.nextLine(); - if (nextLine.equalsIgnoreCase("exit")) { - System.exit(0); - } - messages.add(new ChatMessage(ChatMessageRole.USER.value(), nextLine)); - } - } + System.out.print("Next Query: "); + String nextLine = scanner.nextLine(); + if (nextLine.equalsIgnoreCase("exit")) { + System.exit(0); + } + messages.add(new ChatMessage(ChatMessageRole.USER.value(), nextLine)); + } + } } \ No newline at end of file diff --git a/example/src/main/java/example/TikTokensExample.java b/example/src/main/java/example/TikTokensExample.java index 3da1a4d7..62445511 100644 --- a/example/src/main/java/example/TikTokensExample.java +++ b/example/src/main/java/example/TikTokensExample.java @@ -1,21 +1,22 @@ package example; -import com.theokanning.openai.completion.chat.ChatMessage; -import com.theokanning.openai.completion.chat.ChatMessageRole; -import com.theokanning.openai.utils.TikTokensUtil; +import com.launchableinc.openai.completion.chat.ChatMessage; +import com.launchableinc.openai.completion.chat.ChatMessageRole; +import com.launchableinc.openai.utils.TikTokensUtil; import java.util.ArrayList; import java.util.List; class TikTokensExample { - public static void main(String... args) { - List messages = new ArrayList<>(); - messages.add(new ChatMessage(ChatMessageRole.SYSTEM.value(), "Hello OpenAI 1.")); - messages.add(new ChatMessage(ChatMessageRole.SYSTEM.value(), "Hello OpenAI 2. ")); + public static void main(String... args) { + List messages = new ArrayList<>(); + messages.add(new ChatMessage(ChatMessageRole.SYSTEM.value(), "Hello OpenAI 1.")); + messages.add(new ChatMessage(ChatMessageRole.SYSTEM.value(), "Hello OpenAI 2. ")); - int tokens_1 = TikTokensUtil.tokens(TikTokensUtil.ModelEnum.GPT_3_5_TURBO.getName(), messages); - int tokens_2 = TikTokensUtil.tokens(TikTokensUtil.ModelEnum.GPT_3_5_TURBO.getName(), "Hello OpenAI 1."); - } + int tokens_1 = TikTokensUtil.tokens(TikTokensUtil.ModelEnum.GPT_3_5_TURBO.getName(), messages); + int tokens_2 = TikTokensUtil.tokens(TikTokensUtil.ModelEnum.GPT_3_5_TURBO.getName(), + "Hello OpenAI 1."); + } } diff --git a/gradle.properties b/gradle.properties index a4f840ab..221dca72 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,18 +1,14 @@ -GROUP=com.theokanning.openai-gpt3-java -VERSION_NAME=0.18.2 - -POM_URL=https://github.com/theokanning/openai-java -POM_SCM_URL=https://github.com/theokanning/openai-java -POM_SCM_CONNECTION=https://github.com/theokanning/openai-java.git -POM_SCM_DEV_CONNECTION=https://github.com/theokanning/openai-java.git - +GROUP=com.launchableinc.openai-java +VERSION_NAME=0.1.0 +POM_URL=https://github.com/launchableinc/openai-java +POM_SCM_URL=https://github.com/launchableinc/openai-java +POM_SCM_CONNECTION=https://github.com/launchableinc/openai-java.git +POM_SCM_DEV_CONNECTION=https://github.com/launchableinc/openai-java.git POM_LICENSE_NAME=The MIT License POM_LICENSE_URL=https://www.mit.edu/~amini/LICENSE.md POM_LICENSE_DIST=repo - -POM_DEVELOPER_ID=theokanning -POM_DEVELOPER_NAME=Theo Kanning - +POM_DEVELOPER_ID=Launchableinc +POM_DEVELOPER_NAME=Launchable,inc. org.gradle.parallel=true org.gradle.caching=true diff --git a/service/src/main/java/com/launchableinc/openai/service/AuthenticationInterceptor.java b/service/src/main/java/com/launchableinc/openai/service/AuthenticationInterceptor.java index 798eccb7..8bc4684e 100644 --- a/service/src/main/java/com/launchableinc/openai/service/AuthenticationInterceptor.java +++ b/service/src/main/java/com/launchableinc/openai/service/AuthenticationInterceptor.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.service; +package com.launchableinc.openai.service; import okhttp3.Interceptor; import okhttp3.Request; @@ -12,19 +12,19 @@ */ public class AuthenticationInterceptor implements Interceptor { - private final String token; + private final String token; - AuthenticationInterceptor(String token) { - Objects.requireNonNull(token, "OpenAI token required"); - this.token = token; - } + AuthenticationInterceptor(String token) { + Objects.requireNonNull(token, "OpenAI token required"); + this.token = token; + } - @Override - public Response intercept(Chain chain) throws IOException { - Request request = chain.request() - .newBuilder() - .header("Authorization", "Bearer " + token) - .build(); - return chain.proceed(request); - } + @Override + public Response intercept(Chain chain) throws IOException { + Request request = chain.request() + .newBuilder() + .header("Authorization", "Bearer " + token) + .build(); + return chain.proceed(request); + } } diff --git a/service/src/main/java/com/launchableinc/openai/service/ChatCompletionRequestMixIn.java b/service/src/main/java/com/launchableinc/openai/service/ChatCompletionRequestMixIn.java index e2f24ffb..bc774426 100644 --- a/service/src/main/java/com/launchableinc/openai/service/ChatCompletionRequestMixIn.java +++ b/service/src/main/java/com/launchableinc/openai/service/ChatCompletionRequestMixIn.java @@ -1,13 +1,13 @@ -package com.theokanning.openai.service; +package com.launchableinc.openai.service; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; -import com.theokanning.openai.completion.chat.ChatCompletionRequest; +import com.launchableinc.openai.completion.chat.ChatCompletionRequest; public abstract class ChatCompletionRequestMixIn { - @JsonSerialize(using = ChatCompletionRequestSerializerAndDeserializer.Serializer.class) - @JsonDeserialize(using = ChatCompletionRequestSerializerAndDeserializer.Deserializer.class) - abstract ChatCompletionRequest.ChatCompletionRequestFunctionCall getFunctionCall(); + @JsonSerialize(using = ChatCompletionRequestSerializerAndDeserializer.Serializer.class) + @JsonDeserialize(using = ChatCompletionRequestSerializerAndDeserializer.Deserializer.class) + abstract ChatCompletionRequest.ChatCompletionRequestFunctionCall getFunctionCall(); } diff --git a/service/src/main/java/com/launchableinc/openai/service/ChatCompletionRequestSerializerAndDeserializer.java b/service/src/main/java/com/launchableinc/openai/service/ChatCompletionRequestSerializerAndDeserializer.java index e9a8b023..94c5b89c 100644 --- a/service/src/main/java/com/launchableinc/openai/service/ChatCompletionRequestSerializerAndDeserializer.java +++ b/service/src/main/java/com/launchableinc/openai/service/ChatCompletionRequestSerializerAndDeserializer.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.service; +package com.launchableinc.openai.service; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; @@ -6,36 +6,42 @@ import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; -import com.theokanning.openai.completion.chat.ChatCompletionRequest; +import com.launchableinc.openai.completion.chat.ChatCompletionRequest; import java.io.IOException; public class ChatCompletionRequestSerializerAndDeserializer { - public static class Serializer extends JsonSerializer { - @Override - public void serialize(ChatCompletionRequest.ChatCompletionRequestFunctionCall value, JsonGenerator gen, SerializerProvider serializers) throws IOException { - if (value == null || value.getName() == null) { - gen.writeNull(); - } else if ("none".equals(value.getName()) || "auto".equals(value.getName())) { - gen.writeString(value.getName()); - } else { - gen.writeStartObject(); - gen.writeFieldName("name"); - gen.writeString(value.getName()); - gen.writeEndObject(); - } - } - } + public static class Serializer extends + JsonSerializer { - public static class Deserializer extends JsonDeserializer { - @Override - public ChatCompletionRequest.ChatCompletionRequestFunctionCall deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { - if (p.getCurrentToken().isStructStart()) { - p.nextToken(); //key - p.nextToken(); //value - } - return new ChatCompletionRequest.ChatCompletionRequestFunctionCall(p.getValueAsString()); - } - } + @Override + public void serialize(ChatCompletionRequest.ChatCompletionRequestFunctionCall value, + JsonGenerator gen, SerializerProvider serializers) throws IOException { + if (value == null || value.getName() == null) { + gen.writeNull(); + } else if ("none" .equals(value.getName()) || "auto" .equals(value.getName())) { + gen.writeString(value.getName()); + } else { + gen.writeStartObject(); + gen.writeFieldName("name"); + gen.writeString(value.getName()); + gen.writeEndObject(); + } + } + } + + public static class Deserializer extends + JsonDeserializer { + + @Override + public ChatCompletionRequest.ChatCompletionRequestFunctionCall deserialize(JsonParser p, + DeserializationContext ctxt) throws IOException { + if (p.getCurrentToken().isStructStart()) { + p.nextToken(); //key + p.nextToken(); //value + } + return new ChatCompletionRequest.ChatCompletionRequestFunctionCall(p.getValueAsString()); + } + } } diff --git a/service/src/main/java/com/launchableinc/openai/service/ChatFunctionCallArgumentsSerializerAndDeserializer.java b/service/src/main/java/com/launchableinc/openai/service/ChatFunctionCallArgumentsSerializerAndDeserializer.java index 9b7be0f9..c2c32224 100644 --- a/service/src/main/java/com/launchableinc/openai/service/ChatFunctionCallArgumentsSerializerAndDeserializer.java +++ b/service/src/main/java/com/launchableinc/openai/service/ChatFunctionCallArgumentsSerializerAndDeserializer.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.service; +package com.launchableinc.openai.service; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParseException; @@ -12,53 +12,54 @@ public class ChatFunctionCallArgumentsSerializerAndDeserializer { - private final static ObjectMapper MAPPER = new ObjectMapper(); + private final static ObjectMapper MAPPER = new ObjectMapper(); - private ChatFunctionCallArgumentsSerializerAndDeserializer() { - } + private ChatFunctionCallArgumentsSerializerAndDeserializer() { + } - public static class Serializer extends JsonSerializer { + public static class Serializer extends JsonSerializer { - private Serializer() { - } + private Serializer() { + } - @Override - public void serialize(JsonNode value, JsonGenerator gen, SerializerProvider serializers) throws IOException { - if (value == null) { - gen.writeNull(); - } else { - gen.writeString(value instanceof TextNode ? value.asText() : value.toPrettyString()); - } - } - } + @Override + public void serialize(JsonNode value, JsonGenerator gen, SerializerProvider serializers) + throws IOException { + if (value == null) { + gen.writeNull(); + } else { + gen.writeString(value instanceof TextNode ? value.asText() : value.toPrettyString()); + } + } + } - public static class Deserializer extends JsonDeserializer { + public static class Deserializer extends JsonDeserializer { - private Deserializer() { - } + private Deserializer() { + } - @Override - public JsonNode deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { - String json = p.getValueAsString(); - if (json == null || p.currentToken() == JsonToken.VALUE_NULL) { - return null; - } + @Override + public JsonNode deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { + String json = p.getValueAsString(); + if (json == null || p.currentToken() == JsonToken.VALUE_NULL) { + return null; + } - try { - JsonNode node = null; - try { - node = MAPPER.readTree(json); - } catch (JsonParseException ignored) { - } - if (node == null || node.getNodeType() == JsonNodeType.MISSING) { - node = MAPPER.readTree(p); - } - return node; - } catch (Exception ex) { - ex.printStackTrace(); - return null; - } - } - } + try { + JsonNode node = null; + try { + node = MAPPER.readTree(json); + } catch (JsonParseException ignored) { + } + if (node == null || node.getNodeType() == JsonNodeType.MISSING) { + node = MAPPER.readTree(p); + } + return node; + } catch (Exception ex) { + ex.printStackTrace(); + return null; + } + } + } } diff --git a/service/src/main/java/com/launchableinc/openai/service/ChatFunctionCallMixIn.java b/service/src/main/java/com/launchableinc/openai/service/ChatFunctionCallMixIn.java index 7b32e051..56693bb3 100644 --- a/service/src/main/java/com/launchableinc/openai/service/ChatFunctionCallMixIn.java +++ b/service/src/main/java/com/launchableinc/openai/service/ChatFunctionCallMixIn.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.service; +package com.launchableinc.openai.service; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; @@ -6,8 +6,8 @@ public abstract class ChatFunctionCallMixIn { - @JsonSerialize(using = ChatFunctionCallArgumentsSerializerAndDeserializer.Serializer.class) - @JsonDeserialize(using = ChatFunctionCallArgumentsSerializerAndDeserializer.Deserializer.class) - abstract JsonNode getArguments(); + @JsonSerialize(using = ChatFunctionCallArgumentsSerializerAndDeserializer.Serializer.class) + @JsonDeserialize(using = ChatFunctionCallArgumentsSerializerAndDeserializer.Deserializer.class) + abstract JsonNode getArguments(); } diff --git a/service/src/main/java/com/launchableinc/openai/service/ChatFunctionMixIn.java b/service/src/main/java/com/launchableinc/openai/service/ChatFunctionMixIn.java index d94a9179..4eb6b859 100644 --- a/service/src/main/java/com/launchableinc/openai/service/ChatFunctionMixIn.java +++ b/service/src/main/java/com/launchableinc/openai/service/ChatFunctionMixIn.java @@ -1,10 +1,10 @@ -package com.theokanning.openai.service; +package com.launchableinc.openai.service; import com.fasterxml.jackson.databind.annotation.JsonSerialize; public abstract class ChatFunctionMixIn { - @JsonSerialize(using = ChatFunctionParametersSerializer.class) - abstract Class getParametersClass(); + @JsonSerialize(using = ChatFunctionParametersSerializer.class) + abstract Class getParametersClass(); } diff --git a/service/src/main/java/com/launchableinc/openai/service/ChatFunctionParametersSerializer.java b/service/src/main/java/com/launchableinc/openai/service/ChatFunctionParametersSerializer.java index c0273916..b1b25c42 100644 --- a/service/src/main/java/com/launchableinc/openai/service/ChatFunctionParametersSerializer.java +++ b/service/src/main/java/com/launchableinc/openai/service/ChatFunctionParametersSerializer.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.service; +package com.launchableinc.openai.service; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonNode; @@ -12,23 +12,24 @@ public class ChatFunctionParametersSerializer extends JsonSerializer> { - private final ObjectMapper mapper = new ObjectMapper(); - private final JsonSchemaConfig config = JsonSchemaConfig.vanillaJsonSchemaDraft4(); - private final JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator(mapper, config); - - @Override - public void serialize(Class value, JsonGenerator gen, SerializerProvider serializers) throws IOException { - if (value == null) { - gen.writeNull(); - } else { - try { - JsonNode schema = jsonSchemaGenerator.generateJsonSchema(value); - gen.writeObject(schema); - } catch (Exception e) { - throw new RuntimeException("Failed to generate JSON Schema", e); - } - } - } + private final ObjectMapper mapper = new ObjectMapper(); + private final JsonSchemaConfig config = JsonSchemaConfig.vanillaJsonSchemaDraft4(); + private final JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator(mapper, config); + + @Override + public void serialize(Class value, JsonGenerator gen, SerializerProvider serializers) + throws IOException { + if (value == null) { + gen.writeNull(); + } else { + try { + JsonNode schema = jsonSchemaGenerator.generateJsonSchema(value); + gen.writeObject(schema); + } catch (Exception e) { + throw new RuntimeException("Failed to generate JSON Schema", e); + } + } + } } diff --git a/service/src/main/java/com/launchableinc/openai/service/ChatMessageAccumulator.java b/service/src/main/java/com/launchableinc/openai/service/ChatMessageAccumulator.java index a55173cc..2725763b 100644 --- a/service/src/main/java/com/launchableinc/openai/service/ChatMessageAccumulator.java +++ b/service/src/main/java/com/launchableinc/openai/service/ChatMessageAccumulator.java @@ -1,84 +1,84 @@ -package com.theokanning.openai.service; +package com.launchableinc.openai.service; -import com.theokanning.openai.completion.chat.ChatFunctionCall; -import com.theokanning.openai.completion.chat.ChatMessage; +import com.launchableinc.openai.completion.chat.ChatFunctionCall; +import com.launchableinc.openai.completion.chat.ChatMessage; /** - * Class that accumulates chat messages and provides utility methods for - * handling message chunks and function calls within a chat stream. This - * class is immutable. + * Class that accumulates chat messages and provides utility methods for handling message chunks and + * function calls within a chat stream. This class is immutable. * * @author [Your Name] */ public class ChatMessageAccumulator { - private final ChatMessage messageChunk; - private final ChatMessage accumulatedMessage; + private final ChatMessage messageChunk; + private final ChatMessage accumulatedMessage; - /** - * Constructor that initializes the message chunk and accumulated message. - * - * @param messageChunk The message chunk. - * @param accumulatedMessage The accumulated message. - */ - public ChatMessageAccumulator(ChatMessage messageChunk, ChatMessage accumulatedMessage) { - this.messageChunk = messageChunk; - this.accumulatedMessage = accumulatedMessage; - } + /** + * Constructor that initializes the message chunk and accumulated message. + * + * @param messageChunk The message chunk. + * @param accumulatedMessage The accumulated message. + */ + public ChatMessageAccumulator(ChatMessage messageChunk, ChatMessage accumulatedMessage) { + this.messageChunk = messageChunk; + this.accumulatedMessage = accumulatedMessage; + } - /** - * Checks if the accumulated message contains a function call. - * - * @return true if the accumulated message contains a function call, false otherwise. - */ - public boolean isFunctionCall() { - return getAccumulatedMessage().getFunctionCall() != null && getAccumulatedMessage().getFunctionCall().getName() != null; - } + /** + * Checks if the accumulated message contains a function call. + * + * @return true if the accumulated message contains a function call, false otherwise. + */ + public boolean isFunctionCall() { + return getAccumulatedMessage().getFunctionCall() != null + && getAccumulatedMessage().getFunctionCall().getName() != null; + } - /** - * Checks if the accumulated message contains a chat message. - * - * @return true if the accumulated message contains a chat message, false otherwise. - */ - public boolean isChatMessage() { - return !isFunctionCall(); - } + /** + * Checks if the accumulated message contains a chat message. + * + * @return true if the accumulated message contains a chat message, false otherwise. + */ + public boolean isChatMessage() { + return !isFunctionCall(); + } - /** - * Retrieves the message chunk. - * - * @return the message chunk. - */ - public ChatMessage getMessageChunk() { - return messageChunk; - } + /** + * Retrieves the message chunk. + * + * @return the message chunk. + */ + public ChatMessage getMessageChunk() { + return messageChunk; + } - /** - * Retrieves the accumulated message. - * - * @return the accumulated message. - */ - public ChatMessage getAccumulatedMessage() { - return accumulatedMessage; - } + /** + * Retrieves the accumulated message. + * + * @return the accumulated message. + */ + public ChatMessage getAccumulatedMessage() { + return accumulatedMessage; + } - /** - * Retrieves the function call from the message chunk. - * This is equivalent to getMessageChunk().getFunctionCall(). - * - * @return the function call from the message chunk. - */ - public ChatFunctionCall getChatFunctionCallChunk() { - return getMessageChunk().getFunctionCall(); - } + /** + * Retrieves the function call from the message chunk. This is equivalent to + * getMessageChunk().getFunctionCall(). + * + * @return the function call from the message chunk. + */ + public ChatFunctionCall getChatFunctionCallChunk() { + return getMessageChunk().getFunctionCall(); + } - /** - * Retrieves the function call from the accumulated message. - * This is equivalent to getAccumulatedMessage().getFunctionCall(). - * - * @return the function call from the accumulated message. - */ - public ChatFunctionCall getAccumulatedChatFunctionCall() { - return getAccumulatedMessage().getFunctionCall(); - } + /** + * Retrieves the function call from the accumulated message. This is equivalent to + * getAccumulatedMessage().getFunctionCall(). + * + * @return the function call from the accumulated message. + */ + public ChatFunctionCall getAccumulatedChatFunctionCall() { + return getAccumulatedMessage().getFunctionCall(); + } } diff --git a/service/src/main/java/com/launchableinc/openai/service/FunctionExecutor.java b/service/src/main/java/com/launchableinc/openai/service/FunctionExecutor.java index 5d143a95..620244c8 100644 --- a/service/src/main/java/com/launchableinc/openai/service/FunctionExecutor.java +++ b/service/src/main/java/com/launchableinc/openai/service/FunctionExecutor.java @@ -1,105 +1,111 @@ -package com.theokanning.openai.service; +package com.launchableinc.openai.service; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.TextNode; -import com.theokanning.openai.completion.chat.ChatFunction; -import com.theokanning.openai.completion.chat.ChatFunctionCall; -import com.theokanning.openai.completion.chat.ChatMessage; -import com.theokanning.openai.completion.chat.ChatMessageRole; +import com.launchableinc.openai.completion.chat.ChatFunction; +import com.launchableinc.openai.completion.chat.ChatFunctionCall; +import com.launchableinc.openai.completion.chat.ChatMessage; +import com.launchableinc.openai.completion.chat.ChatMessageRole; import java.util.*; public class FunctionExecutor { - private ObjectMapper MAPPER = new ObjectMapper(); - private final Map FUNCTIONS = new HashMap<>(); - - public FunctionExecutor(List functions) { - setFunctions(functions); - } - - public FunctionExecutor(List functions, ObjectMapper objectMapper) { - setFunctions(functions); - setObjectMapper(objectMapper); - } - - public Optional executeAndConvertToMessageSafely(ChatFunctionCall call) { - try { - return Optional.ofNullable(executeAndConvertToMessage(call)); - } catch (Exception ignored) { - return Optional.empty(); - } - } - - public ChatMessage executeAndConvertToMessageHandlingExceptions(ChatFunctionCall call) { - try { - return executeAndConvertToMessage(call); - } catch (Exception exception) { - exception.printStackTrace(); - return convertExceptionToMessage(exception); - } - } - - public ChatMessage convertExceptionToMessage(Exception exception) { - String error = exception.getMessage() == null ? exception.toString() : exception.getMessage(); - return new ChatMessage(ChatMessageRole.FUNCTION.value(), "{\"error\": \"" + error + "\"}", "error"); - } - - public ChatMessage executeAndConvertToMessage(ChatFunctionCall call) { - return new ChatMessage(ChatMessageRole.FUNCTION.value(), executeAndConvertToJson(call).toPrettyString(), call.getName()); - } - - public JsonNode executeAndConvertToJson(ChatFunctionCall call) { - try { - Object execution = execute(call); - if (execution instanceof TextNode) { - JsonNode objectNode = MAPPER.readTree(((TextNode) execution).asText()); - if (objectNode.isMissingNode()) - return (JsonNode) execution; - return objectNode; - } - if (execution instanceof ObjectNode) { - return (JsonNode) execution; - } - if (execution instanceof String) { - JsonNode objectNode = MAPPER.readTree((String) execution); - if (objectNode.isMissingNode()) - throw new RuntimeException("Parsing exception"); - return objectNode; - } - return MAPPER.readValue(MAPPER.writeValueAsString(execution), JsonNode.class); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - @SuppressWarnings("unchecked") - public T execute(ChatFunctionCall call) { - ChatFunction function = FUNCTIONS.get(call.getName()); - Object obj; - try { - JsonNode arguments = call.getArguments(); - obj = MAPPER.readValue(arguments instanceof TextNode ? arguments.asText() : arguments.toPrettyString(), function.getParametersClass()); - } catch (JsonProcessingException e) { - throw new RuntimeException(e); - } - return (T) function.getExecutor().apply(obj); - } - - public List getFunctions() { - return new ArrayList<>(FUNCTIONS.values()); - } - - public void setFunctions(List functions) { - this.FUNCTIONS.clear(); - functions.forEach(f -> this.FUNCTIONS.put(f.getName(), f)); - } - - public void setObjectMapper(ObjectMapper objectMapper) { - this.MAPPER = objectMapper; - } + private ObjectMapper MAPPER = new ObjectMapper(); + private final Map FUNCTIONS = new HashMap<>(); + + public FunctionExecutor(List functions) { + setFunctions(functions); + } + + public FunctionExecutor(List functions, ObjectMapper objectMapper) { + setFunctions(functions); + setObjectMapper(objectMapper); + } + + public Optional executeAndConvertToMessageSafely(ChatFunctionCall call) { + try { + return Optional.ofNullable(executeAndConvertToMessage(call)); + } catch (Exception ignored) { + return Optional.empty(); + } + } + + public ChatMessage executeAndConvertToMessageHandlingExceptions(ChatFunctionCall call) { + try { + return executeAndConvertToMessage(call); + } catch (Exception exception) { + exception.printStackTrace(); + return convertExceptionToMessage(exception); + } + } + + public ChatMessage convertExceptionToMessage(Exception exception) { + String error = exception.getMessage() == null ? exception.toString() : exception.getMessage(); + return new ChatMessage(ChatMessageRole.FUNCTION.value(), "{\"error\": \"" + error + "\"}", + "error"); + } + + public ChatMessage executeAndConvertToMessage(ChatFunctionCall call) { + return new ChatMessage(ChatMessageRole.FUNCTION.value(), + executeAndConvertToJson(call).toPrettyString(), call.getName()); + } + + public JsonNode executeAndConvertToJson(ChatFunctionCall call) { + try { + Object execution = execute(call); + if (execution instanceof TextNode) { + JsonNode objectNode = MAPPER.readTree(((TextNode) execution).asText()); + if (objectNode.isMissingNode()) { + return (JsonNode) execution; + } + return objectNode; + } + if (execution instanceof ObjectNode) { + return (JsonNode) execution; + } + if (execution instanceof String) { + JsonNode objectNode = MAPPER.readTree((String) execution); + if (objectNode.isMissingNode()) { + throw new RuntimeException("Parsing exception"); + } + return objectNode; + } + return MAPPER.readValue(MAPPER.writeValueAsString(execution), JsonNode.class); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @SuppressWarnings("unchecked") + public T execute(ChatFunctionCall call) { + ChatFunction function = FUNCTIONS.get(call.getName()); + Object obj; + try { + JsonNode arguments = call.getArguments(); + obj = MAPPER.readValue( + arguments instanceof TextNode ? arguments.asText() : arguments.toPrettyString(), + function.getParametersClass()); + } catch (JsonProcessingException e) { + throw new RuntimeException(e); + } + return (T) function.getExecutor().apply(obj); + } + + public List getFunctions() { + return new ArrayList<>(FUNCTIONS.values()); + } + + public void setFunctions(List functions) { + this.FUNCTIONS.clear(); + functions.forEach(f -> this.FUNCTIONS.put(f.getName(), f)); + } + + public void setObjectMapper(ObjectMapper objectMapper) { + this.MAPPER = objectMapper; + } } diff --git a/service/src/main/java/com/launchableinc/openai/service/OpenAiService.java b/service/src/main/java/com/launchableinc/openai/service/OpenAiService.java index 52ab6b0f..5d0ff003 100644 --- a/service/src/main/java/com/launchableinc/openai/service/OpenAiService.java +++ b/service/src/main/java/com/launchableinc/openai/service/OpenAiService.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.service; +package com.launchableinc.openai.service; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.type.TypeReference; @@ -6,45 +6,45 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.node.TextNode; -import com.theokanning.openai.*; -import com.theokanning.openai.assistants.*; -import com.theokanning.openai.audio.*; -import com.theokanning.openai.billing.BillingUsage; -import com.theokanning.openai.billing.Subscription; -import com.theokanning.openai.client.OpenAiApi; -import com.theokanning.openai.completion.CompletionChunk; -import com.theokanning.openai.completion.CompletionRequest; -import com.theokanning.openai.completion.CompletionResult; -import com.theokanning.openai.completion.chat.*; -import com.theokanning.openai.edit.EditRequest; -import com.theokanning.openai.edit.EditResult; -import com.theokanning.openai.embedding.EmbeddingRequest; -import com.theokanning.openai.embedding.EmbeddingResult; -import com.theokanning.openai.file.File; -import com.theokanning.openai.fine_tuning.FineTuningEvent; -import com.theokanning.openai.fine_tuning.FineTuningJob; -import com.theokanning.openai.fine_tuning.FineTuningJobRequest; -import com.theokanning.openai.finetune.FineTuneEvent; -import com.theokanning.openai.finetune.FineTuneRequest; -import com.theokanning.openai.finetune.FineTuneResult; -import com.theokanning.openai.image.CreateImageEditRequest; -import com.theokanning.openai.image.CreateImageRequest; -import com.theokanning.openai.image.CreateImageVariationRequest; -import com.theokanning.openai.image.ImageResult; -import com.theokanning.openai.messages.Message; -import com.theokanning.openai.messages.MessageFile; -import com.theokanning.openai.messages.MessageRequest; -import com.theokanning.openai.messages.ModifyMessageRequest; -import com.theokanning.openai.model.Model; -import com.theokanning.openai.moderation.ModerationRequest; -import com.theokanning.openai.moderation.ModerationResult; -import com.theokanning.openai.runs.CreateThreadAndRunRequest; -import com.theokanning.openai.runs.Run; -import com.theokanning.openai.runs.RunCreateRequest; -import com.theokanning.openai.runs.RunStep; -import com.theokanning.openai.runs.SubmitToolOutputsRequest; -import com.theokanning.openai.threads.Thread; -import com.theokanning.openai.threads.ThreadRequest; +import com.launchableinc.openai.*; +import com.launchableinc.openai.assistants.*; +import com.launchableinc.openai.audio.*; +import com.launchableinc.openai.billing.BillingUsage; +import com.launchableinc.openai.billing.Subscription; +import com.launchableinc.openai.client.OpenAiApi; +import com.launchableinc.openai.completion.CompletionChunk; +import com.launchableinc.openai.completion.CompletionRequest; +import com.launchableinc.openai.completion.CompletionResult; +import com.launchableinc.openai.completion.chat.*; +import com.launchableinc.openai.edit.EditRequest; +import com.launchableinc.openai.edit.EditResult; +import com.launchableinc.openai.embedding.EmbeddingRequest; +import com.launchableinc.openai.embedding.EmbeddingResult; +import com.launchableinc.openai.file.File; +import com.launchableinc.openai.fine_tuning.FineTuningEvent; +import com.launchableinc.openai.fine_tuning.FineTuningJob; +import com.launchableinc.openai.fine_tuning.FineTuningJobRequest; +import com.launchableinc.openai.finetune.FineTuneEvent; +import com.launchableinc.openai.finetune.FineTuneRequest; +import com.launchableinc.openai.finetune.FineTuneResult; +import com.launchableinc.openai.image.CreateImageEditRequest; +import com.launchableinc.openai.image.CreateImageRequest; +import com.launchableinc.openai.image.CreateImageVariationRequest; +import com.launchableinc.openai.image.ImageResult; +import com.launchableinc.openai.messages.Message; +import com.launchableinc.openai.messages.MessageFile; +import com.launchableinc.openai.messages.MessageRequest; +import com.launchableinc.openai.messages.ModifyMessageRequest; +import com.launchableinc.openai.model.Model; +import com.launchableinc.openai.moderation.ModerationRequest; +import com.launchableinc.openai.moderation.ModerationResult; +import com.launchableinc.openai.runs.CreateThreadAndRunRequest; +import com.launchableinc.openai.runs.Run; +import com.launchableinc.openai.runs.RunCreateRequest; +import com.launchableinc.openai.runs.RunStep; +import com.launchableinc.openai.runs.SubmitToolOutputsRequest; +import com.launchableinc.openai.threads.Thread; +import com.launchableinc.openai.threads.ThreadRequest; import io.reactivex.BackpressureStrategy; import io.reactivex.Flowable; import io.reactivex.Single; @@ -68,595 +68,611 @@ public class OpenAiService { - private static final String BASE_URL = "https://api.openai.com/"; - private static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(10); - private static final ObjectMapper mapper = defaultObjectMapper(); - - private final OpenAiApi api; - private final ExecutorService executorService; - - /** - * Creates a new OpenAiService that wraps OpenAiApi - * - * @param token OpenAi token string "sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" - */ - public OpenAiService(final String token) { - this(token, DEFAULT_TIMEOUT); - } - - /** - * Creates a new OpenAiService that wraps OpenAiApi - * - * @param token OpenAi token string "sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" - * @param timeout http read timeout, Duration.ZERO means no timeout - */ - public OpenAiService(final String token, final Duration timeout) { - ObjectMapper mapper = defaultObjectMapper(); - OkHttpClient client = defaultClient(token, timeout); - Retrofit retrofit = defaultRetrofit(client, mapper); - - this.api = retrofit.create(OpenAiApi.class); - this.executorService = client.dispatcher().executorService(); - } - - /** - * Creates a new OpenAiService that wraps OpenAiApi. - * Use this if you need more customization, but use OpenAiService(api, executorService) if you use streaming and - * want to shut down instantly - * - * @param api OpenAiApi instance to use for all methods - */ - public OpenAiService(final OpenAiApi api) { - this.api = api; - this.executorService = null; - } - - /** - * Creates a new OpenAiService that wraps OpenAiApi. - * The ExecutorService must be the one you get from the client you created the api with - * otherwise shutdownExecutor() won't work. - *

- * Use this if you need more customization. - * - * @param api OpenAiApi instance to use for all methods - * @param executorService the ExecutorService from client.dispatcher().executorService() - */ - public OpenAiService(final OpenAiApi api, final ExecutorService executorService) { - this.api = api; - this.executorService = executorService; - } - - public List listModels() { - return execute(api.listModels()).data; - } - - public Model getModel(String modelId) { - return execute(api.getModel(modelId)); - } - - public CompletionResult createCompletion(CompletionRequest request) { - return execute(api.createCompletion(request)); - } - - public Flowable streamCompletion(CompletionRequest request) { - request.setStream(true); - - return stream(api.createCompletionStream(request), CompletionChunk.class); - } - - public ChatCompletionResult createChatCompletion(ChatCompletionRequest request) { - return execute(api.createChatCompletion(request)); - } - - public Flowable streamChatCompletion(ChatCompletionRequest request) { - request.setStream(true); - - return stream(api.createChatCompletionStream(request), ChatCompletionChunk.class); - } - - public EditResult createEdit(EditRequest request) { - return execute(api.createEdit(request)); - } - - public EmbeddingResult createEmbeddings(EmbeddingRequest request) { - return execute(api.createEmbeddings(request)); - } - - public List listFiles() { - return execute(api.listFiles()).data; - } - - public File uploadFile(String purpose, String filepath) { - java.io.File file = new java.io.File(filepath); - RequestBody purposeBody = RequestBody.create(MultipartBody.FORM, purpose); - RequestBody fileBody = RequestBody.create(MediaType.parse("text"), file); - MultipartBody.Part body = MultipartBody.Part.createFormData("file", filepath, fileBody); - - return execute(api.uploadFile(purposeBody, body)); - } - - public DeleteResult deleteFile(String fileId) { - return execute(api.deleteFile(fileId)); - } - - public File retrieveFile(String fileId) { - return execute(api.retrieveFile(fileId)); - } - - public ResponseBody retrieveFileContent(String fileId) { - return execute(api.retrieveFileContent(fileId)); - } - - public FineTuningJob createFineTuningJob(FineTuningJobRequest request) { - return execute(api.createFineTuningJob(request)); - } - - public List listFineTuningJobs() { - return execute(api.listFineTuningJobs()).data; - } - - public FineTuningJob retrieveFineTuningJob(String fineTuningJobId) { - return execute(api.retrieveFineTuningJob(fineTuningJobId)); - } - - public FineTuningJob cancelFineTuningJob(String fineTuningJobId) { - return execute(api.cancelFineTuningJob(fineTuningJobId)); - } - - public List listFineTuningJobEvents(String fineTuningJobId) { - return execute(api.listFineTuningJobEvents(fineTuningJobId)).data; - } - - @Deprecated - public FineTuneResult createFineTune(FineTuneRequest request) { - return execute(api.createFineTune(request)); - } - - public CompletionResult createFineTuneCompletion(CompletionRequest request) { - return execute(api.createFineTuneCompletion(request)); - } - - @Deprecated - public List listFineTunes() { - return execute(api.listFineTunes()).data; - } - - @Deprecated - public FineTuneResult retrieveFineTune(String fineTuneId) { - return execute(api.retrieveFineTune(fineTuneId)); - } - - @Deprecated - public FineTuneResult cancelFineTune(String fineTuneId) { - return execute(api.cancelFineTune(fineTuneId)); - } - - @Deprecated - public List listFineTuneEvents(String fineTuneId) { - return execute(api.listFineTuneEvents(fineTuneId)).data; - } - - public DeleteResult deleteFineTune(String fineTuneId) { - return execute(api.deleteFineTune(fineTuneId)); - } - - public ImageResult createImage(CreateImageRequest request) { - return execute(api.createImage(request)); - } - - public ImageResult createImageEdit(CreateImageEditRequest request, String imagePath, String maskPath) { - java.io.File image = new java.io.File(imagePath); - java.io.File mask = null; - if (maskPath != null) { - mask = new java.io.File(maskPath); - } - return createImageEdit(request, image, mask); - } - - public ImageResult createImageEdit(CreateImageEditRequest request, java.io.File image, java.io.File mask) { - RequestBody imageBody = RequestBody.create(MediaType.parse("image"), image); - - MultipartBody.Builder builder = new MultipartBody.Builder() - .setType(MediaType.get("multipart/form-data")) - .addFormDataPart("prompt", request.getPrompt()) - .addFormDataPart("size", request.getSize()) - .addFormDataPart("response_format", request.getResponseFormat()) - .addFormDataPart("image", "image", imageBody); - - if (request.getN() != null) { - builder.addFormDataPart("n", request.getN().toString()); - } - - if (mask != null) { - RequestBody maskBody = RequestBody.create(MediaType.parse("image"), mask); - builder.addFormDataPart("mask", "mask", maskBody); - } - - if (request.getModel() != null) { - builder.addFormDataPart("model", request.getModel()); - } - - return execute(api.createImageEdit(builder.build())); - } - - public ImageResult createImageVariation(CreateImageVariationRequest request, String imagePath) { - java.io.File image = new java.io.File(imagePath); - return createImageVariation(request, image); - } - - public ImageResult createImageVariation(CreateImageVariationRequest request, java.io.File image) { - RequestBody imageBody = RequestBody.create(MediaType.parse("image"), image); - - MultipartBody.Builder builder = new MultipartBody.Builder() - .setType(MediaType.get("multipart/form-data")) - .addFormDataPart("size", request.getSize()) - .addFormDataPart("response_format", request.getResponseFormat()) - .addFormDataPart("image", "image", imageBody); - - if (request.getN() != null) { - builder.addFormDataPart("n", request.getN().toString()); - } - - if (request.getModel() != null) { - builder.addFormDataPart("model", request.getModel()); - } - - return execute(api.createImageVariation(builder.build())); - } - - public TranscriptionResult createTranscription(CreateTranscriptionRequest request, String audioPath) { - java.io.File audio = new java.io.File(audioPath); - return createTranscription(request, audio); - } - - public TranscriptionResult createTranscription(CreateTranscriptionRequest request, java.io.File audio) { - RequestBody audioBody = RequestBody.create(MediaType.parse("audio"), audio); - - MultipartBody.Builder builder = new MultipartBody.Builder() - .setType(MediaType.get("multipart/form-data")) - .addFormDataPart("model", request.getModel()) - .addFormDataPart("file", audio.getName(), audioBody); - - if (request.getPrompt() != null) { - builder.addFormDataPart("prompt", request.getPrompt()); - } - if (request.getResponseFormat() != null) { - builder.addFormDataPart("response_format", request.getResponseFormat()); - } - if (request.getTemperature() != null) { - builder.addFormDataPart("temperature", request.getTemperature().toString()); - } - if (request.getLanguage() != null) { - builder.addFormDataPart("language", request.getLanguage()); - } - - return execute(api.createTranscription(builder.build())); - } - - public TranslationResult createTranslation(CreateTranslationRequest request, String audioPath) { - java.io.File audio = new java.io.File(audioPath); - return createTranslation(request, audio); - } - - public TranslationResult createTranslation(CreateTranslationRequest request, java.io.File audio) { - RequestBody audioBody = RequestBody.create(MediaType.parse("audio"), audio); - - MultipartBody.Builder builder = new MultipartBody.Builder() - .setType(MediaType.get("multipart/form-data")) - .addFormDataPart("model", request.getModel()) - .addFormDataPart("file", audio.getName(), audioBody); - - if (request.getPrompt() != null) { - builder.addFormDataPart("prompt", request.getPrompt()); - } - if (request.getResponseFormat() != null) { - builder.addFormDataPart("response_format", request.getResponseFormat()); - } - if (request.getTemperature() != null) { - builder.addFormDataPart("temperature", request.getTemperature().toString()); - } - - return execute(api.createTranslation(builder.build())); - } - - public ModerationResult createModeration(ModerationRequest request) { - return execute(api.createModeration(request)); - } - - public ResponseBody createSpeech(CreateSpeechRequest request) { - return execute(api.createSpeech(request)); - } - - public Assistant createAssistant(AssistantRequest request) { - return execute(api.createAssistant(request)); - } - - public Assistant retrieveAssistant(String assistantId) { - return execute(api.retrieveAssistant(assistantId)); - } - - public Assistant modifyAssistant(String assistantId, ModifyAssistantRequest request) { - return execute(api.modifyAssistant(assistantId, request)); - } - - public DeleteResult deleteAssistant(String assistantId) { - return execute(api.deleteAssistant(assistantId)); - } - - public OpenAiResponse listAssistants(ListSearchParameters params) { - Map queryParameters = mapper.convertValue(params, new TypeReference>() { - }); - return execute(api.listAssistants(queryParameters)); - } - - public AssistantFile createAssistantFile(String assistantId, AssistantFileRequest fileRequest) { - return execute(api.createAssistantFile(assistantId, fileRequest)); - } - - public AssistantFile retrieveAssistantFile(String assistantId, String fileId) { - return execute(api.retrieveAssistantFile(assistantId, fileId)); - } - - public DeleteResult deleteAssistantFile(String assistantId, String fileId) { - return execute(api.deleteAssistantFile(assistantId, fileId)); - } - - public OpenAiResponse listAssistantFiles(String assistantId, ListSearchParameters params) { - Map queryParameters = mapper.convertValue(params, new TypeReference>() { - }); - return execute(api.listAssistantFiles(assistantId, queryParameters)); - } - - public Thread createThread(ThreadRequest request) { - return execute(api.createThread(request)); - } - - public Thread retrieveThread(String threadId) { - return execute(api.retrieveThread(threadId)); - } - - public Thread modifyThread(String threadId, ThreadRequest request) { - return execute(api.modifyThread(threadId, request)); - } - - public DeleteResult deleteThread(String threadId) { - return execute(api.deleteThread(threadId)); - } - - public Message createMessage(String threadId, MessageRequest request) { - return execute(api.createMessage(threadId, request)); - } - - public Message retrieveMessage(String threadId, String messageId) { - return execute(api.retrieveMessage(threadId, messageId)); - } - - public Message modifyMessage(String threadId, String messageId, ModifyMessageRequest request) { - return execute(api.modifyMessage(threadId, messageId, request)); - } - - public OpenAiResponse listMessages(String threadId) { - return execute(api.listMessages(threadId)); - } - - public OpenAiResponse listMessages(String threadId, ListSearchParameters params) { - Map queryParameters = mapper.convertValue(params, new TypeReference>() { - }); - return execute(api.listMessages(threadId, queryParameters)); - } - - public MessageFile retrieveMessageFile(String threadId, String messageId, String fileId) { - return execute(api.retrieveMessageFile(threadId, messageId, fileId)); - } - - public OpenAiResponse listMessageFiles(String threadId, String messageId) { - return execute(api.listMessageFiles(threadId, messageId)); - } - - public OpenAiResponse listMessageFiles(String threadId, String messageId, ListSearchParameters params) { - Map queryParameters = mapper.convertValue(params, new TypeReference>() { - }); - return execute(api.listMessageFiles(threadId, messageId, queryParameters)); - } - - public Run createRun(String threadId, RunCreateRequest runCreateRequest) { - return execute(api.createRun(threadId, runCreateRequest)); - } - - public Run retrieveRun(String threadId, String runId) { - return execute(api.retrieveRun(threadId, runId)); - } - - public Run modifyRun(String threadId, String runId, Map metadata) { - return execute(api.modifyRun(threadId, runId, metadata)); - } - - public OpenAiResponse listRuns(String threadId, ListSearchParameters listSearchParameters) { - Map search = new HashMap<>(); - if (listSearchParameters != null) { - ObjectMapper mapper = defaultObjectMapper(); - search = mapper.convertValue(listSearchParameters, Map.class); - } - return execute(api.listRuns(threadId, search)); - } - - public Run submitToolOutputs(String threadId, String runId, SubmitToolOutputsRequest submitToolOutputsRequest) { - return execute(api.submitToolOutputs(threadId, runId, submitToolOutputsRequest)); - } - - public Run cancelRun(String threadId, String runId) { - return execute(api.cancelRun(threadId, runId)); - } - - public Run createThreadAndRun(CreateThreadAndRunRequest createThreadAndRunRequest) { - return execute(api.createThreadAndRun(createThreadAndRunRequest)); - } - - public RunStep retrieveRunStep(String threadId, String runId, String stepId) { - return execute(api.retrieveRunStep(threadId, runId, stepId)); - } - - public OpenAiResponse listRunSteps(String threadId, String runId, ListSearchParameters listSearchParameters) { - Map search = new HashMap<>(); - if (listSearchParameters != null) { - ObjectMapper mapper = defaultObjectMapper(); - search = mapper.convertValue(listSearchParameters, Map.class); - } - return execute(api.listRunSteps(threadId, runId, search)); - } - - /** - * Calls the Open AI api, returns the response, and parses error messages if the request fails - */ - public static T execute(Single apiCall) { - try { - return apiCall.blockingGet(); - } catch (HttpException e) { - try { - if (e.response() == null || e.response().errorBody() == null) { - throw e; - } - String errorBody = e.response().errorBody().string(); - - OpenAiError error = mapper.readValue(errorBody, OpenAiError.class); - throw new OpenAiHttpException(error, e, e.code()); - } catch (IOException ex) { - // couldn't parse OpenAI error - throw e; - } - } - } - - /** - * Calls the Open AI api and returns a Flowable of SSE for streaming - * omitting the last message. - * - * @param apiCall The api call - */ - public static Flowable stream(Call apiCall) { - return stream(apiCall, false); - } - - /** - * Calls the Open AI api and returns a Flowable of SSE for streaming. - * - * @param apiCall The api call - * @param emitDone If true the last message ([DONE]) is emitted - */ - public static Flowable stream(Call apiCall, boolean emitDone) { - return Flowable.create(emitter -> apiCall.enqueue(new ResponseBodyCallback(emitter, emitDone)), BackpressureStrategy.BUFFER); - } - - /** - * Calls the Open AI api and returns a Flowable of type T for streaming - * omitting the last message. - * - * @param apiCall The api call - * @param cl Class of type T to return - */ - public static Flowable stream(Call apiCall, Class cl) { - return stream(apiCall).map(sse -> mapper.readValue(sse.getData(), cl)); - } - - /** - * Shuts down the OkHttp ExecutorService. - * The default behaviour of OkHttp's ExecutorService (ConnectionPool) - * is to shut down after an idle timeout of 60s. - * Call this method to shut down the ExecutorService immediately. - */ - public void shutdownExecutor() { - Objects.requireNonNull(this.executorService, "executorService must be set in order to shut down"); - this.executorService.shutdown(); - } - - public static OpenAiApi buildApi(String token, Duration timeout) { - ObjectMapper mapper = defaultObjectMapper(); - OkHttpClient client = defaultClient(token, timeout); - Retrofit retrofit = defaultRetrofit(client, mapper); - - return retrofit.create(OpenAiApi.class); - } - - public static ObjectMapper defaultObjectMapper() { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); - mapper.addMixIn(ChatFunction.class, ChatFunctionMixIn.class); - mapper.addMixIn(ChatCompletionRequest.class, ChatCompletionRequestMixIn.class); - mapper.addMixIn(ChatFunctionCall.class, ChatFunctionCallMixIn.class); - return mapper; - } - - public static OkHttpClient defaultClient(String token, Duration timeout) { - return new OkHttpClient.Builder() - .addInterceptor(new AuthenticationInterceptor(token)) - .connectionPool(new ConnectionPool(5, 1, TimeUnit.SECONDS)) - .readTimeout(timeout.toMillis(), TimeUnit.MILLISECONDS) - .build(); - } - - public static Retrofit defaultRetrofit(OkHttpClient client, ObjectMapper mapper) { - return new Retrofit.Builder() - .baseUrl(BASE_URL) - .client(client) - .addConverterFactory(JacksonConverterFactory.create(mapper)) - .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) - .build(); - } - - public Flowable mapStreamToAccumulator(Flowable flowable) { - ChatFunctionCall functionCall = new ChatFunctionCall(null, null); - ChatMessage accumulatedMessage = new ChatMessage(ChatMessageRole.ASSISTANT.value(), null); - - return flowable.map(chunk -> { - ChatMessage messageChunk = chunk.getChoices().get(0).getMessage(); - if (messageChunk.getFunctionCall() != null) { - if (messageChunk.getFunctionCall().getName() != null) { - String namePart = messageChunk.getFunctionCall().getName(); - functionCall.setName((functionCall.getName() == null ? "" : functionCall.getName()) + namePart); - } - if (messageChunk.getFunctionCall().getArguments() != null) { - String argumentsPart = messageChunk.getFunctionCall().getArguments() == null ? "" : messageChunk.getFunctionCall().getArguments().asText(); - functionCall.setArguments(new TextNode((functionCall.getArguments() == null ? "" : functionCall.getArguments().asText()) + argumentsPart)); - } - accumulatedMessage.setFunctionCall(functionCall); - } else { - accumulatedMessage.setContent((accumulatedMessage.getContent() == null ? "" : accumulatedMessage.getContent()) + (messageChunk.getContent() == null ? "" : messageChunk.getContent())); - } - - if (chunk.getChoices().get(0).getFinishReason() != null) { // last - if (functionCall.getArguments() != null) { - functionCall.setArguments(mapper.readTree(functionCall.getArguments().asText())); - accumulatedMessage.setFunctionCall(functionCall); - } - } - - return new ChatMessageAccumulator(messageChunk, accumulatedMessage); - }); - } - - /** - * Account information inquiry: including total amount and other information. - * - * @return Account information. - */ - public Subscription subscription() { - Single subscription = api.subscription(); - return subscription.blockingGet(); - } - - /** - * Account API consumption amount information inquiry. - * Up to 100 days of inquiry. - * - * @param starDate - * @param endDate - * @return Consumption amount information. - */ - public BillingUsage billingUsage(@NotNull LocalDate starDate, @NotNull LocalDate endDate) { - Single billingUsage = api.billingUsage(starDate, endDate); - return billingUsage.blockingGet(); - } + private static final String BASE_URL = "https://api.openai.com/"; + private static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(10); + private static final ObjectMapper mapper = defaultObjectMapper(); + + private final OpenAiApi api; + private final ExecutorService executorService; + + /** + * Creates a new OpenAiService that wraps OpenAiApi + * + * @param token OpenAi token string "sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + */ + public OpenAiService(final String token) { + this(token, DEFAULT_TIMEOUT); + } + + /** + * Creates a new OpenAiService that wraps OpenAiApi + * + * @param token OpenAi token string "sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + * @param timeout http read timeout, Duration.ZERO means no timeout + */ + public OpenAiService(final String token, final Duration timeout) { + ObjectMapper mapper = defaultObjectMapper(); + OkHttpClient client = defaultClient(token, timeout); + Retrofit retrofit = defaultRetrofit(client, mapper); + + this.api = retrofit.create(OpenAiApi.class); + this.executorService = client.dispatcher().executorService(); + } + + /** + * Creates a new OpenAiService that wraps OpenAiApi. Use this if you need more customization, but + * use OpenAiService(api, executorService) if you use streaming and want to shut down instantly + * + * @param api OpenAiApi instance to use for all methods + */ + public OpenAiService(final OpenAiApi api) { + this.api = api; + this.executorService = null; + } + + /** + * Creates a new OpenAiService that wraps OpenAiApi. The ExecutorService must be the one you get + * from the client you created the api with otherwise shutdownExecutor() won't work. + *

+ * Use this if you need more customization. + * + * @param api OpenAiApi instance to use for all methods + * @param executorService the ExecutorService from client.dispatcher().executorService() + */ + public OpenAiService(final OpenAiApi api, final ExecutorService executorService) { + this.api = api; + this.executorService = executorService; + } + + public List listModels() { + return execute(api.listModels()).data; + } + + public Model getModel(String modelId) { + return execute(api.getModel(modelId)); + } + + public CompletionResult createCompletion(CompletionRequest request) { + return execute(api.createCompletion(request)); + } + + public Flowable streamCompletion(CompletionRequest request) { + request.setStream(true); + + return stream(api.createCompletionStream(request), CompletionChunk.class); + } + + public ChatCompletionResult createChatCompletion(ChatCompletionRequest request) { + return execute(api.createChatCompletion(request)); + } + + public Flowable streamChatCompletion(ChatCompletionRequest request) { + request.setStream(true); + + return stream(api.createChatCompletionStream(request), ChatCompletionChunk.class); + } + + public EditResult createEdit(EditRequest request) { + return execute(api.createEdit(request)); + } + + public EmbeddingResult createEmbeddings(EmbeddingRequest request) { + return execute(api.createEmbeddings(request)); + } + + public List listFiles() { + return execute(api.listFiles()).data; + } + + public File uploadFile(String purpose, String filepath) { + java.io.File file = new java.io.File(filepath); + RequestBody purposeBody = RequestBody.create(MultipartBody.FORM, purpose); + RequestBody fileBody = RequestBody.create(MediaType.parse("text"), file); + MultipartBody.Part body = MultipartBody.Part.createFormData("file", filepath, fileBody); + + return execute(api.uploadFile(purposeBody, body)); + } + + public DeleteResult deleteFile(String fileId) { + return execute(api.deleteFile(fileId)); + } + + public File retrieveFile(String fileId) { + return execute(api.retrieveFile(fileId)); + } + + public ResponseBody retrieveFileContent(String fileId) { + return execute(api.retrieveFileContent(fileId)); + } + + public FineTuningJob createFineTuningJob(FineTuningJobRequest request) { + return execute(api.createFineTuningJob(request)); + } + + public List listFineTuningJobs() { + return execute(api.listFineTuningJobs()).data; + } + + public FineTuningJob retrieveFineTuningJob(String fineTuningJobId) { + return execute(api.retrieveFineTuningJob(fineTuningJobId)); + } + + public FineTuningJob cancelFineTuningJob(String fineTuningJobId) { + return execute(api.cancelFineTuningJob(fineTuningJobId)); + } + + public List listFineTuningJobEvents(String fineTuningJobId) { + return execute(api.listFineTuningJobEvents(fineTuningJobId)).data; + } + + @Deprecated + public FineTuneResult createFineTune(FineTuneRequest request) { + return execute(api.createFineTune(request)); + } + + public CompletionResult createFineTuneCompletion(CompletionRequest request) { + return execute(api.createFineTuneCompletion(request)); + } + + @Deprecated + public List listFineTunes() { + return execute(api.listFineTunes()).data; + } + + @Deprecated + public FineTuneResult retrieveFineTune(String fineTuneId) { + return execute(api.retrieveFineTune(fineTuneId)); + } + + @Deprecated + public FineTuneResult cancelFineTune(String fineTuneId) { + return execute(api.cancelFineTune(fineTuneId)); + } + + @Deprecated + public List listFineTuneEvents(String fineTuneId) { + return execute(api.listFineTuneEvents(fineTuneId)).data; + } + + public DeleteResult deleteFineTune(String fineTuneId) { + return execute(api.deleteFineTune(fineTuneId)); + } + + public ImageResult createImage(CreateImageRequest request) { + return execute(api.createImage(request)); + } + + public ImageResult createImageEdit(CreateImageEditRequest request, String imagePath, + String maskPath) { + java.io.File image = new java.io.File(imagePath); + java.io.File mask = null; + if (maskPath != null) { + mask = new java.io.File(maskPath); + } + return createImageEdit(request, image, mask); + } + + public ImageResult createImageEdit(CreateImageEditRequest request, java.io.File image, + java.io.File mask) { + RequestBody imageBody = RequestBody.create(MediaType.parse("image"), image); + + MultipartBody.Builder builder = new MultipartBody.Builder() + .setType(MediaType.get("multipart/form-data")) + .addFormDataPart("prompt", request.getPrompt()) + .addFormDataPart("size", request.getSize()) + .addFormDataPart("response_format", request.getResponseFormat()) + .addFormDataPart("image", "image", imageBody); + + if (request.getN() != null) { + builder.addFormDataPart("n", request.getN().toString()); + } + + if (mask != null) { + RequestBody maskBody = RequestBody.create(MediaType.parse("image"), mask); + builder.addFormDataPart("mask", "mask", maskBody); + } + + if (request.getModel() != null) { + builder.addFormDataPart("model", request.getModel()); + } + + return execute(api.createImageEdit(builder.build())); + } + + public ImageResult createImageVariation(CreateImageVariationRequest request, String imagePath) { + java.io.File image = new java.io.File(imagePath); + return createImageVariation(request, image); + } + + public ImageResult createImageVariation(CreateImageVariationRequest request, java.io.File image) { + RequestBody imageBody = RequestBody.create(MediaType.parse("image"), image); + + MultipartBody.Builder builder = new MultipartBody.Builder() + .setType(MediaType.get("multipart/form-data")) + .addFormDataPart("size", request.getSize()) + .addFormDataPart("response_format", request.getResponseFormat()) + .addFormDataPart("image", "image", imageBody); + + if (request.getN() != null) { + builder.addFormDataPart("n", request.getN().toString()); + } + + if (request.getModel() != null) { + builder.addFormDataPart("model", request.getModel()); + } + + return execute(api.createImageVariation(builder.build())); + } + + public TranscriptionResult createTranscription(CreateTranscriptionRequest request, + String audioPath) { + java.io.File audio = new java.io.File(audioPath); + return createTranscription(request, audio); + } + + public TranscriptionResult createTranscription(CreateTranscriptionRequest request, + java.io.File audio) { + RequestBody audioBody = RequestBody.create(MediaType.parse("audio"), audio); + + MultipartBody.Builder builder = new MultipartBody.Builder() + .setType(MediaType.get("multipart/form-data")) + .addFormDataPart("model", request.getModel()) + .addFormDataPart("file", audio.getName(), audioBody); + + if (request.getPrompt() != null) { + builder.addFormDataPart("prompt", request.getPrompt()); + } + if (request.getResponseFormat() != null) { + builder.addFormDataPart("response_format", request.getResponseFormat()); + } + if (request.getTemperature() != null) { + builder.addFormDataPart("temperature", request.getTemperature().toString()); + } + if (request.getLanguage() != null) { + builder.addFormDataPart("language", request.getLanguage()); + } + + return execute(api.createTranscription(builder.build())); + } + + public TranslationResult createTranslation(CreateTranslationRequest request, String audioPath) { + java.io.File audio = new java.io.File(audioPath); + return createTranslation(request, audio); + } + + public TranslationResult createTranslation(CreateTranslationRequest request, java.io.File audio) { + RequestBody audioBody = RequestBody.create(MediaType.parse("audio"), audio); + + MultipartBody.Builder builder = new MultipartBody.Builder() + .setType(MediaType.get("multipart/form-data")) + .addFormDataPart("model", request.getModel()) + .addFormDataPart("file", audio.getName(), audioBody); + + if (request.getPrompt() != null) { + builder.addFormDataPart("prompt", request.getPrompt()); + } + if (request.getResponseFormat() != null) { + builder.addFormDataPart("response_format", request.getResponseFormat()); + } + if (request.getTemperature() != null) { + builder.addFormDataPart("temperature", request.getTemperature().toString()); + } + + return execute(api.createTranslation(builder.build())); + } + + public ModerationResult createModeration(ModerationRequest request) { + return execute(api.createModeration(request)); + } + + public ResponseBody createSpeech(CreateSpeechRequest request) { + return execute(api.createSpeech(request)); + } + + public Assistant createAssistant(AssistantRequest request) { + return execute(api.createAssistant(request)); + } + + public Assistant retrieveAssistant(String assistantId) { + return execute(api.retrieveAssistant(assistantId)); + } + + public Assistant modifyAssistant(String assistantId, ModifyAssistantRequest request) { + return execute(api.modifyAssistant(assistantId, request)); + } + + public DeleteResult deleteAssistant(String assistantId) { + return execute(api.deleteAssistant(assistantId)); + } + + public OpenAiResponse listAssistants(ListSearchParameters params) { + Map queryParameters = mapper.convertValue(params, + new TypeReference>() { + }); + return execute(api.listAssistants(queryParameters)); + } + + public AssistantFile createAssistantFile(String assistantId, AssistantFileRequest fileRequest) { + return execute(api.createAssistantFile(assistantId, fileRequest)); + } + + public AssistantFile retrieveAssistantFile(String assistantId, String fileId) { + return execute(api.retrieveAssistantFile(assistantId, fileId)); + } + + public DeleteResult deleteAssistantFile(String assistantId, String fileId) { + return execute(api.deleteAssistantFile(assistantId, fileId)); + } + + public OpenAiResponse listAssistantFiles(String assistantId, + ListSearchParameters params) { + Map queryParameters = mapper.convertValue(params, + new TypeReference>() { + }); + return execute(api.listAssistantFiles(assistantId, queryParameters)); + } + + public Thread createThread(ThreadRequest request) { + return execute(api.createThread(request)); + } + + public Thread retrieveThread(String threadId) { + return execute(api.retrieveThread(threadId)); + } + + public Thread modifyThread(String threadId, ThreadRequest request) { + return execute(api.modifyThread(threadId, request)); + } + + public DeleteResult deleteThread(String threadId) { + return execute(api.deleteThread(threadId)); + } + + public Message createMessage(String threadId, MessageRequest request) { + return execute(api.createMessage(threadId, request)); + } + + public Message retrieveMessage(String threadId, String messageId) { + return execute(api.retrieveMessage(threadId, messageId)); + } + + public Message modifyMessage(String threadId, String messageId, ModifyMessageRequest request) { + return execute(api.modifyMessage(threadId, messageId, request)); + } + + public OpenAiResponse listMessages(String threadId) { + return execute(api.listMessages(threadId)); + } + + public OpenAiResponse listMessages(String threadId, ListSearchParameters params) { + Map queryParameters = mapper.convertValue(params, + new TypeReference>() { + }); + return execute(api.listMessages(threadId, queryParameters)); + } + + public MessageFile retrieveMessageFile(String threadId, String messageId, String fileId) { + return execute(api.retrieveMessageFile(threadId, messageId, fileId)); + } + + public OpenAiResponse listMessageFiles(String threadId, String messageId) { + return execute(api.listMessageFiles(threadId, messageId)); + } + + public OpenAiResponse listMessageFiles(String threadId, String messageId, + ListSearchParameters params) { + Map queryParameters = mapper.convertValue(params, + new TypeReference>() { + }); + return execute(api.listMessageFiles(threadId, messageId, queryParameters)); + } + + public Run createRun(String threadId, RunCreateRequest runCreateRequest) { + return execute(api.createRun(threadId, runCreateRequest)); + } + + public Run retrieveRun(String threadId, String runId) { + return execute(api.retrieveRun(threadId, runId)); + } + + public Run modifyRun(String threadId, String runId, Map metadata) { + return execute(api.modifyRun(threadId, runId, metadata)); + } + + public OpenAiResponse listRuns(String threadId, ListSearchParameters listSearchParameters) { + Map search = new HashMap<>(); + if (listSearchParameters != null) { + ObjectMapper mapper = defaultObjectMapper(); + search = mapper.convertValue(listSearchParameters, Map.class); + } + return execute(api.listRuns(threadId, search)); + } + + public Run submitToolOutputs(String threadId, String runId, + SubmitToolOutputsRequest submitToolOutputsRequest) { + return execute(api.submitToolOutputs(threadId, runId, submitToolOutputsRequest)); + } + + public Run cancelRun(String threadId, String runId) { + return execute(api.cancelRun(threadId, runId)); + } + + public Run createThreadAndRun(CreateThreadAndRunRequest createThreadAndRunRequest) { + return execute(api.createThreadAndRun(createThreadAndRunRequest)); + } + + public RunStep retrieveRunStep(String threadId, String runId, String stepId) { + return execute(api.retrieveRunStep(threadId, runId, stepId)); + } + + public OpenAiResponse listRunSteps(String threadId, String runId, + ListSearchParameters listSearchParameters) { + Map search = new HashMap<>(); + if (listSearchParameters != null) { + ObjectMapper mapper = defaultObjectMapper(); + search = mapper.convertValue(listSearchParameters, Map.class); + } + return execute(api.listRunSteps(threadId, runId, search)); + } + + /** + * Calls the Open AI api, returns the response, and parses error messages if the request fails + */ + public static T execute(Single apiCall) { + try { + return apiCall.blockingGet(); + } catch (HttpException e) { + try { + if (e.response() == null || e.response().errorBody() == null) { + throw e; + } + String errorBody = e.response().errorBody().string(); + + OpenAiError error = mapper.readValue(errorBody, OpenAiError.class); + throw new OpenAiHttpException(error, e, e.code()); + } catch (IOException ex) { + // couldn't parse OpenAI error + throw e; + } + } + } + + /** + * Calls the Open AI api and returns a Flowable of SSE for streaming omitting the last message. + * + * @param apiCall The api call + */ + public static Flowable stream(Call apiCall) { + return stream(apiCall, false); + } + + /** + * Calls the Open AI api and returns a Flowable of SSE for streaming. + * + * @param apiCall The api call + * @param emitDone If true the last message ([DONE]) is emitted + */ + public static Flowable stream(Call apiCall, boolean emitDone) { + return Flowable.create(emitter -> apiCall.enqueue(new ResponseBodyCallback(emitter, emitDone)), + BackpressureStrategy.BUFFER); + } + + /** + * Calls the Open AI api and returns a Flowable of type T for streaming omitting the last + * message. + * + * @param apiCall The api call + * @param cl Class of type T to return + */ + public static Flowable stream(Call apiCall, Class cl) { + return stream(apiCall).map(sse -> mapper.readValue(sse.getData(), cl)); + } + + /** + * Shuts down the OkHttp ExecutorService. The default behaviour of OkHttp's ExecutorService + * (ConnectionPool) is to shut down after an idle timeout of 60s. Call this method to shut down + * the ExecutorService immediately. + */ + public void shutdownExecutor() { + Objects.requireNonNull(this.executorService, + "executorService must be set in order to shut down"); + this.executorService.shutdown(); + } + + public static OpenAiApi buildApi(String token, Duration timeout) { + ObjectMapper mapper = defaultObjectMapper(); + OkHttpClient client = defaultClient(token, timeout); + Retrofit retrofit = defaultRetrofit(client, mapper); + + return retrofit.create(OpenAiApi.class); + } + + public static ObjectMapper defaultObjectMapper() { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); + mapper.addMixIn(ChatFunction.class, ChatFunctionMixIn.class); + mapper.addMixIn(ChatCompletionRequest.class, ChatCompletionRequestMixIn.class); + mapper.addMixIn(ChatFunctionCall.class, ChatFunctionCallMixIn.class); + return mapper; + } + + public static OkHttpClient defaultClient(String token, Duration timeout) { + return new OkHttpClient.Builder() + .addInterceptor(new AuthenticationInterceptor(token)) + .connectionPool(new ConnectionPool(5, 1, TimeUnit.SECONDS)) + .readTimeout(timeout.toMillis(), TimeUnit.MILLISECONDS) + .build(); + } + + public static Retrofit defaultRetrofit(OkHttpClient client, ObjectMapper mapper) { + return new Retrofit.Builder() + .baseUrl(BASE_URL) + .client(client) + .addConverterFactory(JacksonConverterFactory.create(mapper)) + .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) + .build(); + } + + public Flowable mapStreamToAccumulator( + Flowable flowable) { + ChatFunctionCall functionCall = new ChatFunctionCall(null, null); + ChatMessage accumulatedMessage = new ChatMessage(ChatMessageRole.ASSISTANT.value(), null); + + return flowable.map(chunk -> { + ChatMessage messageChunk = chunk.getChoices().get(0).getMessage(); + if (messageChunk.getFunctionCall() != null) { + if (messageChunk.getFunctionCall().getName() != null) { + String namePart = messageChunk.getFunctionCall().getName(); + functionCall.setName( + (functionCall.getName() == null ? "" : functionCall.getName()) + namePart); + } + if (messageChunk.getFunctionCall().getArguments() != null) { + String argumentsPart = messageChunk.getFunctionCall().getArguments() == null ? "" + : messageChunk.getFunctionCall().getArguments().asText(); + functionCall.setArguments(new TextNode( + (functionCall.getArguments() == null ? "" : functionCall.getArguments().asText()) + + argumentsPart)); + } + accumulatedMessage.setFunctionCall(functionCall); + } else { + accumulatedMessage.setContent( + (accumulatedMessage.getContent() == null ? "" : accumulatedMessage.getContent()) + ( + messageChunk.getContent() == null ? "" : messageChunk.getContent())); + } + + if (chunk.getChoices().get(0).getFinishReason() != null) { // last + if (functionCall.getArguments() != null) { + functionCall.setArguments(mapper.readTree(functionCall.getArguments().asText())); + accumulatedMessage.setFunctionCall(functionCall); + } + } + + return new ChatMessageAccumulator(messageChunk, accumulatedMessage); + }); + } + + /** + * Account information inquiry: including total amount and other information. + * + * @return Account information. + */ + public Subscription subscription() { + Single subscription = api.subscription(); + return subscription.blockingGet(); + } + + /** + * Account API consumption amount information inquiry. Up to 100 days of inquiry. + * + * @param starDate + * @param endDate + * @return Consumption amount information. + */ + public BillingUsage billingUsage(@NotNull LocalDate starDate, @NotNull LocalDate endDate) { + Single billingUsage = api.billingUsage(starDate, endDate); + return billingUsage.blockingGet(); + } } diff --git a/service/src/main/java/com/launchableinc/openai/service/ResponseBodyCallback.java b/service/src/main/java/com/launchableinc/openai/service/ResponseBodyCallback.java index c5404e0f..145ed360 100644 --- a/service/src/main/java/com/launchableinc/openai/service/ResponseBodyCallback.java +++ b/service/src/main/java/com/launchableinc/openai/service/ResponseBodyCallback.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.service; +package com.launchableinc.openai.service; import java.io.BufferedReader; import java.io.IOException; @@ -7,8 +7,8 @@ import java.nio.charset.StandardCharsets; import com.fasterxml.jackson.databind.ObjectMapper; -import com.theokanning.openai.OpenAiError; -import com.theokanning.openai.OpenAiHttpException; +import com.launchableinc.openai.OpenAiError; +import com.launchableinc.openai.OpenAiHttpException; import io.reactivex.FlowableEmitter; @@ -19,82 +19,82 @@ import retrofit2.Response; /** - * Callback to parse Server Sent Events (SSE) from raw InputStream and - * emit the events with io.reactivex.FlowableEmitter to allow streaming of - * SSE. + * Callback to parse Server Sent Events (SSE) from raw InputStream and emit the events with + * io.reactivex.FlowableEmitter to allow streaming of SSE. */ public class ResponseBodyCallback implements Callback { - private static final ObjectMapper mapper = OpenAiService.defaultObjectMapper(); - - private FlowableEmitter emitter; - private boolean emitDone; - - public ResponseBodyCallback(FlowableEmitter emitter, boolean emitDone) { - this.emitter = emitter; - this.emitDone = emitDone; - } - - @Override - public void onResponse(Call call, Response response) { - BufferedReader reader = null; - - try { - if (!response.isSuccessful()) { - HttpException e = new HttpException(response); - ResponseBody errorBody = response.errorBody(); - - if (errorBody == null) { - throw e; - } else { - OpenAiError error = mapper.readValue( - errorBody.string(), - OpenAiError.class - ); - throw new OpenAiHttpException(error, e, e.code()); - } - } - - InputStream in = response.body().byteStream(); - reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)); - String line; - SSE sse = null; - - while (!emitter.isCancelled() && (line = reader.readLine()) != null) { - if (line.startsWith("data:")) { - String data = line.substring(5).trim(); - sse = new SSE(data); - } else if (line.equals("") && sse != null) { - if (sse.isDone()) { - if (emitDone) { - emitter.onNext(sse); - } - break; - } - - emitter.onNext(sse); - sse = null; - } else { - throw new SSEFormatException("Invalid sse format! " + line); - } - } - - emitter.onComplete(); - - } catch (Throwable t) { - onFailure(call, t); - } finally { - if (reader != null) { - try { - reader.close(); - } catch (IOException e) { - // do nothing - } - } - } - } - - @Override - public void onFailure(Call call, Throwable t) { - emitter.onError(t); - } + + private static final ObjectMapper mapper = OpenAiService.defaultObjectMapper(); + + private FlowableEmitter emitter; + private boolean emitDone; + + public ResponseBodyCallback(FlowableEmitter emitter, boolean emitDone) { + this.emitter = emitter; + this.emitDone = emitDone; + } + + @Override + public void onResponse(Call call, Response response) { + BufferedReader reader = null; + + try { + if (!response.isSuccessful()) { + HttpException e = new HttpException(response); + ResponseBody errorBody = response.errorBody(); + + if (errorBody == null) { + throw e; + } else { + OpenAiError error = mapper.readValue( + errorBody.string(), + OpenAiError.class + ); + throw new OpenAiHttpException(error, e, e.code()); + } + } + + InputStream in = response.body().byteStream(); + reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)); + String line; + SSE sse = null; + + while (!emitter.isCancelled() && (line = reader.readLine()) != null) { + if (line.startsWith("data:")) { + String data = line.substring(5).trim(); + sse = new SSE(data); + } else if (line.equals("") && sse != null) { + if (sse.isDone()) { + if (emitDone) { + emitter.onNext(sse); + } + break; + } + + emitter.onNext(sse); + sse = null; + } else { + throw new SSEFormatException("Invalid sse format! " + line); + } + } + + emitter.onComplete(); + + } catch (Throwable t) { + onFailure(call, t); + } finally { + if (reader != null) { + try { + reader.close(); + } catch (IOException e) { + // do nothing + } + } + } + } + + @Override + public void onFailure(Call call, Throwable t) { + emitter.onError(t); + } } diff --git a/service/src/main/java/com/launchableinc/openai/service/SSE.java b/service/src/main/java/com/launchableinc/openai/service/SSE.java index c3024fac..ace0faf3 100644 --- a/service/src/main/java/com/launchableinc/openai/service/SSE.java +++ b/service/src/main/java/com/launchableinc/openai/service/SSE.java @@ -1,26 +1,27 @@ -package com.theokanning.openai.service; +package com.launchableinc.openai.service; /** * Simple Server Sent Event representation */ public class SSE { - private static final String DONE_DATA = "[DONE]"; - - private final String data; - public SSE(String data){ - this.data = data; - } + private static final String DONE_DATA = "[DONE]"; - public String getData(){ - return this.data; - } + private final String data; - public byte[] toBytes(){ - return String.format("data: %s\n\n", this.data).getBytes(); - } + public SSE(String data) { + this.data = data; + } - public boolean isDone(){ - return DONE_DATA.equalsIgnoreCase(this.data); - } + public String getData() { + return this.data; + } + + public byte[] toBytes() { + return String.format("data: %s\n\n", this.data).getBytes(); + } + + public boolean isDone() { + return DONE_DATA.equalsIgnoreCase(this.data); + } } \ No newline at end of file diff --git a/service/src/main/java/com/launchableinc/openai/service/SSEFormatException.java b/service/src/main/java/com/launchableinc/openai/service/SSEFormatException.java index f99aeaf3..bfaf35b4 100644 --- a/service/src/main/java/com/launchableinc/openai/service/SSEFormatException.java +++ b/service/src/main/java/com/launchableinc/openai/service/SSEFormatException.java @@ -1,10 +1,11 @@ -package com.theokanning.openai.service; +package com.launchableinc.openai.service; /** * Exception indicating a SSE format error */ -public class SSEFormatException extends Throwable{ - public SSEFormatException(String msg){ +public class SSEFormatException extends Throwable { + + public SSEFormatException(String msg) { super(msg); } } \ No newline at end of file diff --git a/service/src/test/java/com/launchableinc/openai/service/AssistantFunctionTest.java b/service/src/test/java/com/launchableinc/openai/service/AssistantFunctionTest.java index 9ad819a7..1c21dd01 100644 --- a/service/src/test/java/com/launchableinc/openai/service/AssistantFunctionTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/AssistantFunctionTest.java @@ -1,4 +1,4 @@ -package com.theokanning.openai.service; +package com.launchableinc.openai.service; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; @@ -6,143 +6,142 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; -import com.theokanning.openai.ListSearchParameters; -import com.theokanning.openai.OpenAiResponse; -import com.theokanning.openai.assistants.Assistant; -import com.theokanning.openai.assistants.AssistantFunction; -import com.theokanning.openai.assistants.AssistantRequest; -import com.theokanning.openai.assistants.AssistantToolsEnum; -import com.theokanning.openai.assistants.Tool; -import com.theokanning.openai.completion.chat.ChatCompletionRequest; -import com.theokanning.openai.completion.chat.ChatFunction; -import com.theokanning.openai.completion.chat.ChatFunctionCall; -import com.theokanning.openai.messages.Message; -import com.theokanning.openai.messages.MessageRequest; -import com.theokanning.openai.runs.RequiredAction; -import com.theokanning.openai.runs.Run; -import com.theokanning.openai.runs.RunCreateRequest; -import com.theokanning.openai.runs.RunStep; -import com.theokanning.openai.runs.SubmitToolOutputRequestItem; -import com.theokanning.openai.runs.SubmitToolOutputs; -import com.theokanning.openai.runs.SubmitToolOutputsRequest; -import com.theokanning.openai.runs.ToolCall; -import com.theokanning.openai.threads.Thread; -import com.theokanning.openai.threads.ThreadRequest; -import com.theokanning.openai.utils.TikTokensUtil; +import com.launchableinc.openai.OpenAiResponse; +import com.launchableinc.openai.assistants.Assistant; +import com.launchableinc.openai.assistants.AssistantFunction; +import com.launchableinc.openai.assistants.AssistantRequest; +import com.launchableinc.openai.assistants.AssistantToolsEnum; +import com.launchableinc.openai.assistants.Tool; +import com.launchableinc.openai.completion.chat.ChatCompletionRequest; +import com.launchableinc.openai.completion.chat.ChatFunction; +import com.launchableinc.openai.completion.chat.ChatFunctionCall; +import com.launchableinc.openai.messages.Message; +import com.launchableinc.openai.messages.MessageRequest; +import com.launchableinc.openai.runs.RequiredAction; +import com.launchableinc.openai.runs.Run; +import com.launchableinc.openai.runs.RunCreateRequest; +import com.launchableinc.openai.runs.SubmitToolOutputRequestItem; +import com.launchableinc.openai.runs.SubmitToolOutputsRequest; +import com.launchableinc.openai.runs.ToolCall; +import com.launchableinc.openai.threads.Thread; +import com.launchableinc.openai.threads.ThreadRequest; +import com.launchableinc.openai.utils.TikTokensUtil; import org.junit.jupiter.api.Test; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Map; -import java.util.Objects; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; class AssistantFunctionTest { - String token = System.getenv("OPENAI_TOKEN"); - OpenAiService service = new OpenAiService(token, Duration.ofMinutes(1)); - - @Test - void createRetrieveRun() throws JsonProcessingException { - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); - mapper.addMixIn(ChatFunction.class, ChatFunctionMixIn.class); - mapper.addMixIn(ChatCompletionRequest.class, ChatCompletionRequestMixIn.class); - mapper.addMixIn(ChatFunctionCall.class, ChatFunctionCallMixIn.class); - - String funcDef = "{\n" + - " \"type\": \"object\",\n" + - " \"properties\": {\n" + - " \"location\": {\n" + - " \"type\": \"string\",\n" + - " \"description\": \"The city and state, e.g. San Francisco, CA\"\n" + - " },\n" + - " \"unit\": {\n" + - " \"type\": \"string\",\n" + - " \"enum\": [\"celsius\", \"fahrenheit\"]\n" + - " }\n" + - " },\n" + - " \"required\": [\"location\"]\n" + - "}"; - Map funcParameters = mapper.readValue(funcDef, new TypeReference>() {}); - AssistantFunction function = AssistantFunction.builder() - .name("weather_reporter") - .description("Get the current weather of a location") - .parameters(funcParameters) - .build(); - - List toolList = new ArrayList<>(); - Tool funcTool = new Tool(AssistantToolsEnum.FUNCTION, function); - toolList.add(funcTool); - - - AssistantRequest assistantRequest = AssistantRequest.builder() - .model(TikTokensUtil.ModelEnum.GPT_4_1106_preview.getName()) - .name("MATH_TUTOR") - .instructions("You are a personal Math Tutor.") - .tools(toolList) - .build(); - Assistant assistant = service.createAssistant(assistantRequest); - - ThreadRequest threadRequest = ThreadRequest.builder() - .build(); - Thread thread = service.createThread(threadRequest); - - MessageRequest messageRequest = MessageRequest.builder() - .content("What's the weather of Xiamen?") - .build(); - - Message message = service.createMessage(thread.getId(), messageRequest); - - RunCreateRequest runCreateRequest = RunCreateRequest.builder() - .assistantId(assistant.getId()) - .build(); - - Run run = service.createRun(thread.getId(), runCreateRequest); - assertNotNull(run); - - Run retrievedRun = service.retrieveRun(thread.getId(), run.getId()); - while (!(retrievedRun.getStatus().equals("completed")) - && !(retrievedRun.getStatus().equals("failed")) - && !(retrievedRun.getStatus().equals("requires_action"))){ - retrievedRun = service.retrieveRun(thread.getId(), run.getId()); - } - if (retrievedRun.getStatus().equals("requires_action")) { - RequiredAction requiredAction = retrievedRun.getRequiredAction(); - System.out.println("requiredAction"); - System.out.println(mapper.writeValueAsString(requiredAction)); - List toolCalls = requiredAction.getSubmitToolOutputs().getToolCalls(); - ToolCall toolCall = toolCalls.get(0); - String toolCallId = toolCall.getId(); - - SubmitToolOutputRequestItem toolOutputRequestItem = SubmitToolOutputRequestItem.builder() - .toolCallId(toolCallId) - .output("sunny") - .build(); - List toolOutputRequestItems = new ArrayList<>(); - toolOutputRequestItems.add(toolOutputRequestItem); - SubmitToolOutputsRequest submitToolOutputsRequest = SubmitToolOutputsRequest.builder() - .toolOutputs(toolOutputRequestItems) - .build(); - retrievedRun = service.submitToolOutputs(retrievedRun.getThreadId(), retrievedRun.getId(), submitToolOutputsRequest); - - while (!(retrievedRun.getStatus().equals("completed")) - && !(retrievedRun.getStatus().equals("failed")) - && !(retrievedRun.getStatus().equals("requires_action"))){ - retrievedRun = service.retrieveRun(thread.getId(), run.getId()); - } - - OpenAiResponse response = service.listMessages(thread.getId()); - - List messages = response.getData(); - - System.out.println(mapper.writeValueAsString(messages)); - - } - } + + String token = System.getenv("OPENAI_TOKEN"); + OpenAiService service = new OpenAiService(token, Duration.ofMinutes(1)); + + @Test + void createRetrieveRun() throws JsonProcessingException { + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); + mapper.addMixIn(ChatFunction.class, ChatFunctionMixIn.class); + mapper.addMixIn(ChatCompletionRequest.class, ChatCompletionRequestMixIn.class); + mapper.addMixIn(ChatFunctionCall.class, ChatFunctionCallMixIn.class); + + String funcDef = "{\n" + + " \"type\": \"object\",\n" + + " \"properties\": {\n" + + " \"location\": {\n" + + " \"type\": \"string\",\n" + + " \"description\": \"The city and state, e.g. San Francisco, CA\"\n" + + " },\n" + + " \"unit\": {\n" + + " \"type\": \"string\",\n" + + " \"enum\": [\"celsius\", \"fahrenheit\"]\n" + + " }\n" + + " },\n" + + " \"required\": [\"location\"]\n" + + "}"; + Map funcParameters = mapper.readValue(funcDef, + new TypeReference>() { + }); + AssistantFunction function = AssistantFunction.builder() + .name("weather_reporter") + .description("Get the current weather of a location") + .parameters(funcParameters) + .build(); + + List toolList = new ArrayList<>(); + Tool funcTool = new Tool(AssistantToolsEnum.FUNCTION, function); + toolList.add(funcTool); + + AssistantRequest assistantRequest = AssistantRequest.builder() + .model(TikTokensUtil.ModelEnum.GPT_4_1106_preview.getName()) + .name("MATH_TUTOR") + .instructions("You are a personal Math Tutor.") + .tools(toolList) + .build(); + Assistant assistant = service.createAssistant(assistantRequest); + + ThreadRequest threadRequest = ThreadRequest.builder() + .build(); + Thread thread = service.createThread(threadRequest); + + MessageRequest messageRequest = MessageRequest.builder() + .content("What's the weather of Xiamen?") + .build(); + + Message message = service.createMessage(thread.getId(), messageRequest); + + RunCreateRequest runCreateRequest = RunCreateRequest.builder() + .assistantId(assistant.getId()) + .build(); + + Run run = service.createRun(thread.getId(), runCreateRequest); + assertNotNull(run); + + Run retrievedRun = service.retrieveRun(thread.getId(), run.getId()); + while (!(retrievedRun.getStatus().equals("completed")) + && !(retrievedRun.getStatus().equals("failed")) + && !(retrievedRun.getStatus().equals("requires_action"))) { + retrievedRun = service.retrieveRun(thread.getId(), run.getId()); + } + if (retrievedRun.getStatus().equals("requires_action")) { + RequiredAction requiredAction = retrievedRun.getRequiredAction(); + System.out.println("requiredAction"); + System.out.println(mapper.writeValueAsString(requiredAction)); + List toolCalls = requiredAction.getSubmitToolOutputs().getToolCalls(); + ToolCall toolCall = toolCalls.get(0); + String toolCallId = toolCall.getId(); + + SubmitToolOutputRequestItem toolOutputRequestItem = SubmitToolOutputRequestItem.builder() + .toolCallId(toolCallId) + .output("sunny") + .build(); + List toolOutputRequestItems = new ArrayList<>(); + toolOutputRequestItems.add(toolOutputRequestItem); + SubmitToolOutputsRequest submitToolOutputsRequest = SubmitToolOutputsRequest.builder() + .toolOutputs(toolOutputRequestItems) + .build(); + retrievedRun = service.submitToolOutputs(retrievedRun.getThreadId(), retrievedRun.getId(), + submitToolOutputsRequest); + + while (!(retrievedRun.getStatus().equals("completed")) + && !(retrievedRun.getStatus().equals("failed")) + && !(retrievedRun.getStatus().equals("requires_action"))) { + retrievedRun = service.retrieveRun(thread.getId(), run.getId()); + } + + OpenAiResponse response = service.listMessages(thread.getId()); + + List messages = response.getData(); + + System.out.println(mapper.writeValueAsString(messages)); + + } + } } diff --git a/service/src/test/java/com/launchableinc/openai/service/AssistantTest.java b/service/src/test/java/com/launchableinc/openai/service/AssistantTest.java index 8b687e34..c3861616 100644 --- a/service/src/test/java/com/launchableinc/openai/service/AssistantTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/AssistantTest.java @@ -1,11 +1,11 @@ -package com.theokanning.openai.service; - -import com.theokanning.openai.DeleteResult; -import com.theokanning.openai.ListSearchParameters; -import com.theokanning.openai.OpenAiResponse; -import com.theokanning.openai.assistants.*; -import com.theokanning.openai.file.File; -import com.theokanning.openai.utils.TikTokensUtil; +package com.launchableinc.openai.service; + +import com.launchableinc.openai.DeleteResult; +import com.launchableinc.openai.ListSearchParameters; +import com.launchableinc.openai.OpenAiResponse; +import com.launchableinc.openai.assistants.*; +import com.launchableinc.openai.file.File; +import com.launchableinc.openai.utils.TikTokensUtil; import org.junit.jupiter.api.*; import java.util.Collections; @@ -17,112 +17,120 @@ @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class AssistantTest { - static OpenAiService service = new OpenAiService(System.getenv("OPENAI_TOKEN")); - static String assistantId; - static String fileId; - - - @AfterAll - static void teardown() { - try { - service.deleteAssistantFile(assistantId, fileId); - } catch (Exception e) { - // do nothing - } - try { - service.deleteAssistant(assistantId); - } catch (Exception e) { - // do nothing - } - } - - @Test - @Order(1) - void createAssistant() { - AssistantRequest assistantRequest = AssistantRequest.builder().model(TikTokensUtil.ModelEnum.GPT_4_1106_preview.getName()).name("Math Tutor").instructions("You are a personal Math Tutor.").tools(Collections.singletonList(new Tool(AssistantToolsEnum.CODE_INTERPRETER, null))).build(); - Assistant assistant = service.createAssistant(assistantRequest); - - assistantId = assistant.getId(); - - assertEquals(assistant.getName(), "Math Tutor"); - assertEquals(assistant.getTools().get(0).getType(), AssistantToolsEnum.CODE_INTERPRETER); - } - - @Test - @Order(2) - void retrieveAssistant() { - Assistant assistant = service.retrieveAssistant(assistantId); - - assertEquals(assistant.getName(), "Math Tutor"); - } - - @Test - @Order(3) - void modifyAssistant() { - String modifiedName = "Science Tutor"; - ModifyAssistantRequest modifyRequest = ModifyAssistantRequest.builder().name(modifiedName).build(); - - Assistant modifiedAssistant = service.modifyAssistant(assistantId, modifyRequest); - assertEquals(modifiedName, modifiedAssistant.getName()); - } - - @Test - @Order(4) - void listAssistants() { - OpenAiResponse assistants = service.listAssistants(ListSearchParameters.builder().build()); - - assertNotNull(assistants); - assertFalse(assistants.getData().isEmpty()); - } - - @Test - @Order(5) - void createAssistantFile() { - String filePath = "src/test/resources/assistants-data.html"; - File uploadedFile = service.uploadFile("assistants", filePath); - - AssistantFile assistantFile = service.createAssistantFile(assistantId, new AssistantFileRequest(uploadedFile.getId())); - - fileId = assistantFile.getId(); - assertNotNull(assistantFile); - assertEquals(uploadedFile.getId(), assistantFile.getId()); - assertEquals(assistantId, assistantFile.getAssistantId()); - } - - @Test - @Order(6) - void retrieveAssistantFile() { - AssistantFile file = service.retrieveAssistantFile(assistantId, fileId); - - assertEquals(file.getId(), fileId); - } - - - @Test - @Order(7) - void listAssistantFiles() { - List files = service.listAssistantFiles(assistantId, new ListSearchParameters()).data; - - assertFalse(files.isEmpty()); - assertEquals(files.get(0).getId(), fileId); - assertEquals(files.get(0).getObject(), "assistant.file"); - } - - @Test - @Order(8) - void deleteAssistantFile() { - DeleteResult deletedFile = service.deleteAssistantFile(assistantId, fileId); - - assertEquals(deletedFile.getId(), fileId); - assertTrue(deletedFile.isDeleted()); - } - - @Test - @Order(9) - void deleteAssistant() { - DeleteResult deletedAssistant = service.deleteAssistant(assistantId); - - assertEquals(assistantId, deletedAssistant.getId()); - assertTrue(deletedAssistant.isDeleted()); - } + static OpenAiService service = new OpenAiService(System.getenv("OPENAI_TOKEN")); + static String assistantId; + static String fileId; + + + @AfterAll + static void teardown() { + try { + service.deleteAssistantFile(assistantId, fileId); + } catch (Exception e) { + // do nothing + } + try { + service.deleteAssistant(assistantId); + } catch (Exception e) { + // do nothing + } + } + + @Test + @Order(1) + void createAssistant() { + AssistantRequest assistantRequest = AssistantRequest.builder() + .model(TikTokensUtil.ModelEnum.GPT_4_1106_preview.getName()).name("Math Tutor") + .instructions("You are a personal Math Tutor.") + .tools(Collections.singletonList(new Tool(AssistantToolsEnum.CODE_INTERPRETER, null))) + .build(); + Assistant assistant = service.createAssistant(assistantRequest); + + assistantId = assistant.getId(); + + assertEquals(assistant.getName(), "Math Tutor"); + assertEquals(assistant.getTools().get(0).getType(), AssistantToolsEnum.CODE_INTERPRETER); + } + + @Test + @Order(2) + void retrieveAssistant() { + Assistant assistant = service.retrieveAssistant(assistantId); + + assertEquals(assistant.getName(), "Math Tutor"); + } + + @Test + @Order(3) + void modifyAssistant() { + String modifiedName = "Science Tutor"; + ModifyAssistantRequest modifyRequest = ModifyAssistantRequest.builder().name(modifiedName) + .build(); + + Assistant modifiedAssistant = service.modifyAssistant(assistantId, modifyRequest); + assertEquals(modifiedName, modifiedAssistant.getName()); + } + + @Test + @Order(4) + void listAssistants() { + OpenAiResponse assistants = service.listAssistants( + ListSearchParameters.builder().build()); + + assertNotNull(assistants); + assertFalse(assistants.getData().isEmpty()); + } + + @Test + @Order(5) + void createAssistantFile() { + String filePath = "src/test/resources/assistants-data.html"; + File uploadedFile = service.uploadFile("assistants", filePath); + + AssistantFile assistantFile = service.createAssistantFile(assistantId, + new AssistantFileRequest(uploadedFile.getId())); + + fileId = assistantFile.getId(); + assertNotNull(assistantFile); + assertEquals(uploadedFile.getId(), assistantFile.getId()); + assertEquals(assistantId, assistantFile.getAssistantId()); + } + + @Test + @Order(6) + void retrieveAssistantFile() { + AssistantFile file = service.retrieveAssistantFile(assistantId, fileId); + + assertEquals(file.getId(), fileId); + } + + + @Test + @Order(7) + void listAssistantFiles() { + List files = service.listAssistantFiles(assistantId, + new ListSearchParameters()).data; + + assertFalse(files.isEmpty()); + assertEquals(files.get(0).getId(), fileId); + assertEquals(files.get(0).getObject(), "assistant.file"); + } + + @Test + @Order(8) + void deleteAssistantFile() { + DeleteResult deletedFile = service.deleteAssistantFile(assistantId, fileId); + + assertEquals(deletedFile.getId(), fileId); + assertTrue(deletedFile.isDeleted()); + } + + @Test + @Order(9) + void deleteAssistant() { + DeleteResult deletedAssistant = service.deleteAssistant(assistantId); + + assertEquals(assistantId, deletedAssistant.getId()); + assertTrue(deletedAssistant.isDeleted()); + } } diff --git a/service/src/test/java/com/launchableinc/openai/service/AudioTest.java b/service/src/test/java/com/launchableinc/openai/service/AudioTest.java index 9cb083de..45ff5337 100644 --- a/service/src/test/java/com/launchableinc/openai/service/AudioTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/AudioTest.java @@ -1,10 +1,10 @@ -package com.theokanning.openai.service; +package com.launchableinc.openai.service; -import com.theokanning.openai.audio.CreateSpeechRequest; -import com.theokanning.openai.audio.CreateTranscriptionRequest; -import com.theokanning.openai.audio.CreateTranslationRequest; -import com.theokanning.openai.audio.TranscriptionResult; -import com.theokanning.openai.audio.TranslationResult; +import com.launchableinc.openai.audio.CreateSpeechRequest; +import com.launchableinc.openai.audio.CreateTranscriptionRequest; +import com.launchableinc.openai.audio.CreateTranslationRequest; +import com.launchableinc.openai.audio.TranscriptionResult; +import com.launchableinc.openai.audio.TranslationResult; import org.junit.jupiter.api.Test; import java.io.IOException; @@ -18,74 +18,78 @@ public class AudioTest { - static String englishAudioFilePath = "src/test/resources/hello-world.mp3"; - - static String koreanAudioFilePath = "src/test/resources/korean-hello.mp3"; - - String token = System.getenv("OPENAI_TOKEN"); - OpenAiService service = new OpenAiService(token, Duration.ofSeconds(30)); - - @Test - void createTranscription() { - CreateTranscriptionRequest createTranscriptionRequest = CreateTranscriptionRequest.builder() - .model("whisper-1") - .build(); - - String text = service.createTranscription(createTranscriptionRequest, englishAudioFilePath).getText(); - assertEquals("Hello World.", text); - } - - @Test - void createTranscriptionVerbose() { - CreateTranscriptionRequest createTranscriptionRequest = CreateTranscriptionRequest.builder() - .model("whisper-1") - .responseFormat("verbose_json") - .build(); - - TranscriptionResult result = service.createTranscription(createTranscriptionRequest, englishAudioFilePath); - assertEquals("Hello World.", result.getText()); - assertEquals("transcribe", result.getTask()); - assertEquals("english", result.getLanguage()); - assertTrue(result.getDuration() > 0); - assertEquals(1, result.getSegments().size()); - } - - @Test - void createTranslation() { - CreateTranslationRequest createTranslationRequest = CreateTranslationRequest.builder() - .model("whisper-1") - .build(); - - String text = service.createTranslation(createTranslationRequest, koreanAudioFilePath).getText(); - assertEquals("Hello, my name is Yoona. I am a Korean native speaker.", text); - } - - @Test - void createTranslationVerbose() { - CreateTranslationRequest createTranslationRequest = CreateTranslationRequest.builder() - .model("whisper-1") - .responseFormat("verbose_json") - .build(); - - TranslationResult result = service.createTranslation(createTranslationRequest, koreanAudioFilePath); - assertEquals("Hello, my name is Yoona. I am a Korean native speaker.", result.getText()); - assertEquals("translate", result.getTask()); - assertEquals("english", result.getLanguage()); - assertTrue(result.getDuration() > 0); - assertEquals(1, result.getSegments().size()); - } - - @Test - void createSpeech() throws IOException { - CreateSpeechRequest createSpeechRequest = CreateSpeechRequest.builder() - .model("tts-1") - .input("Hello World.") - .voice("alloy") - .build(); - - final ResponseBody speech = service.createSpeech(createSpeechRequest); - assertNotNull(speech); - assertEquals(MediaType.get("audio/mpeg"), speech.contentType()); - assertTrue(speech.bytes().length > 0); - } + static String englishAudioFilePath = "src/test/resources/hello-world.mp3"; + + static String koreanAudioFilePath = "src/test/resources/korean-hello.mp3"; + + String token = System.getenv("OPENAI_TOKEN"); + OpenAiService service = new OpenAiService(token, Duration.ofSeconds(30)); + + @Test + void createTranscription() { + CreateTranscriptionRequest createTranscriptionRequest = CreateTranscriptionRequest.builder() + .model("whisper-1") + .build(); + + String text = service.createTranscription(createTranscriptionRequest, englishAudioFilePath) + .getText(); + assertEquals("Hello World.", text); + } + + @Test + void createTranscriptionVerbose() { + CreateTranscriptionRequest createTranscriptionRequest = CreateTranscriptionRequest.builder() + .model("whisper-1") + .responseFormat("verbose_json") + .build(); + + TranscriptionResult result = service.createTranscription(createTranscriptionRequest, + englishAudioFilePath); + assertEquals("Hello World.", result.getText()); + assertEquals("transcribe", result.getTask()); + assertEquals("english", result.getLanguage()); + assertTrue(result.getDuration() > 0); + assertEquals(1, result.getSegments().size()); + } + + @Test + void createTranslation() { + CreateTranslationRequest createTranslationRequest = CreateTranslationRequest.builder() + .model("whisper-1") + .build(); + + String text = service.createTranslation(createTranslationRequest, koreanAudioFilePath) + .getText(); + assertEquals("Hello, my name is Yoona. I am a Korean native speaker.", text); + } + + @Test + void createTranslationVerbose() { + CreateTranslationRequest createTranslationRequest = CreateTranslationRequest.builder() + .model("whisper-1") + .responseFormat("verbose_json") + .build(); + + TranslationResult result = service.createTranslation(createTranslationRequest, + koreanAudioFilePath); + assertEquals("Hello, my name is Yoona. I am a Korean native speaker.", result.getText()); + assertEquals("translate", result.getTask()); + assertEquals("english", result.getLanguage()); + assertTrue(result.getDuration() > 0); + assertEquals(1, result.getSegments().size()); + } + + @Test + void createSpeech() throws IOException { + CreateSpeechRequest createSpeechRequest = CreateSpeechRequest.builder() + .model("tts-1") + .input("Hello World.") + .voice("alloy") + .build(); + + final ResponseBody speech = service.createSpeech(createSpeechRequest); + assertNotNull(speech); + assertEquals(MediaType.get("audio/mpeg"), speech.contentType()); + assertTrue(speech.bytes().length > 0); + } } diff --git a/service/src/test/java/com/launchableinc/openai/service/ChatCompletionTest.java b/service/src/test/java/com/launchableinc/openai/service/ChatCompletionTest.java index 25f0defb..d84d8574 100644 --- a/service/src/test/java/com/launchableinc/openai/service/ChatCompletionTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/ChatCompletionTest.java @@ -1,10 +1,10 @@ -package com.theokanning.openai.service; +package com.launchableinc.openai.service; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyDescription; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; -import com.theokanning.openai.completion.chat.*; +import com.launchableinc.openai.completion.chat.*; import org.junit.jupiter.api.Test; import java.util.*; @@ -13,291 +13,316 @@ class ChatCompletionTest { - static class Weather { - @JsonPropertyDescription("City and state, for example: León, Guanajuato") - public String location; - - @JsonPropertyDescription("The temperature unit, can be 'celsius' or 'fahrenheit'") - @JsonProperty(required = true) - public WeatherUnit unit; - } - - enum WeatherUnit { - CELSIUS, FAHRENHEIT; - } - - static class WeatherResponse { - public String location; - public WeatherUnit unit; - public int temperature; - public String description; - - public WeatherResponse(String location, WeatherUnit unit, int temperature, String description) { - this.location = location; - this.unit = unit; - this.temperature = temperature; - this.description = description; - } - } - - String token = System.getenv("OPENAI_TOKEN"); - OpenAiService service = new OpenAiService(token); - - @Test - void createChatCompletion() { - final List messages = new ArrayList<>(); - final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), "You are a dog and will speak as such."); - messages.add(systemMessage); - - ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest - .builder() - .model("gpt-3.5-turbo") - .messages(messages) - .n(5) - .maxTokens(50) - .logitBias(new HashMap<>()) - .build(); - - List choices = service.createChatCompletion(chatCompletionRequest).getChoices(); - assertEquals(5, choices.size()); - } - - @Test - void streamChatCompletion() { - final List messages = new ArrayList<>(); - final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), "You are a dog and will speak as such."); - messages.add(systemMessage); - - ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest - .builder() - .model("gpt-3.5-turbo") - .messages(messages) - .n(1) - .maxTokens(50) - .logitBias(new HashMap<>()) - .stream(true) - .build(); - - List chunks = new ArrayList<>(); - service.streamChatCompletion(chatCompletionRequest).blockingForEach(chunks::add); - assertTrue(chunks.size() > 0); - assertNotNull(chunks.get(0).getChoices().get(0)); - } - - @Test - void createChatCompletionWithFunctions() { - final List functions = Collections.singletonList(ChatFunction.builder() - .name("get_weather") - .description("Get the current weather in a given location") - .executor(Weather.class, w -> new WeatherResponse(w.location, w.unit, 25, "sunny")) - .build()); - final FunctionExecutor functionExecutor = new FunctionExecutor(functions); - - final List messages = new ArrayList<>(); - final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), "You are a helpful assistant."); - final ChatMessage userMessage = new ChatMessage(ChatMessageRole.USER.value(), "What is the weather in Monterrey, Nuevo León?"); - messages.add(systemMessage); - messages.add(userMessage); - - ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest - .builder() - .model("gpt-3.5-turbo-0613") - .messages(messages) - .functions(functionExecutor.getFunctions()) - .n(1) - .maxTokens(100) - .logitBias(new HashMap<>()) - .build(); - - ChatCompletionChoice choice = service.createChatCompletion(chatCompletionRequest).getChoices().get(0); - assertEquals("function_call", choice.getFinishReason()); - assertNotNull(choice.getMessage().getFunctionCall()); - assertEquals("get_weather", choice.getMessage().getFunctionCall().getName()); - assertInstanceOf(ObjectNode.class, choice.getMessage().getFunctionCall().getArguments()); - - ChatMessage callResponse = functionExecutor.executeAndConvertToMessageHandlingExceptions(choice.getMessage().getFunctionCall()); - assertNotEquals("error", callResponse.getName()); - - // this performs an unchecked cast - WeatherResponse functionExecutionResponse = functionExecutor.execute(choice.getMessage().getFunctionCall()); - assertInstanceOf(WeatherResponse.class, functionExecutionResponse); - assertEquals(25, functionExecutionResponse.temperature); - - JsonNode jsonFunctionExecutionResponse = functionExecutor.executeAndConvertToJson(choice.getMessage().getFunctionCall()); - assertInstanceOf(ObjectNode.class, jsonFunctionExecutionResponse); - assertEquals("25", jsonFunctionExecutionResponse.get("temperature").asText()); - - messages.add(choice.getMessage()); - messages.add(callResponse); - - ChatCompletionRequest chatCompletionRequest2 = ChatCompletionRequest - .builder() - .model("gpt-3.5-turbo-0613") - .messages(messages) - .functions(functionExecutor.getFunctions()) - .n(1) - .maxTokens(100) - .logitBias(new HashMap<>()) - .build(); - - ChatCompletionChoice choice2 = service.createChatCompletion(chatCompletionRequest2).getChoices().get(0); - assertNotEquals("function_call", choice2.getFinishReason()); // could be stop or length, but should not be function_call - assertNull(choice2.getMessage().getFunctionCall()); - assertNotNull(choice2.getMessage().getContent()); - } - - @Test - void createChatCompletionWithDynamicFunctions() { - ChatFunctionDynamic function = ChatFunctionDynamic.builder() - .name("get_weather") - .description("Get the current weather of a location") - .addProperty(ChatFunctionProperty.builder() - .name("location") - .type("string") - .description("City and state, for example: León, Guanajuato") - .build()) - .addProperty(ChatFunctionProperty.builder() - .name("unit") - .type("string") - .description("The temperature unit, can be 'celsius' or 'fahrenheit'") - .enumValues(new HashSet<>(Arrays.asList("celsius", "fahrenheit"))) - .required(true) - .build()) - .build(); - - final List messages = new ArrayList<>(); - final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), "You are a helpful assistant."); - final ChatMessage userMessage = new ChatMessage(ChatMessageRole.USER.value(), "What is the weather in Monterrey, Nuevo León?"); - messages.add(systemMessage); - messages.add(userMessage); - - ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest - .builder() - .model("gpt-3.5-turbo-0613") - .messages(messages) - .functions(Collections.singletonList(function)) - .n(1) - .maxTokens(100) - .logitBias(new HashMap<>()) - .build(); - - ChatCompletionChoice choice = service.createChatCompletion(chatCompletionRequest).getChoices().get(0); - assertEquals("function_call", choice.getFinishReason()); - assertNotNull(choice.getMessage().getFunctionCall()); - assertEquals("get_weather", choice.getMessage().getFunctionCall().getName()); - assertInstanceOf(ObjectNode.class, choice.getMessage().getFunctionCall().getArguments()); - assertNotNull(choice.getMessage().getFunctionCall().getArguments().get("location")); - assertNotNull(choice.getMessage().getFunctionCall().getArguments().get("unit")); - } - - @Test - void streamChatCompletionWithFunctions() { - final List functions = Collections.singletonList(ChatFunction.builder() - .name("get_weather") - .description("Get the current weather in a given location") - .executor(Weather.class, w -> new WeatherResponse(w.location, w.unit, 25, "sunny")) - .build()); - final FunctionExecutor functionExecutor = new FunctionExecutor(functions); - - final List messages = new ArrayList<>(); - final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), "You are a helpful assistant."); - final ChatMessage userMessage = new ChatMessage(ChatMessageRole.USER.value(), "What is the weather in Monterrey, Nuevo León?"); - messages.add(systemMessage); - messages.add(userMessage); - - ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest - .builder() - .model("gpt-3.5-turbo-0613") - .messages(messages) - .functions(functionExecutor.getFunctions()) - .n(1) - .maxTokens(100) - .logitBias(new HashMap<>()) - .build(); - - ChatMessage accumulatedMessage = service.mapStreamToAccumulator(service.streamChatCompletion(chatCompletionRequest)) - .blockingLast() - .getAccumulatedMessage(); - assertNotNull(accumulatedMessage.getFunctionCall()); - assertEquals("get_weather", accumulatedMessage.getFunctionCall().getName()); - assertInstanceOf(ObjectNode.class, accumulatedMessage.getFunctionCall().getArguments()); - - ChatMessage callResponse = functionExecutor.executeAndConvertToMessageHandlingExceptions(accumulatedMessage.getFunctionCall()); - assertNotEquals("error", callResponse.getName()); - - // this performs an unchecked cast - WeatherResponse functionExecutionResponse = functionExecutor.execute(accumulatedMessage.getFunctionCall()); - assertInstanceOf(WeatherResponse.class, functionExecutionResponse); - assertEquals(25, functionExecutionResponse.temperature); - - JsonNode jsonFunctionExecutionResponse = functionExecutor.executeAndConvertToJson(accumulatedMessage.getFunctionCall()); - assertInstanceOf(ObjectNode.class, jsonFunctionExecutionResponse); - assertEquals("25", jsonFunctionExecutionResponse.get("temperature").asText()); - - - messages.add(accumulatedMessage); - messages.add(callResponse); - - ChatCompletionRequest chatCompletionRequest2 = ChatCompletionRequest - .builder() - .model("gpt-3.5-turbo-0613") - .messages(messages) - .functions(functionExecutor.getFunctions()) - .n(1) - .maxTokens(100) - .logitBias(new HashMap<>()) - .build(); - - ChatMessage accumulatedMessage2 = service.mapStreamToAccumulator(service.streamChatCompletion(chatCompletionRequest2)) - .blockingLast() - .getAccumulatedMessage(); - assertNull(accumulatedMessage2.getFunctionCall()); - assertNotNull(accumulatedMessage2.getContent()); - } - - @Test - void streamChatCompletionWithDynamicFunctions() { - ChatFunctionDynamic function = ChatFunctionDynamic.builder() - .name("get_weather") - .description("Get the current weather of a location") - .addProperty(ChatFunctionProperty.builder() - .name("location") - .type("string") - .description("City and state, for example: León, Guanajuato") - .build()) - .addProperty(ChatFunctionProperty.builder() - .name("unit") - .type("string") - .description("The temperature unit, can be 'celsius' or 'fahrenheit'") - .enumValues(new HashSet<>(Arrays.asList("celsius", "fahrenheit"))) - .required(true) - .build()) - .build(); - - final List messages = new ArrayList<>(); - final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), "You are a helpful assistant."); - final ChatMessage userMessage = new ChatMessage(ChatMessageRole.USER.value(), "What is the weather in Monterrey, Nuevo León?"); - messages.add(systemMessage); - messages.add(userMessage); - - ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest - .builder() - .model("gpt-3.5-turbo-0613") - .messages(messages) - .functions(Collections.singletonList(function)) - .n(1) - .maxTokens(100) - .logitBias(new HashMap<>()) - .build(); - - ChatMessage accumulatedMessage = service.mapStreamToAccumulator(service.streamChatCompletion(chatCompletionRequest)) - .blockingLast() - .getAccumulatedMessage(); - assertNotNull(accumulatedMessage.getFunctionCall()); - assertEquals("get_weather", accumulatedMessage.getFunctionCall().getName()); - assertInstanceOf(ObjectNode.class, accumulatedMessage.getFunctionCall().getArguments()); - assertNotNull(accumulatedMessage.getFunctionCall().getArguments().get("location")); - assertNotNull(accumulatedMessage.getFunctionCall().getArguments().get("unit")); - } + static class Weather { + + @JsonPropertyDescription("City and state, for example: León, Guanajuato") + public String location; + + @JsonPropertyDescription("The temperature unit, can be 'celsius' or 'fahrenheit'") + @JsonProperty(required = true) + public WeatherUnit unit; + } + + enum WeatherUnit { + CELSIUS, FAHRENHEIT; + } + + static class WeatherResponse { + + public String location; + public WeatherUnit unit; + public int temperature; + public String description; + + public WeatherResponse(String location, WeatherUnit unit, int temperature, String description) { + this.location = location; + this.unit = unit; + this.temperature = temperature; + this.description = description; + } + } + + String token = System.getenv("OPENAI_TOKEN"); + OpenAiService service = new OpenAiService(token); + + @Test + void createChatCompletion() { + final List messages = new ArrayList<>(); + final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), + "You are a dog and will speak as such."); + messages.add(systemMessage); + + ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest + .builder() + .model("gpt-3.5-turbo") + .messages(messages) + .n(5) + .maxTokens(50) + .logitBias(new HashMap<>()) + .build(); + + List choices = service.createChatCompletion(chatCompletionRequest) + .getChoices(); + assertEquals(5, choices.size()); + } + + @Test + void streamChatCompletion() { + final List messages = new ArrayList<>(); + final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), + "You are a dog and will speak as such."); + messages.add(systemMessage); + + ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest + .builder() + .model("gpt-3.5-turbo") + .messages(messages) + .n(1) + .maxTokens(50) + .logitBias(new HashMap<>()) + .stream(true) + .build(); + + List chunks = new ArrayList<>(); + service.streamChatCompletion(chatCompletionRequest).blockingForEach(chunks::add); + assertTrue(chunks.size() > 0); + assertNotNull(chunks.get(0).getChoices().get(0)); + } + + @Test + void createChatCompletionWithFunctions() { + final List functions = Collections.singletonList(ChatFunction.builder() + .name("get_weather") + .description("Get the current weather in a given location") + .executor(Weather.class, w -> new WeatherResponse(w.location, w.unit, 25, "sunny")) + .build()); + final FunctionExecutor functionExecutor = new FunctionExecutor(functions); + + final List messages = new ArrayList<>(); + final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), + "You are a helpful assistant."); + final ChatMessage userMessage = new ChatMessage(ChatMessageRole.USER.value(), + "What is the weather in Monterrey, Nuevo León?"); + messages.add(systemMessage); + messages.add(userMessage); + + ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest + .builder() + .model("gpt-3.5-turbo-0613") + .messages(messages) + .functions(functionExecutor.getFunctions()) + .n(1) + .maxTokens(100) + .logitBias(new HashMap<>()) + .build(); + + ChatCompletionChoice choice = service.createChatCompletion(chatCompletionRequest).getChoices() + .get(0); + assertEquals("function_call", choice.getFinishReason()); + assertNotNull(choice.getMessage().getFunctionCall()); + assertEquals("get_weather", choice.getMessage().getFunctionCall().getName()); + assertInstanceOf(ObjectNode.class, choice.getMessage().getFunctionCall().getArguments()); + + ChatMessage callResponse = functionExecutor.executeAndConvertToMessageHandlingExceptions( + choice.getMessage().getFunctionCall()); + assertNotEquals("error", callResponse.getName()); + + // this performs an unchecked cast + WeatherResponse functionExecutionResponse = functionExecutor.execute( + choice.getMessage().getFunctionCall()); + assertInstanceOf(WeatherResponse.class, functionExecutionResponse); + assertEquals(25, functionExecutionResponse.temperature); + + JsonNode jsonFunctionExecutionResponse = functionExecutor.executeAndConvertToJson( + choice.getMessage().getFunctionCall()); + assertInstanceOf(ObjectNode.class, jsonFunctionExecutionResponse); + assertEquals("25", jsonFunctionExecutionResponse.get("temperature").asText()); + + messages.add(choice.getMessage()); + messages.add(callResponse); + + ChatCompletionRequest chatCompletionRequest2 = ChatCompletionRequest + .builder() + .model("gpt-3.5-turbo-0613") + .messages(messages) + .functions(functionExecutor.getFunctions()) + .n(1) + .maxTokens(100) + .logitBias(new HashMap<>()) + .build(); + + ChatCompletionChoice choice2 = service.createChatCompletion(chatCompletionRequest2).getChoices() + .get(0); + assertNotEquals("function_call", + choice2.getFinishReason()); // could be stop or length, but should not be function_call + assertNull(choice2.getMessage().getFunctionCall()); + assertNotNull(choice2.getMessage().getContent()); + } + + @Test + void createChatCompletionWithDynamicFunctions() { + ChatFunctionDynamic function = ChatFunctionDynamic.builder() + .name("get_weather") + .description("Get the current weather of a location") + .addProperty(ChatFunctionProperty.builder() + .name("location") + .type("string") + .description("City and state, for example: León, Guanajuato") + .build()) + .addProperty(ChatFunctionProperty.builder() + .name("unit") + .type("string") + .description("The temperature unit, can be 'celsius' or 'fahrenheit'") + .enumValues(new HashSet<>(Arrays.asList("celsius", "fahrenheit"))) + .required(true) + .build()) + .build(); + + final List messages = new ArrayList<>(); + final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), + "You are a helpful assistant."); + final ChatMessage userMessage = new ChatMessage(ChatMessageRole.USER.value(), + "What is the weather in Monterrey, Nuevo León?"); + messages.add(systemMessage); + messages.add(userMessage); + + ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest + .builder() + .model("gpt-3.5-turbo-0613") + .messages(messages) + .functions(Collections.singletonList(function)) + .n(1) + .maxTokens(100) + .logitBias(new HashMap<>()) + .build(); + + ChatCompletionChoice choice = service.createChatCompletion(chatCompletionRequest).getChoices() + .get(0); + assertEquals("function_call", choice.getFinishReason()); + assertNotNull(choice.getMessage().getFunctionCall()); + assertEquals("get_weather", choice.getMessage().getFunctionCall().getName()); + assertInstanceOf(ObjectNode.class, choice.getMessage().getFunctionCall().getArguments()); + assertNotNull(choice.getMessage().getFunctionCall().getArguments().get("location")); + assertNotNull(choice.getMessage().getFunctionCall().getArguments().get("unit")); + } + + @Test + void streamChatCompletionWithFunctions() { + final List functions = Collections.singletonList(ChatFunction.builder() + .name("get_weather") + .description("Get the current weather in a given location") + .executor(Weather.class, w -> new WeatherResponse(w.location, w.unit, 25, "sunny")) + .build()); + final FunctionExecutor functionExecutor = new FunctionExecutor(functions); + + final List messages = new ArrayList<>(); + final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), + "You are a helpful assistant."); + final ChatMessage userMessage = new ChatMessage(ChatMessageRole.USER.value(), + "What is the weather in Monterrey, Nuevo León?"); + messages.add(systemMessage); + messages.add(userMessage); + + ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest + .builder() + .model("gpt-3.5-turbo-0613") + .messages(messages) + .functions(functionExecutor.getFunctions()) + .n(1) + .maxTokens(100) + .logitBias(new HashMap<>()) + .build(); + + ChatMessage accumulatedMessage = service.mapStreamToAccumulator( + service.streamChatCompletion(chatCompletionRequest)) + .blockingLast() + .getAccumulatedMessage(); + assertNotNull(accumulatedMessage.getFunctionCall()); + assertEquals("get_weather", accumulatedMessage.getFunctionCall().getName()); + assertInstanceOf(ObjectNode.class, accumulatedMessage.getFunctionCall().getArguments()); + + ChatMessage callResponse = functionExecutor.executeAndConvertToMessageHandlingExceptions( + accumulatedMessage.getFunctionCall()); + assertNotEquals("error", callResponse.getName()); + + // this performs an unchecked cast + WeatherResponse functionExecutionResponse = functionExecutor.execute( + accumulatedMessage.getFunctionCall()); + assertInstanceOf(WeatherResponse.class, functionExecutionResponse); + assertEquals(25, functionExecutionResponse.temperature); + + JsonNode jsonFunctionExecutionResponse = functionExecutor.executeAndConvertToJson( + accumulatedMessage.getFunctionCall()); + assertInstanceOf(ObjectNode.class, jsonFunctionExecutionResponse); + assertEquals("25", jsonFunctionExecutionResponse.get("temperature").asText()); + + messages.add(accumulatedMessage); + messages.add(callResponse); + + ChatCompletionRequest chatCompletionRequest2 = ChatCompletionRequest + .builder() + .model("gpt-3.5-turbo-0613") + .messages(messages) + .functions(functionExecutor.getFunctions()) + .n(1) + .maxTokens(100) + .logitBias(new HashMap<>()) + .build(); + + ChatMessage accumulatedMessage2 = service.mapStreamToAccumulator( + service.streamChatCompletion(chatCompletionRequest2)) + .blockingLast() + .getAccumulatedMessage(); + assertNull(accumulatedMessage2.getFunctionCall()); + assertNotNull(accumulatedMessage2.getContent()); + } + + @Test + void streamChatCompletionWithDynamicFunctions() { + ChatFunctionDynamic function = ChatFunctionDynamic.builder() + .name("get_weather") + .description("Get the current weather of a location") + .addProperty(ChatFunctionProperty.builder() + .name("location") + .type("string") + .description("City and state, for example: León, Guanajuato") + .build()) + .addProperty(ChatFunctionProperty.builder() + .name("unit") + .type("string") + .description("The temperature unit, can be 'celsius' or 'fahrenheit'") + .enumValues(new HashSet<>(Arrays.asList("celsius", "fahrenheit"))) + .required(true) + .build()) + .build(); + + final List messages = new ArrayList<>(); + final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), + "You are a helpful assistant."); + final ChatMessage userMessage = new ChatMessage(ChatMessageRole.USER.value(), + "What is the weather in Monterrey, Nuevo León?"); + messages.add(systemMessage); + messages.add(userMessage); + + ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest + .builder() + .model("gpt-3.5-turbo-0613") + .messages(messages) + .functions(Collections.singletonList(function)) + .n(1) + .maxTokens(100) + .logitBias(new HashMap<>()) + .build(); + + ChatMessage accumulatedMessage = service.mapStreamToAccumulator( + service.streamChatCompletion(chatCompletionRequest)) + .blockingLast() + .getAccumulatedMessage(); + assertNotNull(accumulatedMessage.getFunctionCall()); + assertEquals("get_weather", accumulatedMessage.getFunctionCall().getName()); + assertInstanceOf(ObjectNode.class, accumulatedMessage.getFunctionCall().getArguments()); + assertNotNull(accumulatedMessage.getFunctionCall().getArguments().get("location")); + assertNotNull(accumulatedMessage.getFunctionCall().getArguments().get("unit")); + } } diff --git a/service/src/test/java/com/launchableinc/openai/service/CompletionTest.java b/service/src/test/java/com/launchableinc/openai/service/CompletionTest.java index 69284c3b..728e44e8 100644 --- a/service/src/test/java/com/launchableinc/openai/service/CompletionTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/CompletionTest.java @@ -1,9 +1,8 @@ -package com.theokanning.openai.service; +package com.launchableinc.openai.service; -import com.theokanning.openai.completion.CompletionChoice; -import com.theokanning.openai.completion.CompletionChunk; -import com.theokanning.openai.completion.CompletionRequest; -import com.theokanning.openai.service.OpenAiService; +import com.launchableinc.openai.completion.CompletionChoice; +import com.launchableinc.openai.completion.CompletionChunk; +import com.launchableinc.openai.completion.CompletionRequest; import org.junit.jupiter.api.Test; import java.util.ArrayList; @@ -15,44 +14,44 @@ public class CompletionTest { - String token = System.getenv("OPENAI_TOKEN"); - OpenAiService service = new OpenAiService(token); - - @Test - void createCompletion() { - CompletionRequest completionRequest = CompletionRequest.builder() - .model("babbage-002") - .prompt("Somebody once told me the world is gonna roll me") - .echo(true) - .n(5) - .maxTokens(50) - .user("testing") - .logitBias(new HashMap<>()) - .logprobs(5) - .build(); - - List choices = service.createCompletion(completionRequest).getChoices(); - assertEquals(5, choices.size()); - assertNotNull(choices.get(0).getLogprobs()); - } - - @Test - void streamCompletion() { - CompletionRequest completionRequest = CompletionRequest.builder() - .model("babbage-002") - .prompt("Somebody once told me the world is gonna roll me") - .echo(true) - .n(1) - .maxTokens(25) - .user("testing") - .logitBias(new HashMap<>()) - .logprobs(5) - .stream(true) - .build(); - - List chunks = new ArrayList<>(); - service.streamCompletion(completionRequest).blockingForEach(chunks::add); - assertTrue(chunks.size() > 0); - assertNotNull(chunks.get(0).getChoices().get(0)); - } + String token = System.getenv("OPENAI_TOKEN"); + OpenAiService service = new OpenAiService(token); + + @Test + void createCompletion() { + CompletionRequest completionRequest = CompletionRequest.builder() + .model("babbage-002") + .prompt("Somebody once told me the world is gonna roll me") + .echo(true) + .n(5) + .maxTokens(50) + .user("testing") + .logitBias(new HashMap<>()) + .logprobs(5) + .build(); + + List choices = service.createCompletion(completionRequest).getChoices(); + assertEquals(5, choices.size()); + assertNotNull(choices.get(0).getLogprobs()); + } + + @Test + void streamCompletion() { + CompletionRequest completionRequest = CompletionRequest.builder() + .model("babbage-002") + .prompt("Somebody once told me the world is gonna roll me") + .echo(true) + .n(1) + .maxTokens(25) + .user("testing") + .logitBias(new HashMap<>()) + .logprobs(5) + .stream(true) + .build(); + + List chunks = new ArrayList<>(); + service.streamCompletion(completionRequest).blockingForEach(chunks::add); + assertTrue(chunks.size() > 0); + assertNotNull(chunks.get(0).getChoices().get(0)); + } } diff --git a/service/src/test/java/com/launchableinc/openai/service/EditTest.java b/service/src/test/java/com/launchableinc/openai/service/EditTest.java index 64277bdd..b2574084 100644 --- a/service/src/test/java/com/launchableinc/openai/service/EditTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/EditTest.java @@ -1,26 +1,26 @@ -package com.theokanning.openai.service; +package com.launchableinc.openai.service; -import com.theokanning.openai.OpenAiHttpException; -import com.theokanning.openai.edit.EditRequest; -import com.theokanning.openai.edit.EditResult; +import com.launchableinc.openai.OpenAiHttpException; +import com.launchableinc.openai.edit.EditRequest; +import com.launchableinc.openai.edit.EditResult; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertNotNull; public class EditTest { - String token = System.getenv("OPENAI_TOKEN"); - com.theokanning.openai.service.OpenAiService service = new OpenAiService(token); + String token = System.getenv("OPENAI_TOKEN"); + com.launchableinc.openai.service.OpenAiService service = new OpenAiService(token); - @Test - void edit() throws OpenAiHttpException { - EditRequest request = EditRequest.builder() - .model("text-davinci-edit-001") - .input("What day of the wek is it?") - .instruction("Fix the spelling mistakes") - .build(); + @Test + void edit() throws OpenAiHttpException { + EditRequest request = EditRequest.builder() + .model("text-davinci-edit-001") + .input("What day of the wek is it?") + .instruction("Fix the spelling mistakes") + .build(); - EditResult result = service.createEdit(request); - assertNotNull(result.getChoices().get(0).getText()); - } + EditResult result = service.createEdit(request); + assertNotNull(result.getChoices().get(0).getText()); + } } diff --git a/service/src/test/java/com/launchableinc/openai/service/EmbeddingTest.java b/service/src/test/java/com/launchableinc/openai/service/EmbeddingTest.java index 3320dcea..44d33d99 100644 --- a/service/src/test/java/com/launchableinc/openai/service/EmbeddingTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/EmbeddingTest.java @@ -1,7 +1,7 @@ -package com.theokanning.openai.service; +package com.launchableinc.openai.service; -import com.theokanning.openai.embedding.Embedding; -import com.theokanning.openai.embedding.EmbeddingRequest; +import com.launchableinc.openai.embedding.Embedding; +import com.launchableinc.openai.embedding.EmbeddingRequest; import org.junit.jupiter.api.Test; import java.util.Collections; @@ -12,19 +12,19 @@ public class EmbeddingTest { - String token = System.getenv("OPENAI_TOKEN"); - com.theokanning.openai.service.OpenAiService service = new OpenAiService(token); + String token = System.getenv("OPENAI_TOKEN"); + com.launchableinc.openai.service.OpenAiService service = new OpenAiService(token); - @Test - void createEmbeddings() { - EmbeddingRequest embeddingRequest = EmbeddingRequest.builder() - .model("text-embedding-ada-002") - .input(Collections.singletonList("The food was delicious and the waiter...")) - .build(); + @Test + void createEmbeddings() { + EmbeddingRequest embeddingRequest = EmbeddingRequest.builder() + .model("text-embedding-ada-002") + .input(Collections.singletonList("The food was delicious and the waiter...")) + .build(); - List embeddings = service.createEmbeddings(embeddingRequest).getData(); + List embeddings = service.createEmbeddings(embeddingRequest).getData(); - assertFalse(embeddings.isEmpty()); - assertFalse(embeddings.get(0).getEmbedding().isEmpty()); - } + assertFalse(embeddings.isEmpty()); + assertFalse(embeddings.get(0).getEmbedding().isEmpty()); + } } diff --git a/service/src/test/java/com/launchableinc/openai/service/FileTest.java b/service/src/test/java/com/launchableinc/openai/service/FileTest.java index 51dd9407..46dc034a 100644 --- a/service/src/test/java/com/launchableinc/openai/service/FileTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/FileTest.java @@ -1,7 +1,7 @@ -package com.theokanning.openai.service; +package com.launchableinc.openai.service; -import com.theokanning.openai.DeleteResult; -import com.theokanning.openai.file.File; +import com.launchableinc.openai.DeleteResult; +import com.launchableinc.openai.file.File; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; @@ -19,53 +19,54 @@ @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class FileTest { - static String filePath = "src/test/resources/fine-tuning-data.jsonl"; - String token = System.getenv("OPENAI_TOKEN"); - OpenAiService service = new OpenAiService(token); - static String fileId; + static String filePath = "src/test/resources/fine-tuning-data.jsonl"; - @Test - @Order(1) - void uploadFile() throws Exception { - File file = service.uploadFile("fine-tune", filePath); - fileId = file.getId(); + String token = System.getenv("OPENAI_TOKEN"); + OpenAiService service = new OpenAiService(token); + static String fileId; - assertEquals("fine-tune", file.getPurpose()); - assertEquals(filePath, file.getFilename()); + @Test + @Order(1) + void uploadFile() throws Exception { + File file = service.uploadFile("fine-tune", filePath); + fileId = file.getId(); - // wait for file to be processed - TimeUnit.SECONDS.sleep(10); - } + assertEquals("fine-tune", file.getPurpose()); + assertEquals(filePath, file.getFilename()); - @Test - @Order(2) - void listFiles() { - List files = service.listFiles(); + // wait for file to be processed + TimeUnit.SECONDS.sleep(10); + } - assertTrue(files.stream().anyMatch(file -> file.getId().equals(fileId))); - } + @Test + @Order(2) + void listFiles() { + List files = service.listFiles(); - @Test - @Order(3) - void retrieveFile() { - File file = service.retrieveFile(fileId); + assertTrue(files.stream().anyMatch(file -> file.getId().equals(fileId))); + } - assertEquals(filePath, file.getFilename()); - } + @Test + @Order(3) + void retrieveFile() { + File file = service.retrieveFile(fileId); - @Test - @Order(4) - void retrieveFileContent() throws IOException { - String fileBytesToString = service.retrieveFileContent(fileId).string(); - String contents = new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8); - assertEquals(contents, fileBytesToString); - } + assertEquals(filePath, file.getFilename()); + } - @Test - @Order(5) - void deleteFile() { - DeleteResult result = service.deleteFile(fileId); - assertTrue(result.isDeleted()); - } + @Test + @Order(4) + void retrieveFileContent() throws IOException { + String fileBytesToString = service.retrieveFileContent(fileId).string(); + String contents = new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8); + assertEquals(contents, fileBytesToString); + } + + @Test + @Order(5) + void deleteFile() { + DeleteResult result = service.deleteFile(fileId); + assertTrue(result.isDeleted()); + } } diff --git a/service/src/test/java/com/launchableinc/openai/service/FineTuneTest.java b/service/src/test/java/com/launchableinc/openai/service/FineTuneTest.java index e47460d0..3afbf279 100644 --- a/service/src/test/java/com/launchableinc/openai/service/FineTuneTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/FineTuneTest.java @@ -1,8 +1,8 @@ -package com.theokanning.openai.service; +package com.launchableinc.openai.service; -import com.theokanning.openai.finetune.FineTuneEvent; -import com.theokanning.openai.finetune.FineTuneRequest; -import com.theokanning.openai.finetune.FineTuneResult; +import com.launchableinc.openai.finetune.FineTuneEvent; +import com.launchableinc.openai.finetune.FineTuneRequest; +import com.launchableinc.openai.finetune.FineTuneResult; import org.junit.jupiter.api.*; import java.util.List; @@ -13,70 +13,71 @@ @Deprecated @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class FineTuneTest { - static com.theokanning.openai.service.OpenAiService service; - static String fileId; - static String fineTuneId; - - - @BeforeAll - static void setup() throws Exception { - String token = System.getenv("OPENAI_TOKEN"); - service = new OpenAiService(token); - fileId = service.uploadFile("fine-tune", "src/test/resources/fine-tuning-data.jsonl").getId(); - - // wait for file to be processed - TimeUnit.SECONDS.sleep(10); - } - - @AfterAll - static void teardown() { - service.deleteFile(fileId); - } - - @Test - @Order(1) - void createFineTune() { - FineTuneRequest request = FineTuneRequest.builder() - .trainingFile(fileId) - .model("ada") - .nEpochs(4) - .build(); - - FineTuneResult fineTune = service.createFineTune(request); - fineTuneId = fineTune.getId(); - - assertEquals("pending", fineTune.getStatus()); - } - - @Test - @Order(2) - void listFineTunes() { - List fineTunes = service.listFineTunes(); - - assertTrue(fineTunes.stream().anyMatch(fineTune -> fineTune.getId().equals(fineTuneId))); - } - - @Test - @Order(3) - void listFineTuneEvents() { - List events = service.listFineTuneEvents(fineTuneId); - - assertFalse(events.isEmpty()); - } - - @Test - @Order(3) - void retrieveFineTune() { - FineTuneResult fineTune = service.retrieveFineTune(fineTuneId); - - assertEquals("ada", fineTune.getModel()); - } - - @Test - @Order(4) - void cancelFineTune() { - FineTuneResult fineTune = service.cancelFineTune(fineTuneId); - - assertEquals("cancelled", fineTune.getStatus()); - } + + static com.launchableinc.openai.service.OpenAiService service; + static String fileId; + static String fineTuneId; + + + @BeforeAll + static void setup() throws Exception { + String token = System.getenv("OPENAI_TOKEN"); + service = new OpenAiService(token); + fileId = service.uploadFile("fine-tune", "src/test/resources/fine-tuning-data.jsonl").getId(); + + // wait for file to be processed + TimeUnit.SECONDS.sleep(10); + } + + @AfterAll + static void teardown() { + service.deleteFile(fileId); + } + + @Test + @Order(1) + void createFineTune() { + FineTuneRequest request = FineTuneRequest.builder() + .trainingFile(fileId) + .model("ada") + .nEpochs(4) + .build(); + + FineTuneResult fineTune = service.createFineTune(request); + fineTuneId = fineTune.getId(); + + assertEquals("pending", fineTune.getStatus()); + } + + @Test + @Order(2) + void listFineTunes() { + List fineTunes = service.listFineTunes(); + + assertTrue(fineTunes.stream().anyMatch(fineTune -> fineTune.getId().equals(fineTuneId))); + } + + @Test + @Order(3) + void listFineTuneEvents() { + List events = service.listFineTuneEvents(fineTuneId); + + assertFalse(events.isEmpty()); + } + + @Test + @Order(3) + void retrieveFineTune() { + FineTuneResult fineTune = service.retrieveFineTune(fineTuneId); + + assertEquals("ada", fineTune.getModel()); + } + + @Test + @Order(4) + void cancelFineTune() { + FineTuneResult fineTune = service.cancelFineTune(fineTuneId); + + assertEquals("cancelled", fineTune.getStatus()); + } } diff --git a/service/src/test/java/com/launchableinc/openai/service/FineTuningTest.java b/service/src/test/java/com/launchableinc/openai/service/FineTuningTest.java index c0b98f6f..ef7b409b 100644 --- a/service/src/test/java/com/launchableinc/openai/service/FineTuningTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/FineTuningTest.java @@ -1,9 +1,9 @@ -package com.theokanning.openai.service; +package com.launchableinc.openai.service; -import com.theokanning.openai.fine_tuning.FineTuningEvent; -import com.theokanning.openai.fine_tuning.FineTuningJob; -import com.theokanning.openai.fine_tuning.FineTuningJobRequest; -import com.theokanning.openai.fine_tuning.Hyperparameters; +import com.launchableinc.openai.fine_tuning.FineTuningEvent; +import com.launchableinc.openai.fine_tuning.FineTuningJob; +import com.launchableinc.openai.fine_tuning.FineTuningJobRequest; +import com.launchableinc.openai.fine_tuning.Hyperparameters; import org.junit.jupiter.api.*; import java.util.List; @@ -13,80 +13,83 @@ @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class FineTuningTest { - static OpenAiService service; - static String fileId; - static String fineTuningJobId; - - - @BeforeAll - static void setup() throws Exception { - String token = System.getenv("OPENAI_TOKEN"); - service = new OpenAiService(token); - fileId = service.uploadFile("fine-tune", "src/test/resources/chat-fine-tuning-data.jsonl").getId(); - - // wait for file to be processed - TimeUnit.SECONDS.sleep(10); - } - - @AfterAll - static void teardown() { - try { - service.deleteFile(fileId); - } catch (Exception e) { - // ignore - } - } - - @Test - @Order(1) - void createFineTuningJob() { - Hyperparameters hyperparameters = Hyperparameters.builder() - .nEpochs(4) - .build(); - FineTuningJobRequest request = FineTuningJobRequest.builder() - .trainingFile(fileId) - .model("gpt-3.5-turbo") - .hyperparameters(hyperparameters) - .build(); - - FineTuningJob fineTuningJob = service.createFineTuningJob(request); - fineTuningJobId = fineTuningJob.getId(); - - assertNotNull(fineTuningJob); - } - - @Test - @Order(2) - void listFineTuningJobs() { - List fineTuningJobs = service.listFineTuningJobs(); - - assertTrue(fineTuningJobs.stream().anyMatch(fineTuningJob -> fineTuningJob.getId().equals(fineTuningJobId))); - } - - @Test - @Order(2) - void listFineTuningEvents() { - List events = service.listFineTuningJobEvents(fineTuningJobId); - - assertFalse(events.isEmpty()); - } - - @Test - @Order(2) - void retrieveFineTuningJob() { - FineTuningJob fineTune = service.retrieveFineTuningJob(fineTuningJobId); - - assertTrue(fineTune.getModel().startsWith("gpt-3.5-turbo")); - } - - @Test - @Order(3) - void cancelFineTuningJob() throws Exception { - FineTuningJob fineTuningJob = service.cancelFineTuningJob(fineTuningJobId); - - assertEquals("cancelled", fineTuningJob.getStatus()); - - // wait before cleaning up to prevent job failure emails - TimeUnit.SECONDS.sleep(3); - } + + static OpenAiService service; + static String fileId; + static String fineTuningJobId; + + + @BeforeAll + static void setup() throws Exception { + String token = System.getenv("OPENAI_TOKEN"); + service = new OpenAiService(token); + fileId = service.uploadFile("fine-tune", "src/test/resources/chat-fine-tuning-data.jsonl") + .getId(); + + // wait for file to be processed + TimeUnit.SECONDS.sleep(10); + } + + @AfterAll + static void teardown() { + try { + service.deleteFile(fileId); + } catch (Exception e) { + // ignore + } + } + + @Test + @Order(1) + void createFineTuningJob() { + Hyperparameters hyperparameters = Hyperparameters.builder() + .nEpochs(4) + .build(); + FineTuningJobRequest request = FineTuningJobRequest.builder() + .trainingFile(fileId) + .model("gpt-3.5-turbo") + .hyperparameters(hyperparameters) + .build(); + + FineTuningJob fineTuningJob = service.createFineTuningJob(request); + fineTuningJobId = fineTuningJob.getId(); + + assertNotNull(fineTuningJob); + } + + @Test + @Order(2) + void listFineTuningJobs() { + List fineTuningJobs = service.listFineTuningJobs(); + + assertTrue(fineTuningJobs.stream() + .anyMatch(fineTuningJob -> fineTuningJob.getId().equals(fineTuningJobId))); + } + + @Test + @Order(2) + void listFineTuningEvents() { + List events = service.listFineTuningJobEvents(fineTuningJobId); + + assertFalse(events.isEmpty()); + } + + @Test + @Order(2) + void retrieveFineTuningJob() { + FineTuningJob fineTune = service.retrieveFineTuningJob(fineTuningJobId); + + assertTrue(fineTune.getModel().startsWith("gpt-3.5-turbo")); + } + + @Test + @Order(3) + void cancelFineTuningJob() throws Exception { + FineTuningJob fineTuningJob = service.cancelFineTuningJob(fineTuningJobId); + + assertEquals("cancelled", fineTuningJob.getStatus()); + + // wait before cleaning up to prevent job failure emails + TimeUnit.SECONDS.sleep(3); + } } diff --git a/service/src/test/java/com/launchableinc/openai/service/ImageTest.java b/service/src/test/java/com/launchableinc/openai/service/ImageTest.java index e56b7907..8ca7c22b 100644 --- a/service/src/test/java/com/launchableinc/openai/service/ImageTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/ImageTest.java @@ -1,9 +1,9 @@ -package com.theokanning.openai.service; +package com.launchableinc.openai.service; -import com.theokanning.openai.image.CreateImageEditRequest; -import com.theokanning.openai.image.CreateImageRequest; -import com.theokanning.openai.image.CreateImageVariationRequest; -import com.theokanning.openai.image.Image; +import com.launchableinc.openai.image.CreateImageEditRequest; +import com.launchableinc.openai.image.CreateImageRequest; +import com.launchableinc.openai.image.CreateImageVariationRequest; +import com.launchableinc.openai.image.Image; import org.junit.jupiter.api.Test; import java.time.Duration; @@ -15,81 +15,84 @@ public class ImageTest { - static String filePath = "src/test/resources/penguin.png"; - static String fileWithAlphaPath = "src/test/resources/penguin_with_alpha.png"; - static String maskPath = "src/test/resources/mask.png"; - - String token = System.getenv("OPENAI_TOKEN"); - com.theokanning.openai.service.OpenAiService service = new OpenAiService(token, Duration.ofSeconds(30)); - - @Test - void createImageUrl() { - CreateImageRequest createImageRequest = CreateImageRequest.builder() - .prompt("penguin") - .n(3) - .size("256x256") - .user("testing") - .build(); - - List images = service.createImage(createImageRequest).getData(); - assertEquals(3, images.size()); - assertNotNull(images.get(0).getUrl()); - } - - @Test - void createImageBase64() { - CreateImageRequest createImageRequest = CreateImageRequest.builder() - .prompt("penguin") - .responseFormat("b64_json") - .user("testing") - .build(); - - List images = service.createImage(createImageRequest).getData(); - assertEquals(1, images.size()); - assertNotNull(images.get(0).getB64Json()); - } - - @Test - void createImageEdit() { - CreateImageEditRequest createImageRequest = CreateImageEditRequest.builder() - .prompt("a penguin with a red background") - .responseFormat("url") - .size("256x256") - .user("testing") - .n(2) - .build(); - - List images = service.createImageEdit(createImageRequest, fileWithAlphaPath, null).getData(); - assertEquals(2, images.size()); - assertNotNull(images.get(0).getUrl()); - } - - @Test - void createImageEditWithMask() { - CreateImageEditRequest createImageRequest = CreateImageEditRequest.builder() - .prompt("a penguin with a red hat") - .responseFormat("url") - .size("256x256") - .user("testing") - .n(2) - .build(); - - List images = service.createImageEdit(createImageRequest, filePath, maskPath).getData(); - assertEquals(2, images.size()); - assertNotNull(images.get(0).getUrl()); - } - - @Test - void createImageVariation() { - CreateImageVariationRequest createImageVariationRequest = CreateImageVariationRequest.builder() - .responseFormat("url") - .size("256x256") - .user("testing") - .n(2) - .build(); - - List images = service.createImageVariation(createImageVariationRequest, filePath).getData(); - assertEquals(2, images.size()); - assertNotNull(images.get(0).getUrl()); - } + static String filePath = "src/test/resources/penguin.png"; + static String fileWithAlphaPath = "src/test/resources/penguin_with_alpha.png"; + static String maskPath = "src/test/resources/mask.png"; + + String token = System.getenv("OPENAI_TOKEN"); + com.launchableinc.openai.service.OpenAiService service = new OpenAiService(token, + Duration.ofSeconds(30)); + + @Test + void createImageUrl() { + CreateImageRequest createImageRequest = CreateImageRequest.builder() + .prompt("penguin") + .n(3) + .size("256x256") + .user("testing") + .build(); + + List images = service.createImage(createImageRequest).getData(); + assertEquals(3, images.size()); + assertNotNull(images.get(0).getUrl()); + } + + @Test + void createImageBase64() { + CreateImageRequest createImageRequest = CreateImageRequest.builder() + .prompt("penguin") + .responseFormat("b64_json") + .user("testing") + .build(); + + List images = service.createImage(createImageRequest).getData(); + assertEquals(1, images.size()); + assertNotNull(images.get(0).getB64Json()); + } + + @Test + void createImageEdit() { + CreateImageEditRequest createImageRequest = CreateImageEditRequest.builder() + .prompt("a penguin with a red background") + .responseFormat("url") + .size("256x256") + .user("testing") + .n(2) + .build(); + + List images = service.createImageEdit(createImageRequest, fileWithAlphaPath, null) + .getData(); + assertEquals(2, images.size()); + assertNotNull(images.get(0).getUrl()); + } + + @Test + void createImageEditWithMask() { + CreateImageEditRequest createImageRequest = CreateImageEditRequest.builder() + .prompt("a penguin with a red hat") + .responseFormat("url") + .size("256x256") + .user("testing") + .n(2) + .build(); + + List images = service.createImageEdit(createImageRequest, filePath, maskPath).getData(); + assertEquals(2, images.size()); + assertNotNull(images.get(0).getUrl()); + } + + @Test + void createImageVariation() { + CreateImageVariationRequest createImageVariationRequest = CreateImageVariationRequest.builder() + .responseFormat("url") + .size("256x256") + .user("testing") + .n(2) + .build(); + + List images = service.createImageVariation(createImageVariationRequest, filePath) + .getData(); + assertEquals(2, images.size()); + assertNotNull(images.get(0).getUrl()); + } } diff --git a/service/src/test/java/com/launchableinc/openai/service/MessageTest.java b/service/src/test/java/com/launchableinc/openai/service/MessageTest.java index 06a903c0..6c609938 100644 --- a/service/src/test/java/com/launchableinc/openai/service/MessageTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/MessageTest.java @@ -1,13 +1,12 @@ -package com.theokanning.openai.service; - -import com.theokanning.openai.ListSearchParameters; -import com.theokanning.openai.file.File; -import com.theokanning.openai.messages.Message; -import com.theokanning.openai.messages.MessageFile; -import com.theokanning.openai.messages.MessageRequest; -import com.theokanning.openai.messages.ModifyMessageRequest; -import com.theokanning.openai.threads.Thread; -import com.theokanning.openai.threads.ThreadRequest; +package com.launchableinc.openai.service; + +import com.launchableinc.openai.ListSearchParameters; +import com.launchableinc.openai.file.File; +import com.launchableinc.openai.messages.Message; +import com.launchableinc.openai.messages.MessageFile; +import com.launchableinc.openai.messages.MessageRequest; +import com.launchableinc.openai.messages.ModifyMessageRequest; +import com.launchableinc.openai.threads.ThreadRequest; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -23,115 +22,116 @@ public class MessageTest { - static OpenAiService service; + static OpenAiService service; - static String threadId; - - @BeforeAll - static void setup() { - String token = System.getenv("OPENAI_TOKEN"); - service = new OpenAiService(token); - - ThreadRequest threadRequest = ThreadRequest.builder() - .build(); - threadId = service.createThread(threadRequest).getId(); - } - - @AfterAll - static void teardown() { - try { - service.deleteThread(threadId); - } catch (Exception e) { - // ignore - } - } - - @Test - void createMessage() { - File file = service.uploadFile("assistants", "src/test/resources/penguin.png"); - Map metadata = new HashMap<>(); - metadata.put("key", "value"); - - MessageRequest messageRequest = MessageRequest.builder() - .content("Hello") - .fileIds(Collections.singletonList(file.getId())) - .metadata(metadata) - .build(); - - Message message = service.createMessage(threadId, messageRequest); - - assertNotNull(message.getId()); - assertEquals("thread.message", message.getObject()); - assertEquals(1, message.getFileIds().size()); - } - - @Test - void retrieveMessage() { - String messageId = createTestMessage().getId(); - - Message message = service.retrieveMessage(threadId, messageId); - - assertEquals(messageId, message.getId()); - } - - @Test - void modifyMessage() { - String messageId = createTestMessage().getId(); - - Map metadata = new HashMap<>(); - metadata.put("key", "value"); - - ModifyMessageRequest request = ModifyMessageRequest.builder() - .metadata(metadata) - .build(); - Message message = service.modifyMessage(threadId, messageId, request); - - assertEquals(messageId, message.getId()); - assertEquals("value", message.getMetadata().get("key")); - } - - @Test - void listMessages() { - ThreadRequest threadRequest = ThreadRequest.builder() - .build(); - String separateThreadId = service.createThread(threadRequest).getId(); - createTestMessage(separateThreadId); - createTestMessage(separateThreadId); - createTestMessage(separateThreadId); - - List messages = service.listMessages(separateThreadId).getData(); - - assertEquals(3, messages.size()); - } - - @Test - void retrieveAndListMessageFile() { - File file = service.uploadFile("assistants", "src/test/resources/penguin.png"); - MessageRequest messageRequest = MessageRequest.builder() - .content("Hello") - .fileIds(Collections.singletonList(file.getId())) - .build(); - - Message message = service.createMessage(threadId, messageRequest); - - MessageFile messageFile = service.retrieveMessageFile(threadId, message.getId(), file.getId()); - - assertEquals(file.getId(), messageFile.getId()); - assertEquals(message.getId(), messageFile.getMessageId()); - - List messageFiles = service.listMessageFiles(threadId, message.getId(), new ListSearchParameters()).getData(); - assertEquals(1, messageFiles.size()); - } - - Message createTestMessage() { - return createTestMessage(threadId); - } - - Message createTestMessage(String threadId) { - MessageRequest messageRequest = MessageRequest.builder() - .content("Hello") - .build(); - - return service.createMessage(threadId, messageRequest); - } + static String threadId; + + @BeforeAll + static void setup() { + String token = System.getenv("OPENAI_TOKEN"); + service = new OpenAiService(token); + + ThreadRequest threadRequest = ThreadRequest.builder() + .build(); + threadId = service.createThread(threadRequest).getId(); + } + + @AfterAll + static void teardown() { + try { + service.deleteThread(threadId); + } catch (Exception e) { + // ignore + } + } + + @Test + void createMessage() { + File file = service.uploadFile("assistants", "src/test/resources/penguin.png"); + Map metadata = new HashMap<>(); + metadata.put("key", "value"); + + MessageRequest messageRequest = MessageRequest.builder() + .content("Hello") + .fileIds(Collections.singletonList(file.getId())) + .metadata(metadata) + .build(); + + Message message = service.createMessage(threadId, messageRequest); + + assertNotNull(message.getId()); + assertEquals("thread.message", message.getObject()); + assertEquals(1, message.getFileIds().size()); + } + + @Test + void retrieveMessage() { + String messageId = createTestMessage().getId(); + + Message message = service.retrieveMessage(threadId, messageId); + + assertEquals(messageId, message.getId()); + } + + @Test + void modifyMessage() { + String messageId = createTestMessage().getId(); + + Map metadata = new HashMap<>(); + metadata.put("key", "value"); + + ModifyMessageRequest request = ModifyMessageRequest.builder() + .metadata(metadata) + .build(); + Message message = service.modifyMessage(threadId, messageId, request); + + assertEquals(messageId, message.getId()); + assertEquals("value", message.getMetadata().get("key")); + } + + @Test + void listMessages() { + ThreadRequest threadRequest = ThreadRequest.builder() + .build(); + String separateThreadId = service.createThread(threadRequest).getId(); + createTestMessage(separateThreadId); + createTestMessage(separateThreadId); + createTestMessage(separateThreadId); + + List messages = service.listMessages(separateThreadId).getData(); + + assertEquals(3, messages.size()); + } + + @Test + void retrieveAndListMessageFile() { + File file = service.uploadFile("assistants", "src/test/resources/penguin.png"); + MessageRequest messageRequest = MessageRequest.builder() + .content("Hello") + .fileIds(Collections.singletonList(file.getId())) + .build(); + + Message message = service.createMessage(threadId, messageRequest); + + MessageFile messageFile = service.retrieveMessageFile(threadId, message.getId(), file.getId()); + + assertEquals(file.getId(), messageFile.getId()); + assertEquals(message.getId(), messageFile.getMessageId()); + + List messageFiles = service.listMessageFiles(threadId, message.getId(), + new ListSearchParameters()).getData(); + assertEquals(1, messageFiles.size()); + } + + Message createTestMessage() { + return createTestMessage(threadId); + } + + Message createTestMessage(String threadId) { + MessageRequest messageRequest = MessageRequest.builder() + .content("Hello") + .build(); + + return service.createMessage(threadId, messageRequest); + } } \ No newline at end of file diff --git a/service/src/test/java/com/launchableinc/openai/service/ModelTest.java b/service/src/test/java/com/launchableinc/openai/service/ModelTest.java index 637ed5e6..e9f96e8b 100644 --- a/service/src/test/java/com/launchableinc/openai/service/ModelTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/ModelTest.java @@ -1,6 +1,6 @@ -package com.theokanning.openai.service; +package com.launchableinc.openai.service; -import com.theokanning.openai.model.Model; +import com.launchableinc.openai.model.Model; import org.junit.jupiter.api.Test; import java.util.List; @@ -11,21 +11,21 @@ public class ModelTest { - String token = System.getenv("OPENAI_TOKEN"); - com.theokanning.openai.service.OpenAiService service = new OpenAiService(token); + String token = System.getenv("OPENAI_TOKEN"); + com.launchableinc.openai.service.OpenAiService service = new OpenAiService(token); - @Test - void listModels() { - List models = service.listModels(); + @Test + void listModels() { + List models = service.listModels(); - assertFalse(models.isEmpty()); - } + assertFalse(models.isEmpty()); + } - @Test - void getModel() { - Model model = service.getModel("babbage-002"); + @Test + void getModel() { + Model model = service.getModel("babbage-002"); - assertEquals("babbage-002", model.id); - assertEquals("system", model.ownedBy); - } + assertEquals("babbage-002", model.id); + assertEquals("system", model.ownedBy); + } } diff --git a/service/src/test/java/com/launchableinc/openai/service/ModerationTest.java b/service/src/test/java/com/launchableinc/openai/service/ModerationTest.java index f28bc083..bc477a92 100644 --- a/service/src/test/java/com/launchableinc/openai/service/ModerationTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/ModerationTest.java @@ -1,7 +1,7 @@ -package com.theokanning.openai.service; +package com.launchableinc.openai.service; -import com.theokanning.openai.moderation.Moderation; -import com.theokanning.openai.moderation.ModerationRequest; +import com.launchableinc.openai.moderation.Moderation; +import com.launchableinc.openai.moderation.ModerationRequest; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -9,18 +9,18 @@ public class ModerationTest { - String token = System.getenv("OPENAI_TOKEN"); - com.theokanning.openai.service.OpenAiService service = new OpenAiService(token); + String token = System.getenv("OPENAI_TOKEN"); + com.launchableinc.openai.service.OpenAiService service = new OpenAiService(token); - @Test - void createModeration() { - ModerationRequest moderationRequest = ModerationRequest.builder() - .input("I want to kill him") - .model("text-moderation-latest") - .build(); + @Test + void createModeration() { + ModerationRequest moderationRequest = ModerationRequest.builder() + .input("I want to kill him") + .model("text-moderation-latest") + .build(); - Moderation moderationScore = service.createModeration(moderationRequest).getResults().get(0); + Moderation moderationScore = service.createModeration(moderationRequest).getResults().get(0); - assertTrue(moderationScore.isFlagged()); - } + assertTrue(moderationScore.isFlagged()); + } } diff --git a/service/src/test/java/com/launchableinc/openai/service/OpenAiServiceTest.java b/service/src/test/java/com/launchableinc/openai/service/OpenAiServiceTest.java index 25902486..46761637 100644 --- a/service/src/test/java/com/launchableinc/openai/service/OpenAiServiceTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/OpenAiServiceTest.java @@ -1,7 +1,7 @@ -package com.theokanning.openai.service; +package com.launchableinc.openai.service; -import com.theokanning.openai.OpenAiHttpException; -import com.theokanning.openai.completion.CompletionResult; +import com.launchableinc.openai.OpenAiHttpException; +import com.launchableinc.openai.completion.CompletionResult; import io.reactivex.Single; import okhttp3.MediaType; import okhttp3.ResponseBody; @@ -13,63 +13,66 @@ public class OpenAiServiceTest { - @Test - void assertTokenNotNull() { - String token = null; - assertThrows(NullPointerException.class, () -> new OpenAiService(token)); - } + @Test + void assertTokenNotNull() { + String token = null; + assertThrows(NullPointerException.class, () -> new OpenAiService(token)); + } - @Test - void executeHappyPath() { - CompletionResult expected = new CompletionResult(); - Single single = Single.just(expected); + @Test + void executeHappyPath() { + CompletionResult expected = new CompletionResult(); + Single single = Single.just(expected); - CompletionResult actual = OpenAiService.execute(single); - assertEquals(expected, actual); - } + CompletionResult actual = OpenAiService.execute(single); + assertEquals(expected, actual); + } - @Test - void executeParseHttpError() { - String errorBody = "{\"error\":{\"message\":\"Invalid auth token\",\"type\":\"type\",\"param\":\"param\",\"code\":\"code\"}}"; - HttpException httpException = createException(errorBody, 401); - Single single = Single.error(httpException); + @Test + void executeParseHttpError() { + String errorBody = "{\"error\":{\"message\":\"Invalid auth token\",\"type\":\"type\",\"param\":\"param\",\"code\":\"code\"}}"; + HttpException httpException = createException(errorBody, 401); + Single single = Single.error(httpException); - OpenAiHttpException exception = assertThrows(OpenAiHttpException.class, () -> OpenAiService.execute(single)); + OpenAiHttpException exception = assertThrows(OpenAiHttpException.class, + () -> OpenAiService.execute(single)); - assertEquals("Invalid auth token", exception.getMessage()); - assertEquals("type", exception.type); - assertEquals("param", exception.param); - assertEquals("code", exception.code); - assertEquals(401, exception.statusCode); - } + assertEquals("Invalid auth token", exception.getMessage()); + assertEquals("type", exception.type); + assertEquals("param", exception.param); + assertEquals("code", exception.code); + assertEquals(401, exception.statusCode); + } - @Test - void executeParseUnknownProperties() { - // error body contains one unknown property and no message - String errorBody = "{\"error\":{\"unknown\":\"Invalid auth token\",\"type\":\"type\",\"param\":\"param\",\"code\":\"code\"}}"; - HttpException httpException = createException(errorBody, 401); - Single single = Single.error(httpException); + @Test + void executeParseUnknownProperties() { + // error body contains one unknown property and no message + String errorBody = "{\"error\":{\"unknown\":\"Invalid auth token\",\"type\":\"type\",\"param\":\"param\",\"code\":\"code\"}}"; + HttpException httpException = createException(errorBody, 401); + Single single = Single.error(httpException); - OpenAiHttpException exception = assertThrows(OpenAiHttpException.class, () -> OpenAiService.execute(single)); - assertNull(exception.getMessage()); - assertEquals("type", exception.type); - assertEquals("param", exception.param); - assertEquals("code", exception.code); - assertEquals(401, exception.statusCode); - } + OpenAiHttpException exception = assertThrows(OpenAiHttpException.class, + () -> OpenAiService.execute(single)); + assertNull(exception.getMessage()); + assertEquals("type", exception.type); + assertEquals("param", exception.param); + assertEquals("code", exception.code); + assertEquals(401, exception.statusCode); + } - @Test - void executeNullErrorBodyThrowOriginalError() { - // exception with a successful response creates an error without an error body - HttpException httpException = new HttpException(Response.success(new CompletionResult())); - Single single = Single.error(httpException); + @Test + void executeNullErrorBodyThrowOriginalError() { + // exception with a successful response creates an error without an error body + HttpException httpException = new HttpException(Response.success(new CompletionResult())); + Single single = Single.error(httpException); - HttpException exception = assertThrows(HttpException.class, () -> OpenAiService.execute(single)); - } + HttpException exception = assertThrows(HttpException.class, + () -> OpenAiService.execute(single)); + } - private HttpException createException(String errorBody, int code) { - ResponseBody body = ResponseBody.create(MediaType.get("application/json"), errorBody); - Response response = Response.error(code, body); - return new HttpException(response); - } + private HttpException createException(String errorBody, int code) { + ResponseBody body = ResponseBody.create(MediaType.get("application/json"), errorBody); + Response response = Response.error(code, body); + return new HttpException(response); + } } diff --git a/service/src/test/java/com/launchableinc/openai/service/ResponseBodyCallbackTest.java b/service/src/test/java/com/launchableinc/openai/service/ResponseBodyCallbackTest.java index 7e22c59c..882da2dc 100644 --- a/service/src/test/java/com/launchableinc/openai/service/ResponseBodyCallbackTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/ResponseBodyCallbackTest.java @@ -1,6 +1,6 @@ -package com.theokanning.openai.service; +package com.launchableinc.openai.service; -import com.theokanning.openai.OpenAiHttpException; +import com.launchableinc.openai.OpenAiHttpException; import io.reactivex.BackpressureStrategy; import io.reactivex.Flowable; import io.reactivex.subscribers.TestSubscriber; @@ -15,67 +15,78 @@ public class ResponseBodyCallbackTest { - @Test - void testHappyPath() { - ResponseBody body = ResponseBody.create(MediaType.get("application/json"), "data: line 1\n\ndata: line 2\n\ndata: [DONE]\n\n"); - Call call = Calls.response(body); + @Test + void testHappyPath() { + ResponseBody body = ResponseBody.create(MediaType.get("application/json"), + "data: line 1\n\ndata: line 2\n\ndata: [DONE]\n\n"); + Call call = Calls.response(body); - Flowable flowable = Flowable.create(emitter -> call.enqueue(new ResponseBodyCallback(emitter, false)), BackpressureStrategy.BUFFER); + Flowable flowable = Flowable.create( + emitter -> call.enqueue(new ResponseBodyCallback(emitter, false)), + BackpressureStrategy.BUFFER); - TestSubscriber testSubscriber = new TestSubscriber<>(); - flowable.subscribe(testSubscriber); + TestSubscriber testSubscriber = new TestSubscriber<>(); + flowable.subscribe(testSubscriber); - testSubscriber.assertComplete(); - testSubscriber.assertNoErrors(); - testSubscriber.assertValueCount(2); - assertEquals("line 1", testSubscriber.values().get(0).getData()); - assertEquals("line 2", testSubscriber.values().get(1).getData()); - } + testSubscriber.assertComplete(); + testSubscriber.assertNoErrors(); + testSubscriber.assertValueCount(2); + assertEquals("line 1", testSubscriber.values().get(0).getData()); + assertEquals("line 2", testSubscriber.values().get(1).getData()); + } - @Test - void testEmitDone() { - ResponseBody body = ResponseBody.create(MediaType.get("application/json"), "data: line 1\n\ndata: line 2\n\ndata: [DONE]\n\n"); - Call call = Calls.response(body); + @Test + void testEmitDone() { + ResponseBody body = ResponseBody.create(MediaType.get("application/json"), + "data: line 1\n\ndata: line 2\n\ndata: [DONE]\n\n"); + Call call = Calls.response(body); - Flowable flowable = Flowable.create(emitter -> call.enqueue(new ResponseBodyCallback(emitter, true)), BackpressureStrategy.BUFFER); + Flowable flowable = Flowable.create( + emitter -> call.enqueue(new ResponseBodyCallback(emitter, true)), + BackpressureStrategy.BUFFER); - TestSubscriber testSubscriber = new TestSubscriber<>(); - flowable.subscribe(testSubscriber); + TestSubscriber testSubscriber = new TestSubscriber<>(); + flowable.subscribe(testSubscriber); - testSubscriber.assertComplete(); - testSubscriber.assertNoErrors(); - testSubscriber.assertValueCount(3); - assertEquals("[DONE]", testSubscriber.values().get(2).getData()); - } + testSubscriber.assertComplete(); + testSubscriber.assertNoErrors(); + testSubscriber.assertValueCount(3); + assertEquals("[DONE]", testSubscriber.values().get(2).getData()); + } - @Test - void testSseFormatException() { - ResponseBody body = ResponseBody.create(MediaType.get("application/json"), "bad: line 1\n\ndata: line 2\n\ndata: [DONE]\n\n"); - Call call = Calls.response(body); + @Test + void testSseFormatException() { + ResponseBody body = ResponseBody.create(MediaType.get("application/json"), + "bad: line 1\n\ndata: line 2\n\ndata: [DONE]\n\n"); + Call call = Calls.response(body); - Flowable flowable = Flowable.create(emitter -> call.enqueue(new ResponseBodyCallback(emitter, true)), BackpressureStrategy.BUFFER); + Flowable flowable = Flowable.create( + emitter -> call.enqueue(new ResponseBodyCallback(emitter, true)), + BackpressureStrategy.BUFFER); - TestSubscriber testSubscriber = new TestSubscriber<>(); + TestSubscriber testSubscriber = new TestSubscriber<>(); - flowable.subscribe(testSubscriber); + flowable.subscribe(testSubscriber); - testSubscriber.assertError(SSEFormatException.class); - } + testSubscriber.assertError(SSEFormatException.class); + } - @Test - void testServerError() { - String errorBody = "{\"error\":{\"message\":\"Invalid auth token\",\"type\":\"type\",\"param\":\"param\",\"code\":\"code\"}}"; - ResponseBody body = ResponseBody.create(MediaType.get("application/json"), errorBody); - Call call = Calls.response(Response.error(401, body)); + @Test + void testServerError() { + String errorBody = "{\"error\":{\"message\":\"Invalid auth token\",\"type\":\"type\",\"param\":\"param\",\"code\":\"code\"}}"; + ResponseBody body = ResponseBody.create(MediaType.get("application/json"), errorBody); + Call call = Calls.response(Response.error(401, body)); - Flowable flowable = Flowable.create(emitter -> call.enqueue(new ResponseBodyCallback(emitter, true)), BackpressureStrategy.BUFFER); + Flowable flowable = Flowable.create( + emitter -> call.enqueue(new ResponseBodyCallback(emitter, true)), + BackpressureStrategy.BUFFER); - TestSubscriber testSubscriber = new TestSubscriber<>(); - flowable.subscribe(testSubscriber); + TestSubscriber testSubscriber = new TestSubscriber<>(); + flowable.subscribe(testSubscriber); - testSubscriber.assertError(OpenAiHttpException.class); + testSubscriber.assertError(OpenAiHttpException.class); - assertEquals("Invalid auth token", testSubscriber.errors().get(0).getMessage()); - } + assertEquals("Invalid auth token", testSubscriber.errors().get(0).getMessage()); + } } diff --git a/service/src/test/java/com/launchableinc/openai/service/RunTest.java b/service/src/test/java/com/launchableinc/openai/service/RunTest.java index 2bd0c166..f8b042f6 100644 --- a/service/src/test/java/com/launchableinc/openai/service/RunTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/RunTest.java @@ -1,15 +1,15 @@ -package com.theokanning.openai.service; +package com.launchableinc.openai.service; -import com.theokanning.openai.OpenAiResponse; -import com.theokanning.openai.assistants.Assistant; -import com.theokanning.openai.assistants.AssistantRequest; -import com.theokanning.openai.messages.Message; -import com.theokanning.openai.messages.MessageRequest; -import com.theokanning.openai.runs.Run; -import com.theokanning.openai.runs.RunCreateRequest; -import com.theokanning.openai.threads.Thread; -import com.theokanning.openai.threads.ThreadRequest; -import com.theokanning.openai.utils.TikTokensUtil; +import com.launchableinc.openai.OpenAiResponse; +import com.launchableinc.openai.assistants.Assistant; +import com.launchableinc.openai.assistants.AssistantRequest; +import com.launchableinc.openai.messages.Message; +import com.launchableinc.openai.messages.MessageRequest; +import com.launchableinc.openai.runs.Run; +import com.launchableinc.openai.runs.RunCreateRequest; +import com.launchableinc.openai.threads.Thread; +import com.launchableinc.openai.threads.ThreadRequest; +import com.launchableinc.openai.utils.TikTokensUtil; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; @@ -19,51 +19,52 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; class RunTest { - String token = System.getenv("OPENAI_TOKEN"); - OpenAiService service = new OpenAiService(token); - @Test - @Timeout(10) - void createRetrieveRun() { - AssistantRequest assistantRequest = AssistantRequest.builder() - .model(TikTokensUtil.ModelEnum.GPT_4_1106_preview.getName()) - .name("MATH_TUTOR") - .instructions("You are a personal Math Tutor.") - .build(); - Assistant assistant = service.createAssistant(assistantRequest); + String token = System.getenv("OPENAI_TOKEN"); + OpenAiService service = new OpenAiService(token); - ThreadRequest threadRequest = ThreadRequest.builder() - .build(); - Thread thread = service.createThread(threadRequest); + @Test + @Timeout(10) + void createRetrieveRun() { + AssistantRequest assistantRequest = AssistantRequest.builder() + .model(TikTokensUtil.ModelEnum.GPT_4_1106_preview.getName()) + .name("MATH_TUTOR") + .instructions("You are a personal Math Tutor.") + .build(); + Assistant assistant = service.createAssistant(assistantRequest); - MessageRequest messageRequest = MessageRequest.builder() - .content("Hello") - .build(); + ThreadRequest threadRequest = ThreadRequest.builder() + .build(); + Thread thread = service.createThread(threadRequest); - Message message = service.createMessage(thread.getId(), messageRequest); + MessageRequest messageRequest = MessageRequest.builder() + .content("Hello") + .build(); - RunCreateRequest runCreateRequest = RunCreateRequest.builder() - .assistantId(assistant.getId()) - .build(); + Message message = service.createMessage(thread.getId(), messageRequest); - Run run = service.createRun(thread.getId(), runCreateRequest); - assertNotNull(run); + RunCreateRequest runCreateRequest = RunCreateRequest.builder() + .assistantId(assistant.getId()) + .build(); - Run retrievedRun; - do { - retrievedRun = service.retrieveRun(thread.getId(), run.getId()); - assertEquals(run.getId(), retrievedRun.getId()); - } - while (!(retrievedRun.getStatus().equals("completed")) && !(retrievedRun.getStatus().equals("failed"))); + Run run = service.createRun(thread.getId(), runCreateRequest); + assertNotNull(run); + Run retrievedRun; + do { + retrievedRun = service.retrieveRun(thread.getId(), run.getId()); + assertEquals(run.getId(), retrievedRun.getId()); + } + while (!(retrievedRun.getStatus().equals("completed")) && !(retrievedRun.getStatus() + .equals("failed"))); - assertNotNull(retrievedRun); + assertNotNull(retrievedRun); - OpenAiResponse response = service.listMessages(thread.getId()); + OpenAiResponse response = service.listMessages(thread.getId()); - List messages = response.getData(); - assertEquals(2, messages.size()); - assertEquals("user", messages.get(1).getRole()); - assertEquals("assistant", messages.get(0).getRole()); - } + List messages = response.getData(); + assertEquals(2, messages.size()); + assertEquals("user", messages.get(1).getRole()); + assertEquals("assistant", messages.get(0).getRole()); + } } diff --git a/service/src/test/java/com/launchableinc/openai/service/ThreadTest.java b/service/src/test/java/com/launchableinc/openai/service/ThreadTest.java index 212653af..1b0fe91e 100644 --- a/service/src/test/java/com/launchableinc/openai/service/ThreadTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/ThreadTest.java @@ -1,9 +1,9 @@ -package com.theokanning.openai.service; +package com.launchableinc.openai.service; -import com.theokanning.openai.DeleteResult; -import com.theokanning.openai.messages.MessageRequest; -import com.theokanning.openai.threads.Thread; -import com.theokanning.openai.threads.ThreadRequest; +import com.launchableinc.openai.DeleteResult; +import com.launchableinc.openai.messages.MessageRequest; +import com.launchableinc.openai.threads.Thread; +import com.launchableinc.openai.threads.ThreadRequest; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; @@ -16,52 +16,52 @@ @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class ThreadTest { - String token = System.getenv("OPENAI_TOKEN"); - OpenAiService service = new OpenAiService(token); + String token = System.getenv("OPENAI_TOKEN"); + OpenAiService service = new OpenAiService(token); - static String threadId; + static String threadId; - @Test - @Order(1) - void createThread() { - MessageRequest messageRequest = MessageRequest.builder() - .content("Hello") - .build(); + @Test + @Order(1) + void createThread() { + MessageRequest messageRequest = MessageRequest.builder() + .content("Hello") + .build(); - ThreadRequest threadRequest = ThreadRequest.builder() - .messages(Collections.singletonList(messageRequest)) - .build(); + ThreadRequest threadRequest = ThreadRequest.builder() + .messages(Collections.singletonList(messageRequest)) + .build(); - Thread thread = service.createThread(threadRequest); - threadId = thread.getId(); - assertEquals("thread", thread.getObject()); - } + Thread thread = service.createThread(threadRequest); + threadId = thread.getId(); + assertEquals("thread", thread.getObject()); + } - @Test - @Order(2) - void retrieveThread() { - Thread thread = service.retrieveThread(threadId); - System.out.println(thread.getMetadata()); - assertEquals("thread", thread.getObject()); - } - - @Test - @Order(3) - void modifyThread() { - Map metadata = new HashMap<>(); - metadata.put("action", "modify"); - ThreadRequest threadRequest = ThreadRequest.builder() - .metadata(metadata) - .build(); - Thread thread = service.modifyThread(threadId, threadRequest); - assertEquals("thread", thread.getObject()); - assertEquals("modify", thread.getMetadata().get("action")); - } - - @Test - @Order(4) - void deleteThread() { - DeleteResult deleteResult = service.deleteThread(threadId); - assertEquals("thread.deleted", deleteResult.getObject()); - } + @Test + @Order(2) + void retrieveThread() { + Thread thread = service.retrieveThread(threadId); + System.out.println(thread.getMetadata()); + assertEquals("thread", thread.getObject()); + } + + @Test + @Order(3) + void modifyThread() { + Map metadata = new HashMap<>(); + metadata.put("action", "modify"); + ThreadRequest threadRequest = ThreadRequest.builder() + .metadata(metadata) + .build(); + Thread thread = service.modifyThread(threadId, threadRequest); + assertEquals("thread", thread.getObject()); + assertEquals("modify", thread.getMetadata().get("action")); + } + + @Test + @Order(4) + void deleteThread() { + DeleteResult deleteResult = service.deleteThread(threadId); + assertEquals("thread.deleted", deleteResult.getObject()); + } } \ No newline at end of file From 28c95c590f6ad8ae0727d56436052df2c3dc256c Mon Sep 17 00:00:00 2001 From: Konboi Date: Fri, 16 Feb 2024 13:51:13 +0900 Subject: [PATCH 06/40] Add dependencies to pass test --- api/build.gradle | 2 ++ 1 file changed, 2 insertions(+) diff --git a/api/build.gradle b/api/build.gradle index db97b833..054a90ae 100644 --- a/api/build.gradle +++ b/api/build.gradle @@ -7,6 +7,8 @@ dependencies { api libs.jtokkit compileOnly libs.lombok annotationProcessor libs.lombok + testCompileOnly libs.lombok // Ensure Lombok is available for test compilation + testAnnotationProcessor libs.lombok // Process Lombok annotations in test code testImplementation libs.jacksonDatabind testImplementation(platform(libs.junitBom)) From 32c9c44a6e119017ce5ed7e006c4fef800004ee1 Mon Sep 17 00:00:00 2001 From: Konboi Date: Fri, 16 Feb 2024 14:40:00 +0900 Subject: [PATCH 07/40] don't execute test when OPENAI_TOKEN isn't set --- .../openai/service/AssistantFunctionTest.java | 16 ++++++++++++---- .../openai/service/AssistantTest.java | 12 +++++++++++- .../launchableinc/openai/service/AudioTest.java | 12 ++++++++++-- .../openai/service/ChatCompletionTest.java | 15 +++++++++++++-- .../openai/service/CompletionTest.java | 14 ++++++++++++-- .../launchableinc/openai/service/EditTest.java | 13 +++++++++++-- .../openai/service/EmbeddingTest.java | 13 +++++++++++-- .../launchableinc/openai/service/FileTest.java | 15 +++++++++++++-- .../openai/service/FineTuneTest.java | 11 ++++++++--- .../openai/service/FineTuningTest.java | 8 +++++++- .../launchableinc/openai/service/ImageTest.java | 14 +++++++++++--- .../openai/service/MessageTest.java | 7 ++++++- .../launchableinc/openai/service/ModelTest.java | 14 ++++++++++++-- .../openai/service/ModerationTest.java | 13 +++++++++++-- .../launchableinc/openai/service/RunTest.java | 13 +++++++++++-- .../launchableinc/openai/service/ThreadTest.java | 13 +++++++++++-- 16 files changed, 170 insertions(+), 33 deletions(-) diff --git a/service/src/test/java/com/launchableinc/openai/service/AssistantFunctionTest.java b/service/src/test/java/com/launchableinc/openai/service/AssistantFunctionTest.java index 1c21dd01..56f2975b 100644 --- a/service/src/test/java/com/launchableinc/openai/service/AssistantFunctionTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/AssistantFunctionTest.java @@ -26,6 +26,8 @@ import com.launchableinc.openai.threads.Thread; import com.launchableinc.openai.threads.ThreadRequest; import com.launchableinc.openai.utils.TikTokensUtil; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.time.Duration; @@ -33,17 +35,23 @@ import java.util.List; import java.util.Map; -import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; class AssistantFunctionTest { - String token = System.getenv("OPENAI_TOKEN"); - OpenAiService service = new OpenAiService(token, Duration.ofMinutes(1)); + static final private String token = System.getenv("OPENAI_TOKEN"); + + static OpenAiService service; + + @BeforeAll + static void setup() { + Assumptions.assumeTrue(token != null && !token.isEmpty()); + service = new OpenAiService(token, Duration.ofMinutes(1)); + } + @Test void createRetrieveRun() throws JsonProcessingException { - ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); diff --git a/service/src/test/java/com/launchableinc/openai/service/AssistantTest.java b/service/src/test/java/com/launchableinc/openai/service/AssistantTest.java index c3861616..880832f9 100644 --- a/service/src/test/java/com/launchableinc/openai/service/AssistantTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/AssistantTest.java @@ -17,13 +17,23 @@ @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class AssistantTest { - static OpenAiService service = new OpenAiService(System.getenv("OPENAI_TOKEN")); + static final private String token = System.getenv("OPENAI_TOKEN"); + static String assistantId; static String fileId; + static OpenAiService service; + + @BeforeAll + static void setup() { + Assumptions.assumeTrue(token != null && !token.isEmpty()); + service = new OpenAiService(token); + } @AfterAll static void teardown() { + Assumptions.assumeTrue(token != null && !token.isEmpty()); + OpenAiService service = new OpenAiService(token); try { service.deleteAssistantFile(assistantId, fileId); } catch (Exception e) { diff --git a/service/src/test/java/com/launchableinc/openai/service/AudioTest.java b/service/src/test/java/com/launchableinc/openai/service/AudioTest.java index 45ff5337..8a16e82b 100644 --- a/service/src/test/java/com/launchableinc/openai/service/AudioTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/AudioTest.java @@ -5,6 +5,8 @@ import com.launchableinc.openai.audio.CreateTranslationRequest; import com.launchableinc.openai.audio.TranscriptionResult; import com.launchableinc.openai.audio.TranslationResult; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.io.IOException; @@ -22,8 +24,14 @@ public class AudioTest { static String koreanAudioFilePath = "src/test/resources/korean-hello.mp3"; - String token = System.getenv("OPENAI_TOKEN"); - OpenAiService service = new OpenAiService(token, Duration.ofSeconds(30)); + static final private String token = System.getenv("OPENAI_TOKEN"); + static OpenAiService service; + + @BeforeAll + static void setup() { + Assumptions.assumeTrue(token != null && !token.isEmpty()); + service = new OpenAiService(token, Duration.ofSeconds(30)); + } @Test void createTranscription() { diff --git a/service/src/test/java/com/launchableinc/openai/service/ChatCompletionTest.java b/service/src/test/java/com/launchableinc/openai/service/ChatCompletionTest.java index d84d8574..dc624533 100644 --- a/service/src/test/java/com/launchableinc/openai/service/ChatCompletionTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/ChatCompletionTest.java @@ -5,6 +5,8 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.launchableinc.openai.completion.chat.*; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.util.*; @@ -13,6 +15,17 @@ class ChatCompletionTest { + static final private String token = System.getenv("OPENAI_TOKEN"); + + static OpenAiService service; + + @BeforeAll + static void setup() { + Assumptions.assumeTrue(token != null && !token.isEmpty()); + service = new OpenAiService(token); + } + + static class Weather { @JsonPropertyDescription("City and state, for example: León, Guanajuato") @@ -42,8 +55,6 @@ public WeatherResponse(String location, WeatherUnit unit, int temperature, Strin } } - String token = System.getenv("OPENAI_TOKEN"); - OpenAiService service = new OpenAiService(token); @Test void createChatCompletion() { diff --git a/service/src/test/java/com/launchableinc/openai/service/CompletionTest.java b/service/src/test/java/com/launchableinc/openai/service/CompletionTest.java index 728e44e8..fe2b5870 100644 --- a/service/src/test/java/com/launchableinc/openai/service/CompletionTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/CompletionTest.java @@ -3,6 +3,8 @@ import com.launchableinc.openai.completion.CompletionChoice; import com.launchableinc.openai.completion.CompletionChunk; import com.launchableinc.openai.completion.CompletionRequest; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.util.ArrayList; @@ -14,8 +16,16 @@ public class CompletionTest { - String token = System.getenv("OPENAI_TOKEN"); - OpenAiService service = new OpenAiService(token); + static final private String token = System.getenv("OPENAI_TOKEN"); + + static OpenAiService service; + + @BeforeAll + static void setup() { + Assumptions.assumeTrue(token != null && !token.isEmpty()); + service = new OpenAiService(token); + } + @Test void createCompletion() { diff --git a/service/src/test/java/com/launchableinc/openai/service/EditTest.java b/service/src/test/java/com/launchableinc/openai/service/EditTest.java index b2574084..54091e1d 100644 --- a/service/src/test/java/com/launchableinc/openai/service/EditTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/EditTest.java @@ -3,14 +3,23 @@ import com.launchableinc.openai.OpenAiHttpException; import com.launchableinc.openai.edit.EditRequest; import com.launchableinc.openai.edit.EditResult; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertNotNull; public class EditTest { - String token = System.getenv("OPENAI_TOKEN"); - com.launchableinc.openai.service.OpenAiService service = new OpenAiService(token); + static final private String token = System.getenv("OPENAI_TOKEN"); + + static OpenAiService service; + + @BeforeAll + static void setup() { + Assumptions.assumeTrue(token != null && !token.isEmpty()); + service = new OpenAiService(token); + } @Test void edit() throws OpenAiHttpException { diff --git a/service/src/test/java/com/launchableinc/openai/service/EmbeddingTest.java b/service/src/test/java/com/launchableinc/openai/service/EmbeddingTest.java index 44d33d99..64807dcd 100644 --- a/service/src/test/java/com/launchableinc/openai/service/EmbeddingTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/EmbeddingTest.java @@ -2,6 +2,8 @@ import com.launchableinc.openai.embedding.Embedding; import com.launchableinc.openai.embedding.EmbeddingRequest; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.util.Collections; @@ -12,8 +14,15 @@ public class EmbeddingTest { - String token = System.getenv("OPENAI_TOKEN"); - com.launchableinc.openai.service.OpenAiService service = new OpenAiService(token); + static final private String token = System.getenv("OPENAI_TOKEN"); + + static OpenAiService service; + + @BeforeAll + static void setup() { + Assumptions.assumeTrue(token != null && !token.isEmpty()); + service = new OpenAiService(token); + } @Test void createEmbeddings() { diff --git a/service/src/test/java/com/launchableinc/openai/service/FileTest.java b/service/src/test/java/com/launchableinc/openai/service/FileTest.java index 46dc034a..757dac9a 100644 --- a/service/src/test/java/com/launchableinc/openai/service/FileTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/FileTest.java @@ -2,6 +2,9 @@ import com.launchableinc.openai.DeleteResult; import com.launchableinc.openai.file.File; +import java.time.Duration; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; @@ -22,9 +25,17 @@ public class FileTest { static String filePath = "src/test/resources/fine-tuning-data.jsonl"; - String token = System.getenv("OPENAI_TOKEN"); - OpenAiService service = new OpenAiService(token); static String fileId; + static final private String token = System.getenv("OPENAI_TOKEN"); + + static OpenAiService service; + + @BeforeAll + static void setup() { + Assumptions.assumeTrue(token != null && !token.isEmpty()); + service = new OpenAiService(token); + } + @Test @Order(1) diff --git a/service/src/test/java/com/launchableinc/openai/service/FineTuneTest.java b/service/src/test/java/com/launchableinc/openai/service/FineTuneTest.java index 3afbf279..6eceb048 100644 --- a/service/src/test/java/com/launchableinc/openai/service/FineTuneTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/FineTuneTest.java @@ -14,14 +14,18 @@ @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class FineTuneTest { - static com.launchableinc.openai.service.OpenAiService service; + + static final private String token = System.getenv("OPENAI_TOKEN"); + + static OpenAiService service; + static String fileId; static String fineTuneId; - @BeforeAll static void setup() throws Exception { - String token = System.getenv("OPENAI_TOKEN"); + Assumptions.assumeTrue(token != null && !token.isEmpty()); + service = new OpenAiService(token); fileId = service.uploadFile("fine-tune", "src/test/resources/fine-tuning-data.jsonl").getId(); @@ -31,6 +35,7 @@ static void setup() throws Exception { @AfterAll static void teardown() { + Assumptions.assumeTrue(token != null && !token.isEmpty()); service.deleteFile(fileId); } diff --git a/service/src/test/java/com/launchableinc/openai/service/FineTuningTest.java b/service/src/test/java/com/launchableinc/openai/service/FineTuningTest.java index ef7b409b..ef7e28a1 100644 --- a/service/src/test/java/com/launchableinc/openai/service/FineTuningTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/FineTuningTest.java @@ -14,14 +14,18 @@ @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class FineTuningTest { + static final private String token = System.getenv("OPENAI_TOKEN"); + static OpenAiService service; + static String fileId; static String fineTuningJobId; @BeforeAll static void setup() throws Exception { - String token = System.getenv("OPENAI_TOKEN"); + Assumptions.assumeTrue(token != null && !token.isEmpty()); + service = new OpenAiService(token); fileId = service.uploadFile("fine-tune", "src/test/resources/chat-fine-tuning-data.jsonl") .getId(); @@ -32,6 +36,8 @@ static void setup() throws Exception { @AfterAll static void teardown() { + Assumptions.assumeTrue(token != null && !token.isEmpty()); + try { service.deleteFile(fileId); } catch (Exception e) { diff --git a/service/src/test/java/com/launchableinc/openai/service/ImageTest.java b/service/src/test/java/com/launchableinc/openai/service/ImageTest.java index 8ca7c22b..fa3d2653 100644 --- a/service/src/test/java/com/launchableinc/openai/service/ImageTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/ImageTest.java @@ -4,6 +4,8 @@ import com.launchableinc.openai.image.CreateImageRequest; import com.launchableinc.openai.image.CreateImageVariationRequest; import com.launchableinc.openai.image.Image; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.time.Duration; @@ -19,9 +21,15 @@ public class ImageTest { static String fileWithAlphaPath = "src/test/resources/penguin_with_alpha.png"; static String maskPath = "src/test/resources/mask.png"; - String token = System.getenv("OPENAI_TOKEN"); - com.launchableinc.openai.service.OpenAiService service = new OpenAiService(token, - Duration.ofSeconds(30)); + static final private String token = System.getenv("OPENAI_TOKEN"); + + static OpenAiService service; + + @BeforeAll + static void setup() { + Assumptions.assumeTrue(token != null && !token.isEmpty()); + service = new OpenAiService(token, Duration.ofSeconds(30)); + } @Test void createImageUrl() { diff --git a/service/src/test/java/com/launchableinc/openai/service/MessageTest.java b/service/src/test/java/com/launchableinc/openai/service/MessageTest.java index 6c609938..279b13f1 100644 --- a/service/src/test/java/com/launchableinc/openai/service/MessageTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/MessageTest.java @@ -8,6 +8,7 @@ import com.launchableinc.openai.messages.ModifyMessageRequest; import com.launchableinc.openai.threads.ThreadRequest; import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -22,13 +23,17 @@ public class MessageTest { + + static final private String token = System.getenv("OPENAI_TOKEN"); + static OpenAiService service; static String threadId; @BeforeAll static void setup() { - String token = System.getenv("OPENAI_TOKEN"); + Assumptions.assumeTrue(token != null && !token.isEmpty()); + service = new OpenAiService(token); ThreadRequest threadRequest = ThreadRequest.builder() diff --git a/service/src/test/java/com/launchableinc/openai/service/ModelTest.java b/service/src/test/java/com/launchableinc/openai/service/ModelTest.java index e9f96e8b..dd97579d 100644 --- a/service/src/test/java/com/launchableinc/openai/service/ModelTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/ModelTest.java @@ -1,6 +1,8 @@ package com.launchableinc.openai.service; import com.launchableinc.openai.model.Model; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.util.List; @@ -11,8 +13,16 @@ public class ModelTest { - String token = System.getenv("OPENAI_TOKEN"); - com.launchableinc.openai.service.OpenAiService service = new OpenAiService(token); + + static final private String token = System.getenv("OPENAI_TOKEN"); + + static OpenAiService service; + + @BeforeAll + static void setup() { + Assumptions.assumeTrue(token != null && !token.isEmpty()); + service = new OpenAiService(token); + } @Test void listModels() { diff --git a/service/src/test/java/com/launchableinc/openai/service/ModerationTest.java b/service/src/test/java/com/launchableinc/openai/service/ModerationTest.java index bc477a92..cb24703a 100644 --- a/service/src/test/java/com/launchableinc/openai/service/ModerationTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/ModerationTest.java @@ -2,6 +2,8 @@ import com.launchableinc.openai.moderation.Moderation; import com.launchableinc.openai.moderation.ModerationRequest; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -9,8 +11,15 @@ public class ModerationTest { - String token = System.getenv("OPENAI_TOKEN"); - com.launchableinc.openai.service.OpenAiService service = new OpenAiService(token); + static final private String token = System.getenv("OPENAI_TOKEN"); + + static OpenAiService service; + + @BeforeAll + static void setup() { + Assumptions.assumeTrue(token != null && !token.isEmpty()); + service = new OpenAiService(token); + } @Test void createModeration() { diff --git a/service/src/test/java/com/launchableinc/openai/service/RunTest.java b/service/src/test/java/com/launchableinc/openai/service/RunTest.java index f8b042f6..fc68c10a 100644 --- a/service/src/test/java/com/launchableinc/openai/service/RunTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/RunTest.java @@ -10,6 +10,8 @@ import com.launchableinc.openai.threads.Thread; import com.launchableinc.openai.threads.ThreadRequest; import com.launchableinc.openai.utils.TikTokensUtil; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; @@ -20,8 +22,15 @@ class RunTest { - String token = System.getenv("OPENAI_TOKEN"); - OpenAiService service = new OpenAiService(token); + static final private String token = System.getenv("OPENAI_TOKEN"); + + static OpenAiService service; + + @BeforeAll + static void setup() { + Assumptions.assumeTrue(token != null && !token.isEmpty()); + service = new OpenAiService(token); + } @Test @Timeout(10) diff --git a/service/src/test/java/com/launchableinc/openai/service/ThreadTest.java b/service/src/test/java/com/launchableinc/openai/service/ThreadTest.java index 1b0fe91e..6c68856c 100644 --- a/service/src/test/java/com/launchableinc/openai/service/ThreadTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/ThreadTest.java @@ -4,6 +4,8 @@ import com.launchableinc.openai.messages.MessageRequest; import com.launchableinc.openai.threads.Thread; import com.launchableinc.openai.threads.ThreadRequest; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; @@ -16,11 +18,18 @@ @TestMethodOrder(MethodOrderer.OrderAnnotation.class) public class ThreadTest { - String token = System.getenv("OPENAI_TOKEN"); - OpenAiService service = new OpenAiService(token); + static final private String token = System.getenv("OPENAI_TOKEN"); + + static OpenAiService service; static String threadId; + @BeforeAll + static void setup() { + Assumptions.assumeTrue(token != null && !token.isEmpty()); + service = new OpenAiService(token); + } + @Test @Order(1) void createThread() { From 71b6dc0241bd05e99bd5d0f9dc5c236d5361c232 Mon Sep 17 00:00:00 2001 From: Konboi Date: Wed, 28 Feb 2024 15:29:35 +0900 Subject: [PATCH 08/40] theokanning -> launchableinc --- README.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 4a9ee5d8..fc292a3e 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ -![Maven Central](https://img.shields.io/maven-central/v/com.theokanning.openai-gpt3-java/client?color=blue) +![Maven Central](https://img.shields.io/maven-central/v/com.launchableinc.openai-java/client?color=blue) > ⚠️OpenAI has deprecated all Engine-based APIs. -> See [Deprecated Endpoints](https://github.com/TheoKanning/openai-java#deprecated-endpoints) below +> See [Deprecated Endpoints](https://github.com/launchableinc/openai-java#deprecated-endpoints) below > for more info. # OpenAI-Java @@ -40,14 +40,14 @@ as well as an example project using the service. ### Gradle -`implementation 'com.theokanning.openai-gpt3-java::'` +`implementation 'com.launchableinc.openai-java::'` ### Maven ```xml - com.launchableinc.openai-gpt3-java + com.launchableinc.openai-java {api|client|service} version @@ -63,7 +63,7 @@ Your client will need to use snake case to work with the OpenAI API. ### Retrofit client If you're using retrofit, you can import the `client` module and use -the [OpenAiApi](client/src/main/java/com/theokanning/openai/OpenAiApi.java). +the [OpenAiApi](client/src/main/java/com/launchableincc/openai/OpenAiApi.java). You'll have to add your auth token as a header ( see [AuthenticationInterceptor](client/src/main/java/com/theokanning/openai/AuthenticationInterceptor.java)) and set your converter factory to use snake case and only include non-null fields. @@ -217,7 +217,7 @@ stream: [OpenAiApiFunctionsWithStreamExample.java](example/src/main/java/example ### Streaming thread shutdown If you want to shut down your process immediately after streaming responses, -call `OpenAiService.shutdownExecutor()`. +call `OpenAiService.shutdownExecutor()`. This is not necessary for non-streaming calls. ## Running the example project @@ -252,7 +252,7 @@ Or functions with 'stream' mode enabled: ### Does this support GPT-4? Yes! GPT-4 uses the ChatCompletion Api, and you can see the latest model -options [here](https://platform.openai.com/docs/models/gpt-4). +options [here](https://platform.openai.com/docs/models/gpt-4). GPT-4 is currently in a limited beta (as of 4/1/23), so make sure you have access before trying to use it. @@ -270,8 +270,8 @@ Make sure that OpenAI is available in your country. ### Why doesn't OpenAiService support x configuration option? -Many projects use OpenAiService, and in order to support them best I've kept it extremely simple. -You can create your own OpenAiApi instance to customize headers, timeouts, base urls etc. +Many projects use OpenAiService, and in order to support them best I've kept it extremely simple. +You can create your own OpenAiApi instance to customize headers, timeouts, base urls etc. If you want features like retry logic and async calls, you'll have to make an `OpenAiApi` instance and call it directly instead of using `OpenAiService` From 1b197110b0e5706adc383e47a6bbd4d7f0fd8a66 Mon Sep 17 00:00:00 2001 From: Konboi Date: Wed, 28 Feb 2024 15:37:38 +0900 Subject: [PATCH 09/40] setup launchable --- .github/workflows/test.yml | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index ba858c55..df173ad2 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -5,17 +5,31 @@ on: branches: [ main ] pull_request: branches: [ main ] + +env: + LAUNCHABLE_TOKEN: ${{ secrets.LAUNCHABLE_TOKEN }} + # OPENAI_TOKEN: ${{ secrets.OPENAI_TOKEN }} + jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + # for setup launchable command + - uses: actions/setup-python@v5 + - name: Install launchable CLI + run: | + pip install launchable - name: Set up JDK 1.8 uses: actions/setup-java@v4 with: distribution: temurin java-version: 8 + - name: Record commits and build + run: 'launchable record build --name "$GITHUB_RUN_ID" --source .' - name: Test run: ./gradlew test --stacktrace - #env: - # OPENAI_TOKEN: ${{ secrets.OPENAI_TOKEN }} + - name: Record + run: launchable record tests gradle **/build/test-results/test/*.xml + if: always() + From 623000ac57b81e08d188e1a9ef3aae70ca19c8f4 Mon Sep 17 00:00:00 2001 From: Konboi Date: Wed, 28 Feb 2024 15:45:48 +0900 Subject: [PATCH 10/40] rm template at once --- .github/pull_request_template.md | 12 ------------ 1 file changed, 12 deletions(-) delete mode 100644 .github/pull_request_template.md diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md deleted file mode 100644 index fc0a8d1f..00000000 --- a/.github/pull_request_template.md +++ /dev/null @@ -1,12 +0,0 @@ -Thanks for submitting a pull request! Please check CONTRIBUTING.md for style guidelines. - -### Changes -Describe your changes here - -### New API Checklist -See CONTRIBUTING.md for more info. - -1. [ ] Documentation for every variable -2. [ ] Class-level documentation -3. [ ] POJO JSON parsing tests -4. [ ] Service integration tests \ No newline at end of file From 345d4c6fc7a52abbbe12e69496bd775fd4d76f83 Mon Sep 17 00:00:00 2001 From: Konboi Date: Wed, 28 Feb 2024 15:47:10 +0900 Subject: [PATCH 11/40] fix package path --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index fc292a3e..266b9849 100644 --- a/README.md +++ b/README.md @@ -65,13 +65,13 @@ Your client will need to use snake case to work with the OpenAI API. If you're using retrofit, you can import the `client` module and use the [OpenAiApi](client/src/main/java/com/launchableincc/openai/OpenAiApi.java). You'll have to add your auth token as a header ( -see [AuthenticationInterceptor](client/src/main/java/com/theokanning/openai/AuthenticationInterceptor.java)) +see [AuthenticationInterceptor](client/src/main/java/com/launchableinc/openai/AuthenticationInterceptor.java)) and set your converter factory to use snake case and only include non-null fields. ### OpenAiService If you're looking for the fastest solution, import the `service` module and -use [OpenAiService](service/src/main/java/com/theokanning/openai/service/OpenAiService.java). +use [OpenAiService](service/src/main/java/com/launchableinc/openai/service/OpenAiService.java). > ⚠️The OpenAiService in the client module is deprecated, please switch to the new version in the > service module. From 7b050150d73ef55670fbf114371476c9359c9800 Mon Sep 17 00:00:00 2001 From: Konboi Date: Wed, 28 Feb 2024 16:28:12 +0900 Subject: [PATCH 12/40] update publish config --- build.gradle | 9 ++++++--- gradle.properties | 12 ++++++------ 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/build.gradle b/build.gradle index 23e4f934..eb40c8c4 100644 --- a/build.gradle +++ b/build.gradle @@ -1,11 +1,14 @@ plugins { - id "com.vanniktech.maven.publish" version "0.19.0" apply false + id "com.vanniktech.maven.publish" version "0.27.0" } +import com.vanniktech.maven.publish.SonatypeHost + allprojects { plugins.withId("com.vanniktech.maven.publish") { - mavenPublish { - sonatypeHost = "S01" + mavenPublishing { + // Want to publish to so1.oss.sonatype.org + publishToMavenCentral(SonatypeHost.S01) } } } diff --git a/gradle.properties b/gradle.properties index 221dca72..4a732f1a 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,14 +1,14 @@ GROUP=com.launchableinc.openai-java VERSION_NAME=0.1.0 -POM_URL=https://github.com/launchableinc/openai-java -POM_SCM_URL=https://github.com/launchableinc/openai-java -POM_SCM_CONNECTION=https://github.com/launchableinc/openai-java.git -POM_SCM_DEV_CONNECTION=https://github.com/launchableinc/openai-java.git +POM_URL=https://launchableinc.com +POM_SCM_URL=scm:git:git@github.com:launchableinc/openai-java.git +POM_SCM_CONNECTION=scm:git:git@github.com:launchableinc/openai-java.git +POM_SCM_DEV_CONNECTION=scm:git:git@github.com:launchableinc/openai-java.git POM_LICENSE_NAME=The MIT License POM_LICENSE_URL=https://www.mit.edu/~amini/LICENSE.md POM_LICENSE_DIST=repo -POM_DEVELOPER_ID=Launchableinc -POM_DEVELOPER_NAME=Launchable,inc. +POM_DEVELOPER_ID=engineering +POM_DEVELOPER_NAME=Engineering org.gradle.parallel=true org.gradle.caching=true From 19379ae83e20f99662281bf6c53ce4a58e0f8ddd Mon Sep 17 00:00:00 2001 From: Konboi Date: Wed, 28 Feb 2024 16:42:36 +0900 Subject: [PATCH 13/40] lazy load --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index eb40c8c4..6a059710 100644 --- a/build.gradle +++ b/build.gradle @@ -1,5 +1,5 @@ plugins { - id "com.vanniktech.maven.publish" version "0.27.0" + id "com.vanniktech.maven.publish" version "0.27.0" apply false } import com.vanniktech.maven.publish.SonatypeHost From 437815457767995bd0498759529260f5213db2ee Mon Sep 17 00:00:00 2001 From: Konboi Date: Wed, 28 Feb 2024 16:45:55 +0900 Subject: [PATCH 14/40] fix version to support Java 8 --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 6a059710..5a2d8090 100644 --- a/build.gradle +++ b/build.gradle @@ -1,5 +1,5 @@ plugins { - id "com.vanniktech.maven.publish" version "0.27.0" apply false + id "com.vanniktech.maven.publish" version "0.22.0" } import com.vanniktech.maven.publish.SonatypeHost From 7144ed2da45ac3253899a172e5d1a13ef36830b4 Mon Sep 17 00:00:00 2001 From: Konboi Date: Tue, 5 Mar 2024 20:09:31 +0900 Subject: [PATCH 15/40] need to sign phase --- build.gradle | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index 5a2d8090..68850db6 100644 --- a/build.gradle +++ b/build.gradle @@ -7,8 +7,9 @@ import com.vanniktech.maven.publish.SonatypeHost allprojects { plugins.withId("com.vanniktech.maven.publish") { mavenPublishing { - // Want to publish to so1.oss.sonatype.org - publishToMavenCentral(SonatypeHost.S01) + // Want to publish to so1.oss.sonatype.org + publishToMavenCentral(SonatypeHost.S01) + signAllPublications() } } } From a0fcf31dc89ab594dcfb16726d0e4cc08c335a94 Mon Sep 17 00:00:00 2001 From: Konboi Date: Wed, 6 Mar 2024 16:16:09 +0900 Subject: [PATCH 16/40] fix properties --- gradle.properties | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 4a732f1a..0810a615 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,5 +1,7 @@ -GROUP=com.launchableinc.openai-java +GROUP=com.launchableinc + VERSION_NAME=0.1.0 +POM_ARTIFACT_ID=openai-java POM_URL=https://launchableinc.com POM_SCM_URL=scm:git:git@github.com:launchableinc/openai-java.git POM_SCM_CONNECTION=scm:git:git@github.com:launchableinc/openai-java.git From 02b4ec527c1c740d01f214d57caad88a8bd23651 Mon Sep 17 00:00:00 2001 From: Konboi Date: Wed, 6 Mar 2024 16:41:45 +0900 Subject: [PATCH 17/40] set `true` to release automatically --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 68850db6..7c921414 100644 --- a/build.gradle +++ b/build.gradle @@ -8,7 +8,7 @@ allprojects { plugins.withId("com.vanniktech.maven.publish") { mavenPublishing { // Want to publish to so1.oss.sonatype.org - publishToMavenCentral(SonatypeHost.S01) + publishToMavenCentral(SonatypeHost.S01,true) signAllPublications() } } From 6f6cd8474968872367893cc72190c2ee8a69cfd7 Mon Sep 17 00:00:00 2001 From: Konboi Date: Wed, 6 Mar 2024 17:25:25 +0900 Subject: [PATCH 18/40] fix group name --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 0810a615..b4fe5434 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,4 +1,4 @@ -GROUP=com.launchableinc +GROUP=com.launchableinc.openai-java VERSION_NAME=0.1.0 POM_ARTIFACT_ID=openai-java From 5a16279bb6bd6ed56c990be08144e4bc0559aeb8 Mon Sep 17 00:00:00 2001 From: Konboi Date: Thu, 7 Mar 2024 16:22:23 +0900 Subject: [PATCH 19/40] introduce tagpr --- .github/workflows/publish.yml | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 6e978294..c474f00b 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -2,29 +2,38 @@ name: Publish on: push: - tags: - - '[0-9]+.[0-9]+.[0-9]+' - + branches: + - main jobs: - publish: + tagpr: + permissions: + actions: write + contents: write + pull-requests: write runs-on: ubuntu-latest - + outputs: + tag: ${{ steps.run-tagpr.outputs.tag }} steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 + - uses: Songmu/tagpr@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + publish: + needs: tagpr + if: needs.tagpr.outputs.tag != '' || github.event_name == 'workflow_dispatch' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 - name: Set up JDK 1.8 uses: actions/setup-java@v3 with: distribution: temurin java-version: 8 - - name: Test run: ./gradlew test - env: - OPENAI_TOKEN: ${{ secrets.OPENAI_TOKEN }} - - name: Publish - run: ./gradlew build publish --no-parallel + run: ./gradlew publishAllPublicationsToMavenCentralRepository env: ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.SONATYPE_NEXUS_USERNAME }} ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.SONATYPE_NEXUS_PASSWORD }} From 462d7aff60ed5b4637871fbfe9874e653b94b260 Mon Sep 17 00:00:00 2001 From: Konboi Date: Thu, 7 Mar 2024 16:22:49 +0900 Subject: [PATCH 20/40] fix indent --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 7c921414..186df055 100644 --- a/build.gradle +++ b/build.gradle @@ -8,7 +8,7 @@ allprojects { plugins.withId("com.vanniktech.maven.publish") { mavenPublishing { // Want to publish to so1.oss.sonatype.org - publishToMavenCentral(SonatypeHost.S01,true) + publishToMavenCentral(SonatypeHost.S01, true) signAllPublications() } } From e2e7d3b8a02cd1a15a07399c67d0056e959539f6 Mon Sep 17 00:00:00 2001 From: Konboi Date: Thu, 7 Mar 2024 17:04:37 +0900 Subject: [PATCH 21/40] Support response json format --- .../chat/ChatCompletionRequest.java | 8 +++++ .../completion/chat/ChatResponseFormat.java | 31 +++++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 api/src/main/java/com/launchableinc/openai/completion/chat/ChatResponseFormat.java diff --git a/api/src/main/java/com/launchableinc/openai/completion/chat/ChatCompletionRequest.java b/api/src/main/java/com/launchableinc/openai/completion/chat/ChatCompletionRequest.java index 4bc5f5da..54332ce0 100644 --- a/api/src/main/java/com/launchableinc/openai/completion/chat/ChatCompletionRequest.java +++ b/api/src/main/java/com/launchableinc/openai/completion/chat/ChatCompletionRequest.java @@ -27,6 +27,14 @@ public class ChatCompletionRequest { */ List messages; + /** + * An object specifying 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. + * https://platform.openai.com/docs/api-reference/chat/create#chat-create-response_format + */ + @JsonProperty("response_format") + ChatResponseFormat responseFormat; + /** * 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.
We diff --git a/api/src/main/java/com/launchableinc/openai/completion/chat/ChatResponseFormat.java b/api/src/main/java/com/launchableinc/openai/completion/chat/ChatResponseFormat.java new file mode 100644 index 00000000..19048aac --- /dev/null +++ b/api/src/main/java/com/launchableinc/openai/completion/chat/ChatResponseFormat.java @@ -0,0 +1,31 @@ +package com.launchableinc.openai.completion.chat; + +import com.fasterxml.jackson.annotation.JsonValue; +import lombok.Builder; +import lombok.Data; + +/* + * OpenAI API Document:https://platform.openai.com/docs/api-reference/chat/create#chat-create-response_format + */ +@Data +@Builder +public class ChatResponseFormat { + + private ResponseFormat type; + + public enum ResponseFormat { + TEXT("text"), JSON("json_object"); + + private final String value; + + ResponseFormat(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + } + +} From 2076e07f152dea07f278aec1165b8260f10354dc Mon Sep 17 00:00:00 2001 From: Konboi Date: Thu, 7 Mar 2024 17:04:47 +0900 Subject: [PATCH 22/40] Add example test --- .../openai/service/ChatCompletionTest.java | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/service/src/test/java/com/launchableinc/openai/service/ChatCompletionTest.java b/service/src/test/java/com/launchableinc/openai/service/ChatCompletionTest.java index dc624533..76295293 100644 --- a/service/src/test/java/com/launchableinc/openai/service/ChatCompletionTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/ChatCompletionTest.java @@ -2,9 +2,12 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyDescription; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.launchableinc.openai.completion.chat.*; +import com.launchableinc.openai.completion.chat.ChatResponseFormat.ResponseFormat; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -77,6 +80,37 @@ void createChatCompletion() { assertEquals(5, choices.size()); } + @Test + void createChatCompletion_with_json_mode() { + final List messages = new ArrayList<>(); + final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), + "Generate a random name and age json object. name field is a object that has first and last fields. age is a number."); + messages.add(systemMessage); + + ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest + .builder() + .model("gpt-3.5-turbo-1106") + .messages(messages) + .maxTokens(50) + .logitBias(new HashMap<>()) + .responseFormat(ChatResponseFormat.builder().type(ResponseFormat.JSON).build()) + .build(); + + ChatCompletionChoice choices = service.createChatCompletion(chatCompletionRequest) + .getChoices().get(0); + assertTrue(isValidJson(choices.getMessage().getContent())); + } + + private boolean isValidJson(String jsonString) { + ObjectMapper objectMapper = new ObjectMapper(); + try { + objectMapper.readTree(jsonString); + return true; + } catch (JsonProcessingException e) { + return false; + } + } + @Test void streamChatCompletion() { final List messages = new ArrayList<>(); From f1289afc71a0510011741bf59ad461a939e64d68 Mon Sep 17 00:00:00 2001 From: Konboi Date: Thu, 7 Mar 2024 17:25:46 +0900 Subject: [PATCH 23/40] change next version --- gradle.properties | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/gradle.properties b/gradle.properties index b4fe5434..bbca658f 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,6 +1,5 @@ GROUP=com.launchableinc.openai-java - -VERSION_NAME=0.1.0 +VERSION_NAME=0.2.0 POM_ARTIFACT_ID=openai-java POM_URL=https://launchableinc.com POM_SCM_URL=scm:git:git@github.com:launchableinc/openai-java.git From 625a6daafcfbe2bd99d399a18306ecaa7ebd42fb Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Thu, 7 Mar 2024 08:26:29 +0000 Subject: [PATCH 24/40] [tagpr] prepare for the next release --- .github/release.yml | 4 ++++ .tagpr | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 .github/release.yml create mode 100644 .tagpr diff --git a/.github/release.yml b/.github/release.yml new file mode 100644 index 00000000..b0c5175c --- /dev/null +++ b/.github/release.yml @@ -0,0 +1,4 @@ +changelog: + exclude: + labels: + - tagpr diff --git a/.tagpr b/.tagpr new file mode 100644 index 00000000..4032cce3 --- /dev/null +++ b/.tagpr @@ -0,0 +1,42 @@ +# config file for the tagpr in git config format +# The tagpr generates the initial configuration, which you can rewrite to suit your environment. +# CONFIGURATIONS: +# tagpr.releaseBranch +# Generally, it is "main." It is the branch for releases. The tagpr tracks this branch, +# creates or updates a pull request as a release candidate, or tags when they are merged. +# +# tagpr.versionFile +# Versioning file containing the semantic version needed to be updated at release. +# It will be synchronized with the "git tag". +# Often this is a meta-information file such as gemspec, setup.cfg, package.json, etc. +# Sometimes the source code file, such as version.go or Bar.pm, is used. +# If you do not want to use versioning files but only git tags, specify the "-" string here. +# You can specify multiple version files by comma separated strings. +# +# tagpr.vPrefix +# Flag whether or not v-prefix is added to semver when git tagging. (e.g. v1.2.3 if true) +# This is only a tagging convention, not how it is described in the version file. +# +# tagpr.changelog (Optional) +# Flag whether or not changelog is added or changed during the release. +# +# tagpr.command (Optional) +# Command to change files just before release. +# +# tagpr.template (Optional) +# Pull request template in go template format +# +# tagpr.release (Optional) +# GitHub Release creation behavior after tagging [true, draft, false] +# If this value is not set, the release is to be created. +# +# tagpr.majorLabels (Optional) +# Label of major update targets. Default is [major] +# +# tagpr.minorLabels (Optional) +# Label of minor update targets. Default is [minor] +# +[tagpr] + vPrefix = true + releaseBranch = main + versionFile = - From b01f21f971409bc86f438f207cbc82cbdb5c8282 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Thu, 7 Mar 2024 08:26:29 +0000 Subject: [PATCH 25/40] [tagpr] update CHANGELOG.md --- CHANGELOG.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..ed430fc3 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,11 @@ +# Changelog + +## [v0.2.0](https://github.com/launchableinc/openai-java/compare/v0.1.0...v0.2.0) - 2024-03-07 +- Introduce tag pr by @Konboi in https://github.com/launchableinc/openai-java/pull/4 +- Support json mode by @Konboi in https://github.com/launchableinc/openai-java/pull/6 +- change next version by @Konboi in https://github.com/launchableinc/openai-java/pull/7 + +## [v0.1.0](https://github.com/launchableinc/openai-java/commits/v0.1.0) - 2024-03-06 +- fix indent and version by @Konboi in https://github.com/launchableinc/openai-java/pull/1 +- Fix some points by @Konboi in https://github.com/launchableinc/openai-java/pull/2 +- Fix something by @Konboi in https://github.com/launchableinc/openai-java/pull/3 From 7ab3438f3addf13796bdda5f21e9adb9cb8b7c45 Mon Sep 17 00:00:00 2001 From: Konboi Date: Fri, 8 Mar 2024 13:29:42 +0900 Subject: [PATCH 26/40] set version file --- .tagpr | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.tagpr b/.tagpr index 4032cce3..47bae65f 100644 --- a/.tagpr +++ b/.tagpr @@ -39,4 +39,4 @@ [tagpr] vPrefix = true releaseBranch = main - versionFile = - + versionFile = gradle.properties From 57efdfc26f1f15a14794a6b115ef4bbe3c9559f7 Mon Sep 17 00:00:00 2001 From: Konboi Date: Fri, 8 Mar 2024 13:49:00 +0900 Subject: [PATCH 27/40] set id --- .github/workflows/publish.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index c474f00b..56f43f54 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -15,7 +15,10 @@ jobs: tag: ${{ steps.run-tagpr.outputs.tag }} steps: - uses: actions/checkout@v4 - - uses: Songmu/tagpr@v1 + - name: debug + run: ls -l + - id: run-tagpr + uses: Songmu/tagpr@v1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} From b5a481a5715ec176f215ef5bb94f89a52d199419 Mon Sep 17 00:00:00 2001 From: Konboi Date: Fri, 8 Mar 2024 16:08:49 +0900 Subject: [PATCH 28/40] update lib versions --- gradle/libs.versions.toml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index ecccc347..1a73e596 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,15 +1,15 @@ [versions] -jackson = "2.14.2" +jackson = "2.16.1" retrofit = "2.9.0" [libraries] jacksonDatabind = { module = "com.fasterxml.jackson.core:jackson-databind", version.ref = "jackson" } jacksonAnnotations = { module = "com.fasterxml.jackson.core:jackson-annotations", version.ref = "jackson" } jacksonJsonSchema = { module = "com.kjetland:mbknor-jackson-jsonschema_2.12", version = "1.0.34" } -lombok = { module = "org.projectlombok:lombok", version = "1.18.24" } +lombok = { module = "org.projectlombok:lombok", version = "1.18.30" } junitBom = { module = "org.junit:junit-bom", version = "5.8.2" } retrofit = { module = "com.squareup.retrofit2:retrofit", version.ref = "retrofit" } retrofitJackson = { module = "com.squareup.retrofit2:converter-jackson", version.ref = "retrofit" } retrofitRxJava2 = { module = "com.squareup.retrofit2:adapter-rxjava2", version.ref = "retrofit" } retrofitMock = { module = "com.squareup.retrofit2:retrofit-mock", version.ref = "retrofit" } -jtokkit = { module = "com.knuddels:jtokkit", version = "0.5.1" } +jtokkit = { module = "com.knuddels:jtokkit", version = "0.6.1" } From 3e4d00b74bb33d037103d9e7aba67dd8a54edad4 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Fri, 8 Mar 2024 07:27:27 +0000 Subject: [PATCH 29/40] [tagpr] prepare for the next release --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index bbca658f..9e704633 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,5 +1,5 @@ GROUP=com.launchableinc.openai-java -VERSION_NAME=0.2.0 +VERSION_NAME=0.2.1 POM_ARTIFACT_ID=openai-java POM_URL=https://launchableinc.com POM_SCM_URL=scm:git:git@github.com:launchableinc/openai-java.git From 295b02568d001846af0330089d136fdb020a29fc Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Fri, 8 Mar 2024 07:27:28 +0000 Subject: [PATCH 30/40] [tagpr] update CHANGELOG.md --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index ed430fc3..9d549263 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,8 @@ # Changelog +## [v0.2.1](https://github.com/launchableinc/openai-java/compare/v0.2.0...v0.2.1) - 2024-03-08 +- update lib versions by @Konboi in https://github.com/launchableinc/openai-java/pull/11 + ## [v0.2.0](https://github.com/launchableinc/openai-java/compare/v0.1.0...v0.2.0) - 2024-03-07 - Introduce tag pr by @Konboi in https://github.com/launchableinc/openai-java/pull/4 - Support json mode by @Konboi in https://github.com/launchableinc/openai-java/pull/6 From 744de955e6610d0404844aed97bd8de8fb2f1c9c Mon Sep 17 00:00:00 2001 From: Konboi Date: Fri, 8 Mar 2024 16:32:42 +0900 Subject: [PATCH 31/40] to release v0.3.0 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 9e704633..96c9a9e8 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,5 +1,5 @@ GROUP=com.launchableinc.openai-java -VERSION_NAME=0.2.1 +VERSION_NAME=0.3.0 POM_ARTIFACT_ID=openai-java POM_URL=https://launchableinc.com POM_SCM_URL=scm:git:git@github.com:launchableinc/openai-java.git From ffdbddd60b6042ac5e524142f297ad43b4b02409 Mon Sep 17 00:00:00 2001 From: Konboi Date: Thu, 15 Aug 2024 10:38:45 +0900 Subject: [PATCH 32/40] upgrade api version --- gradle/libs.versions.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 1a73e596..b551bd8a 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -12,4 +12,4 @@ retrofit = { module = "com.squareup.retrofit2:retrofit", version.ref = "retrofit retrofitJackson = { module = "com.squareup.retrofit2:converter-jackson", version.ref = "retrofit" } retrofitRxJava2 = { module = "com.squareup.retrofit2:adapter-rxjava2", version.ref = "retrofit" } retrofitMock = { module = "com.squareup.retrofit2:retrofit-mock", version.ref = "retrofit" } -jtokkit = { module = "com.knuddels:jtokkit", version = "0.6.1" } +jtokkit = { module = "com.knuddels:jtokkit", version = "1.1.0" } From 3a78e049d24c346db33f5f50a2ee60d652943b00 Mon Sep 17 00:00:00 2001 From: Konboi Date: Thu, 15 Aug 2024 10:38:57 +0900 Subject: [PATCH 33/40] fix breaking change --- .../openai/utils/TikTokensUtil.java | 22 ++++++++++++++----- 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/api/src/main/java/com/launchableinc/openai/utils/TikTokensUtil.java b/api/src/main/java/com/launchableinc/openai/utils/TikTokensUtil.java index 3b714b9f..e1ce44fb 100644 --- a/api/src/main/java/com/launchableinc/openai/utils/TikTokensUtil.java +++ b/api/src/main/java/com/launchableinc/openai/utils/TikTokensUtil.java @@ -4,6 +4,7 @@ import com.knuddels.jtokkit.api.Encoding; import com.knuddels.jtokkit.api.EncodingRegistry; import com.knuddels.jtokkit.api.EncodingType; +import com.knuddels.jtokkit.api.IntArrayList; import com.knuddels.jtokkit.api.ModelType; import com.launchableinc.openai.completion.chat.ChatMessage; import lombok.AllArgsConstructor; @@ -46,7 +47,7 @@ public class TikTokensUtil { * @return Encoding array */ public static List encode(Encoding enc, String text) { - return isBlank(text) ? new ArrayList<>() : enc.encode(text); + return isBlank(text) ? new ArrayList<>() : enc.encode(text).boxed(); } /** @@ -69,7 +70,7 @@ public static int tokens(Encoding enc, String text) { * @return Text information corresponding to the encoding array. */ public static String decode(Encoding enc, List encoded) { - return enc.decode(encoded); + return enc.decode(toIntArrayList(encoded)); } /** @@ -94,7 +95,7 @@ public static List encode(EncodingType encodingType, String text) { return new ArrayList<>(); } Encoding enc = getEncoding(encodingType); - List encoded = enc.encode(text); + List encoded = enc.encode(text).boxed(); return encoded; } @@ -119,7 +120,7 @@ public static int tokens(EncodingType encodingType, String text) { */ public static String decode(EncodingType encodingType, List encoded) { Encoding enc = getEncoding(encodingType); - return enc.decode(encoded); + return enc.decode(toIntArrayList(encoded)); } @@ -147,7 +148,7 @@ public static List encode(String modelName, String text) { if (Objects.isNull(enc)) { return new ArrayList<>(); } - List encoded = enc.encode(text); + List encoded = enc.encode(text).boxed(); return encoded; } @@ -209,7 +210,16 @@ public static int tokens(String modelName, List messages) { */ public static String decode(String modelName, List encoded) { Encoding enc = getEncoding(modelName); - return enc.decode(encoded); + return enc.decode(toIntArrayList(encoded)); + } + + private static IntArrayList toIntArrayList(List encoded) { + IntArrayList intArrayList = new IntArrayList(encoded.size()); + for (Integer e : encoded) { + intArrayList.add(e); + } + + return intArrayList; } From fb1f2688ba9d559a9b11652a3a05235845d412fa Mon Sep 17 00:00:00 2001 From: Konboi Date: Thu, 15 Aug 2024 10:58:56 +0900 Subject: [PATCH 34/40] add test case --- .../openai/service/ChatCompletionTest.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/service/src/test/java/com/launchableinc/openai/service/ChatCompletionTest.java b/service/src/test/java/com/launchableinc/openai/service/ChatCompletionTest.java index 76295293..6e4c72e5 100644 --- a/service/src/test/java/com/launchableinc/openai/service/ChatCompletionTest.java +++ b/service/src/test/java/com/launchableinc/openai/service/ChatCompletionTest.java @@ -101,6 +101,27 @@ void createChatCompletion_with_json_mode() { assertTrue(isValidJson(choices.getMessage().getContent())); } + @Test + void createChatCompletion_with_gpt4o() { + final List messages = new ArrayList<>(); + final ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), + "You are a cat and will speak as such."); + messages.add(systemMessage); + + ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest + .builder() + .model("gpt-4o") + .messages(messages) + .n(5) + .maxTokens(50) + .logitBias(new HashMap<>()) + .build(); + + List choices = service.createChatCompletion(chatCompletionRequest) + .getChoices(); + assertEquals(5, choices.size()); + } + private boolean isValidJson(String jsonString) { ObjectMapper objectMapper = new ObjectMapper(); try { From d3cb708f01f76af2eee752ff525043c4e4338a97 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Thu, 15 Aug 2024 03:09:33 +0000 Subject: [PATCH 35/40] [tagpr] prepare for the next release --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 96c9a9e8..69d346e2 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,5 +1,5 @@ GROUP=com.launchableinc.openai-java -VERSION_NAME=0.3.0 +VERSION_NAME=0.3.1 POM_ARTIFACT_ID=openai-java POM_URL=https://launchableinc.com POM_SCM_URL=scm:git:git@github.com:launchableinc/openai-java.git From 579d96845319bc57a49bf52568786311fc2940ad Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Thu, 15 Aug 2024 03:09:34 +0000 Subject: [PATCH 36/40] [tagpr] update CHANGELOG.md --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d549263..96ca7d86 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,7 @@ # Changelog +## [v0.3.1](https://github.com/launchableinc/openai-java/compare/v0.3.0...v0.3.1) - 2024-08-15 + ## [v0.2.1](https://github.com/launchableinc/openai-java/compare/v0.2.0...v0.2.1) - 2024-03-08 - update lib versions by @Konboi in https://github.com/launchableinc/openai-java/pull/11 From 942dac3f6a6612127e9ff0878f6bc589a081d4d3 Mon Sep 17 00:00:00 2001 From: Konboi Date: Thu, 15 Aug 2024 14:23:47 +0900 Subject: [PATCH 37/40] to publish as v0.4.0 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 69d346e2..935f388d 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,5 +1,5 @@ GROUP=com.launchableinc.openai-java -VERSION_NAME=0.3.1 +VERSION_NAME=0.3.2 POM_ARTIFACT_ID=openai-java POM_URL=https://launchableinc.com POM_SCM_URL=scm:git:git@github.com:launchableinc/openai-java.git From 413d68aefa67d2ca236490ea474e5b5e87f803e3 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Thu, 15 Aug 2024 05:28:41 +0000 Subject: [PATCH 38/40] [tagpr] prepare for the next release From 00dbaa3037dcae14d7e3973226a80465d3b01e22 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Thu, 15 Aug 2024 05:28:42 +0000 Subject: [PATCH 39/40] [tagpr] update CHANGELOG.md --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 96ca7d86..f28005ae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,8 @@ # Changelog +## [v0.3.2](https://github.com/launchableinc/openai-java/compare/v0.3.1...v0.3.2) - 2024-08-15 +- to publish as v0.4.0 by @Konboi in https://github.com/launchableinc/openai-java/pull/17 + ## [v0.3.1](https://github.com/launchableinc/openai-java/compare/v0.3.0...v0.3.1) - 2024-08-15 ## [v0.2.1](https://github.com/launchableinc/openai-java/compare/v0.2.0...v0.2.1) - 2024-03-08 From 57d1d4b54d0a1f619eb3fddca117bdbea67c6b1b Mon Sep 17 00:00:00 2001 From: Konboi Date: Thu, 15 Aug 2024 14:36:30 +0900 Subject: [PATCH 40/40] next version is v0.4.0 --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 935f388d..65589071 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,5 +1,5 @@ GROUP=com.launchableinc.openai-java -VERSION_NAME=0.3.2 +VERSION_NAME=0.4.0 POM_ARTIFACT_ID=openai-java POM_URL=https://launchableinc.com POM_SCM_URL=scm:git:git@github.com:launchableinc/openai-java.git