From 78812e89ec2fcbd0fa753013bceb6e183ebd389c Mon Sep 17 00:00:00 2001 From: gouqinggan Date: Thu, 12 Dec 2024 15:41:42 +0800 Subject: [PATCH 1/8] format code Change-Id: Ied466b7bbb1713cb51a40250a08f28427a0f425e --- .github/workflows/ci.yml | 53 ++ .github/workflows/code-check.yml | 38 -- .../com/coze/openapi/api/AudioRoomAPI.java | 7 +- .../com/coze/openapi/api/AudioSpeechAPI.java | 7 +- .../com/coze/openapi/api/AudioVoiceAPI.java | 50 +- .../java/com/coze/openapi/api/BotAPI.java | 33 +- .../java/com/coze/openapi/api/ChatAPI.java | 60 +- .../com/coze/openapi/api/ChatMessageAPI.java | 12 +- .../com/coze/openapi/api/ConversationAPI.java | 37 +- .../openapi/api/ConversationMessageAPI.java | 61 +- .../com/coze/openapi/api/CozeAuthAPI.java | 28 +- .../com/coze/openapi/api/DocumentAPI.java | 27 +- .../java/com/coze/openapi/api/FileAPI.java | 17 +- .../com/coze/openapi/api/WorkflowRunAPI.java | 23 +- .../openapi/api/WorkflowRunHistoryAPI.java | 18 +- .../com/coze/openapi/api/WorkspaceAPI.java | 12 +- .../client/audio/common/AudioFormat.java | 52 +- .../client/audio/common/LanguageCode.java | 52 +- .../client/audio/rooms/CreateRoomReq.java | 20 +- .../client/audio/rooms/CreateRoomResp.java | 39 +- .../client/audio/rooms/model/AudioCodec.java | 43 +- .../audio/rooms/model/RoomAudioConfig.java | 4 +- .../client/audio/rooms/model/RoomConfig.java | 12 +- .../client/audio/speech/CreateSpeechReq.java | 28 +- .../client/audio/speech/CreateSpeechResp.java | 9 +- .../client/audio/voices/CloneVoiceReq.java | 39 +- .../client/audio/voices/CloneVoiceResp.java | 5 +- .../client/audio/voices/ListVoiceReq.java | 17 +- .../client/audio/voices/ListVoiceResp.java | 6 +- .../client/audio/voices/model/Voice.java | 103 ++-- .../openapi/client/auth/DeviceAuthReq.java | 6 +- .../openapi/client/auth/DeviceAuthResp.java | 26 +- .../client/auth/GetAccessTokenReq.java | 43 +- .../client/auth/GetPKCEAuthURLResp.java | 5 +- .../coze/openapi/client/auth/GrantType.java | 20 +- .../coze/openapi/client/auth/OAuthToken.java | 19 +- .../coze/openapi/client/auth/scope/Scope.java | 46 +- .../auth/scope/ScopeAccountPermission.java | 5 +- .../auth/scope/ScopeAttributeConstraint.java | 3 +- ...teConstraintConnectorBotChatAttribute.java | 5 +- .../openapi/client/bots/CreateBotReq.java | 31 +- .../openapi/client/bots/CreateBotResp.java | 5 +- .../coze/openapi/client/bots/ListBotReq.java | 14 +- .../coze/openapi/client/bots/ListBotResp.java | 20 +- .../openapi/client/bots/PublishBotReq.java | 12 +- .../openapi/client/bots/PublishBotResp.java | 16 +- .../openapi/client/bots/RetrieveBotReq.java | 12 +- .../openapi/client/bots/RetrieveBotResp.java | 5 +- .../openapi/client/bots/UpdateBotReq.java | 37 +- .../openapi/client/bots/UpdateBotResp.java | 5 +- .../coze/openapi/client/bots/model/Bot.java | 55 +- .../client/bots/model/BotKnowledge.java | 15 +- .../openapi/client/bots/model/BotMode.java | 41 +- .../client/bots/model/BotModelInfo.java | 14 +- .../client/bots/model/BotOnboardingInfo.java | 17 +- .../client/bots/model/BotPluginAPIInfo.java | 18 +- .../client/bots/model/BotPluginInfo.java | 27 +- .../client/bots/model/BotPromptInfo.java | 8 +- .../openapi/client/bots/model/SimpleBot.java | 24 +- .../openapi/client/chat/CancelChatReq.java | 46 +- .../openapi/client/chat/CancelChatResp.java | 6 +- .../openapi/client/chat/CreateChatReq.java | 110 ++-- .../openapi/client/chat/CreateChatResp.java | 5 +- .../openapi/client/chat/RetrieveChatReq.java | 46 +- .../openapi/client/chat/RetrieveChatResp.java | 5 +- .../client/chat/SubmitToolOutputsReq.java | 83 +-- .../client/chat/SubmitToolOutputsResp.java | 5 +- .../client/chat/message/ListMessageReq.java | 33 +- .../client/chat/message/ListMessageResp.java | 9 +- .../coze/openapi/client/chat/model/Chat.java | 153 +++-- .../openapi/client/chat/model/ChatError.java | 20 +- .../openapi/client/chat/model/ChatEvent.java | 96 ++-- .../client/chat/model/ChatEventType.java | 149 +++-- .../openapi/client/chat/model/ChatPoll.java | 17 +- .../client/chat/model/ChatRequiredAction.java | 24 +- .../chat/model/ChatRequiredActionType.java | 35 +- .../openapi/client/chat/model/ChatStatus.java | 89 ++- .../chat/model/ChatSubmitToolOutputs.java | 16 +- .../client/chat/model/ChatToolCall.java | 34 +- .../chat/model/ChatToolCallFunction.java | 20 +- .../client/chat/model/ChatToolCallType.java | 34 +- .../openapi/client/chat/model/ChatUsage.java | 32 +- .../openapi/client/chat/model/ToolOutput.java | 31 +- .../coze/openapi/client/common/BaseReq.java | 10 +- .../coze/openapi/client/common/BaseResp.java | 3 +- .../openapi/client/common/BaseResponse.java | 34 +- .../openapi/client/common/FileResponse.java | 39 +- .../com/coze/openapi/client/common/Sort.java | 23 +- .../client/common/pagination/PageFetcher.java | 6 +- .../pagination/PageNumBasedPaginator.java | 87 ++- .../client/common/pagination/PageRequest.java | 23 +- .../client/common/pagination/PageResp.java | 14 +- .../common/pagination/PageResponse.java | 27 +- .../pagination/TokenBasedPaginator.java | 84 ++- .../connversations/ClearConversationReq.java | 17 +- .../connversations/ClearConversationResp.java | 5 +- .../connversations/CreateConversationReq.java | 40 +- .../CreateConversationResp.java | 5 +- .../connversations/ListConversationReq.java | 37 +- .../connversations/ListConversationResp.java | 12 +- .../RetrieveConversationReq.java | 26 +- .../RetrieveConversationResp.java | 6 +- .../message/CreateMessageReq.java | 75 ++- .../message/CreateMessageResp.java | 3 +- .../message/DeleteMessageReq.java | 39 +- .../message/DeleteMessageResp.java | 3 +- .../message/ListMessageReq.java | 84 ++- .../message/ListMessageResp.java | 16 +- .../message/RetrieveMessageReq.java | 20 +- .../message/RetrieveMessageResp.java | 8 +- .../message/UpdateMessageReq.java | 85 +-- .../message/UpdateMessageResp.java | 5 +- .../connversations/message/model/Message.java | 218 ++++--- .../message/model/MessageContentType.java | 70 +-- .../message/model/MessageObjectString.java | 165 +++--- .../model/MessageObjectStringType.java | 49 +- .../message/model/MessageRole.java | 45 +- .../message/model/MessageType.java | 67 +-- .../connversations/model/Conversation.java | 25 +- .../dataset/document/CreateDocumentReq.java | 53 +- .../dataset/document/CreateDocumentResp.java | 15 +- .../dataset/document/DeleteDocumentReq.java | 15 +- .../dataset/document/DeleteDocumentResp.java | 6 +- .../dataset/document/ListDocumentReq.java | 40 +- .../dataset/document/ListDocumentResp.java | 13 +- .../dataset/document/UpdateDocumentReq.java | 33 +- .../dataset/document/UpdateDocumentResp.java | 4 +- .../dataset/document/model/Document.java | 213 +++---- .../dataset/document/model/DocumentBase.java | 75 +-- .../document/model/DocumentChunkStrategy.java | 147 +++-- .../document/model/DocumentFormatType.java | 64 +-- .../document/model/DocumentSourceInfo.java | 82 ++- .../document/model/DocumentSourceType.java | 49 +- .../document/model/DocumentStatus.java | 64 +-- .../document/model/DocumentUpdateRule.java | 68 ++- .../document/model/DocumentUpdateType.java | 49 +- .../client/exception/AuthErrorCode.java | 125 ++-- .../client/exception/CozeApiExcetion.java | 19 +- .../client/exception/CozeAuthException.java | 45 +- .../openapi/client/exception/CozeError.java | 29 +- .../openapi/client/files/RetrieveFileReq.java | 9 +- .../client/files/RetrieveFileResp.java | 5 +- .../openapi/client/files/UploadFileReq.java | 57 +- .../openapi/client/files/UploadFileResp.java | 5 +- .../openapi/client/files/model/FileInfo.java | 38 +- .../client/workflows/run/ResumeRunReq.java | 62 +- .../workflows/run/RetrieveRunHistoryReq.java | 31 +- .../workflows/run/RetrieveRunHistoryResp.java | 4 +- .../client/workflows/run/RunWorkflowReq.java | 63 +- .../client/workflows/run/RunWorkflowResp.java | 42 +- .../workflows/run/model/WorkflowEvent.java | 130 ++--- .../run/model/WorkflowEventError.java | 30 +- .../run/model/WorkflowEventInterrupt.java | 26 +- .../run/model/WorkflowEventInterruptData.java | 18 +- .../run/model/WorkflowEventMessage.java | 67 +-- .../run/model/WorkflowEventType.java | 88 ++- .../run/model/WorkflowExecuteStatus.java | 66 +-- .../run/model/WorkflowRunHistory.java | 144 +++-- .../workflows/run/model/WorkflowRunMode.java | 57 +- .../run/model/WorkflowRunResult.java | 34 +- .../client/workspace/ListWorkspaceReq.java | 22 +- .../client/workspace/ListWorkspaceResp.java | 12 +- .../client/workspace/model/Workspace.java | 32 +- .../workspace/model/WorkspaceRoleType.java | 39 +- .../client/workspace/model/WorkspaceType.java | 33 +- .../com/coze/openapi/service/auth/Auth.java | 71 +-- .../openapi/service/auth/AuthLogFactory.java | 23 +- .../service/auth/DeviceOAuthClient.java | 137 ++--- .../coze/openapi/service/auth/JWTOAuth.java | 45 +- .../openapi/service/auth/JWTOAuthClient.java | 268 +++++---- .../openapi/service/auth/OAuthClient.java | 538 +++++++++--------- .../openapi/service/auth/PKCEOAuthClient.java | 189 +++--- .../coze/openapi/service/auth/TokenAuth.java | 18 +- .../openapi/service/auth/WebOAuthClient.java | 59 +- .../coze/openapi/service/config/Consts.java | 6 +- .../service/APIResponseCallAdapter.java | 192 ++++--- .../APIResponseCallAdapterFactory.java | 41 +- .../service/AuthenticationInterceptor.java | 39 +- .../coze/openapi/service/service/CozeAPI.java | 368 ++++++------ .../service/service/TimeoutInterceptor.java | 61 +- .../service/service/audio/AudioService.java | 36 +- .../service/service/audio/RoomService.java | 21 +- .../service/service/audio/SpeechService.java | 36 +- .../service/service/audio/VoiceService.java | 142 ++--- .../service/service/bots/BotService.java | 145 +++-- .../service/chat/ChatMessageService.java | 22 +- .../service/service/chat/ChatService.java | 306 +++++----- .../service/service/chat/EventCallback.java | 34 +- .../service/common/AbstractEventCallback.java | 124 ++-- .../service/common/CozeLoggerFactory.java | 21 +- .../conversation/ConversationService.java | 175 +++--- .../service/conversation/MessageService.java | 220 ++++--- .../service/dataset/DatasetService.java | 16 +- .../service/dataset/DocumentService.java | 151 ++--- .../service/service/file/FileService.java | 90 ++- .../service/workflow/EventCallback.java | 51 +- .../workflow/WorkflowRunHistoryService.java | 34 +- .../service/workflow/WorkflowRunService.java | 86 +-- .../service/workflow/WorkflowService.java | 15 +- .../service/workspace/WorkspaceService.java | 84 ++- .../service/utils/UserAgentInterceptor.java | 117 ++-- .../com/coze/openapi/service/utils/Utils.java | 135 +++-- .../service/audio/RoomServiceTest.java | 88 ++- .../service/audio/SpeechServiceTest.java | 126 ++-- .../service/audio/VoiceServiceTest.java | 242 ++++---- .../service/service/bots/BotServiceTest.java | 379 ++++++------ .../service/chat/ChatMessageServiceTest.java | 124 ++-- .../service/service/chat/ChatServiceTest.java | 365 ++++++------ .../common/AbstractEventCallbackTest.java | 285 +++++----- .../conversation/ConversationServiceTest.java | 327 ++++++----- .../conversation/MessageServiceTest.java | 338 ++++++----- .../service/dataset/DocumentServiceTest.java | 289 +++++----- .../service/service/file/FileServiceTest.java | 290 +++++----- .../service/workflow/EventCallbackTest.java | 75 +-- .../workflow/WorkFlowRunServiceTest.java | 255 ++++----- .../WorkflowRunHistoryServiceTest.java | 109 ++-- .../workspace/WorkspaceServiceTest.java | 241 ++++---- .../java/com/coze/openapi/utils/Utils.java | 26 +- build.gradle | 3 +- .../audio/room/AudioRoomsCreateExample.java | 41 +- .../audio/speech/SpeechCreateExample.java | 52 +- .../audio/voice/VoiceCloneExample.java | 45 +- .../example/audio/voice/VoiceListExample.java | 40 +- .../java/example/auth/DeviceOAuthExample.java | 163 +++--- .../example/auth/HandlerExceptionExample.java | 114 ++-- .../java/example/auth/JWTOAuthExample.java | 117 ++-- .../java/example/auth/PKCEOAuthExample.java | 102 ++-- .../java/example/auth/PkceOauthExample.java | 80 --- .../java/example/auth/TokenAuthExample.java | 46 +- .../java/example/auth/WebOAuthExample.java | 111 ++-- .../java/example/bot/BotPublishExample.java | 148 ++--- .../java/example/bot/BotRetrieveExample.java | 88 +-- .../main/java/example/chat/ChatExample.java | 148 ++--- .../example/chat/ChatWithImageExample.java | 90 +-- .../java/example/chat/StreamChatExample.java | 91 +-- .../example/chat/SubmitToolOutputExample.java | 164 +++--- .../ConversationCreateExample.java | 92 +-- .../ConversationsListExample.java | 60 +- .../message/MessageCrudExample.java | 114 ++-- .../message/MessageListExample.java | 76 +-- .../document/DocumentCrudExample.java | 102 ++-- .../document/DocumentListExample.java | 67 ++- .../main/java/example/file/FileExample.java | 50 +- .../java/example/service/GetLogExample.java | 43 +- .../service/HandlerExceptionExample.java | 52 +- .../example/service/InitClientExample.java | 118 ++-- .../service/SetRequestTimeoutExample.java | 65 ++- .../workflow/AsyncRunWorkflowExample.java | 112 ++-- .../example/workflow/RunWorkflowExample.java | 59 +- .../workflow/StreamWorkflowExample.java | 102 ++-- .../workspace/WorkspaceListExample.java | 48 +- 251 files changed, 8362 insertions(+), 8477 deletions(-) create mode 100644 .github/workflows/ci.yml delete mode 100644 .github/workflows/code-check.yml delete mode 100644 example/src/main/java/example/auth/PkceOauthExample.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 00000000..87a17635 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,53 @@ +name: CI + +on: + push: + branches: [ main, master ] + pull_request: + branches: [ main, master ] + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + + - name: Set up JDK + uses: actions/setup-java@v3 + with: + java-version: '8' + distribution: 'temurin' + cache: gradle + + - name: Grant execute permission for gradlew + run: chmod +x gradlew + + - name: Code style check + run: | + ./gradlew spotlessCheck + ./gradlew checkstyleMain + + - name: Build and Test + run: ./gradlew build test + + - name: Generate JaCoCo Report + run: ./gradlew jacocoTestReport + + - name: Upload coverage to Codecov + uses: codecov/codecov-action@v5 + with: + token: ${{ secrets.CODECOV_TOKEN }} + files: ./build/reports/jacoco/test/jacocoTestReport.xml + flags: unittests + fail_ci_if_error: true + + - name: Cache Gradle packages + uses: actions/cache@v3 + with: + path: | + ~/.gradle/caches + ~/.gradle/wrapper + key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} + restore-keys: | + ${{ runner.os }}-gradle- \ No newline at end of file diff --git a/.github/workflows/code-check.yml b/.github/workflows/code-check.yml deleted file mode 100644 index e91e0e50..00000000 --- a/.github/workflows/code-check.yml +++ /dev/null @@ -1,38 +0,0 @@ -name: Code Check - -on: - pull_request: - branches: [ main, master ] - push: - branches: [ main, master ] - -jobs: - check: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - - name: Set up JDK - uses: actions/setup-java@v3 - with: - java-version: '17' - distribution: 'temurin' - cache: 'gradle' - - - name: Grant execute permission for gradlew - run: chmod +x gradlew - - - name: Code style check - run: | - ./gradlew spotlessCheck - ./gradlew checkstyleMain - - - name: Run tests with coverage - run: ./gradlew test - - - name: Upload coverage to Codecov - uses: codecov/codecov-action@v3 - with: - files: ./build/reports/jacoco/test/jacocoTestReport.xml - flags: unittests - fail_ci_if_error: true \ No newline at end of file diff --git a/api/src/main/java/com/coze/openapi/api/AudioRoomAPI.java b/api/src/main/java/com/coze/openapi/api/AudioRoomAPI.java index ecbe9a0c..289f3a15 100644 --- a/api/src/main/java/com/coze/openapi/api/AudioRoomAPI.java +++ b/api/src/main/java/com/coze/openapi/api/AudioRoomAPI.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.api; import com.coze.openapi.client.audio.rooms.CreateRoomReq; @@ -5,14 +6,12 @@ import com.coze.openapi.client.common.BaseReq; import com.coze.openapi.client.common.BaseResponse; -import io.reactivex.Single; import retrofit2.Call; -import retrofit2.Response; import retrofit2.http.Body; import retrofit2.http.POST; import retrofit2.http.Tag; public interface AudioRoomAPI { - @POST("/v1/audio/rooms") - Call> create(@Body CreateRoomReq request, @Tag BaseReq baseReq); + @POST("/v1/audio/rooms") + Call> create(@Body CreateRoomReq request, @Tag BaseReq baseReq); } diff --git a/api/src/main/java/com/coze/openapi/api/AudioSpeechAPI.java b/api/src/main/java/com/coze/openapi/api/AudioSpeechAPI.java index 186e0a1e..4e69dc73 100644 --- a/api/src/main/java/com/coze/openapi/api/AudioSpeechAPI.java +++ b/api/src/main/java/com/coze/openapi/api/AudioSpeechAPI.java @@ -1,17 +1,16 @@ +/* (C)2024 */ package com.coze.openapi.api; import com.coze.openapi.client.audio.speech.CreateSpeechReq; import com.coze.openapi.client.common.BaseReq; -import io.reactivex.Single; import okhttp3.ResponseBody; import retrofit2.Call; -import retrofit2.Response; import retrofit2.http.Body; import retrofit2.http.POST; import retrofit2.http.Tag; public interface AudioSpeechAPI { - @POST("/v1/audio/speech") - Call create(@Body CreateSpeechReq request, @Tag BaseReq baseReq); + @POST("/v1/audio/speech") + Call create(@Body CreateSpeechReq request, @Tag BaseReq baseReq); } diff --git a/api/src/main/java/com/coze/openapi/api/AudioVoiceAPI.java b/api/src/main/java/com/coze/openapi/api/AudioVoiceAPI.java index e7fc1b68..585aa022 100644 --- a/api/src/main/java/com/coze/openapi/api/AudioVoiceAPI.java +++ b/api/src/main/java/com/coze/openapi/api/AudioVoiceAPI.java @@ -1,5 +1,11 @@ +/* (C)2024 */ package com.coze.openapi.api; +import com.coze.openapi.client.audio.voices.CloneVoiceResp; +import com.coze.openapi.client.audio.voices.ListVoiceResp; +import com.coze.openapi.client.common.BaseReq; +import com.coze.openapi.client.common.BaseResponse; + import okhttp3.MultipartBody; import okhttp3.RequestBody; import retrofit2.Call; @@ -10,33 +16,23 @@ import retrofit2.http.Query; import retrofit2.http.Tag; -import com.coze.openapi.client.audio.voices.CloneVoiceResp; -import com.coze.openapi.client.audio.voices.ListVoiceResp; -import com.coze.openapi.client.common.BaseReq; -import com.coze.openapi.client.common.BaseResponse; - -import io.reactivex.Single; -import retrofit2.Response; public interface AudioVoiceAPI { - @Multipart - @POST("/v1/audio/voices/clone") - Call> clone( - @Part MultipartBody.Part file, - @Part("voice_name") RequestBody voiceName, - @Part("audio_format") RequestBody audioFormat, - @Part("language") RequestBody language, - @Part("voice_id") RequestBody voiceID, - @Part("preview_text") RequestBody previewText, - @Part("text") RequestBody text, - @Tag BaseReq baseReq - ); - - @GET("/v1/audio/voices") - Call> list( - @Query("filter_system_voice") Boolean filterSystemVoice, - @Query("page_num") Integer pageNum, - @Query("page_size") Integer pageSize, - @Tag BaseReq baseReq - ); + @Multipart + @POST("/v1/audio/voices/clone") + Call> clone( + @Part MultipartBody.Part file, + @Part("voice_name") RequestBody voiceName, + @Part("audio_format") RequestBody audioFormat, + @Part("language") RequestBody language, + @Part("voice_id") RequestBody voiceID, + @Part("preview_text") RequestBody previewText, + @Part("text") RequestBody text, + @Tag BaseReq baseReq); + @GET("/v1/audio/voices") + Call> list( + @Query("filter_system_voice") Boolean filterSystemVoice, + @Query("page_num") Integer pageNum, + @Query("page_size") Integer pageSize, + @Tag BaseReq baseReq); } diff --git a/api/src/main/java/com/coze/openapi/api/BotAPI.java b/api/src/main/java/com/coze/openapi/api/BotAPI.java index 17385c09..c48f31a0 100644 --- a/api/src/main/java/com/coze/openapi/api/BotAPI.java +++ b/api/src/main/java/com/coze/openapi/api/BotAPI.java @@ -1,35 +1,40 @@ +/* (C)2024 */ package com.coze.openapi.api; import com.coze.openapi.client.bots.CreateBotReq; import com.coze.openapi.client.bots.CreateBotResp; import com.coze.openapi.client.bots.ListBotResp; -import com.coze.openapi.client.bots.UpdateBotReq; import com.coze.openapi.client.bots.PublishBotReq; import com.coze.openapi.client.bots.PublishBotResp; +import com.coze.openapi.client.bots.UpdateBotReq; import com.coze.openapi.client.bots.model.Bot; +import com.coze.openapi.client.common.BaseReq; import com.coze.openapi.client.common.BaseResponse; import retrofit2.Call; +import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.Query; -import retrofit2.http.Body; import retrofit2.http.Tag; -import com.coze.openapi.client.common.BaseReq; public interface BotAPI { - @GET("/v1/space/published_bots_list") - Call> list(@Query("space_id") String spaceID, @Query("page_index") Integer page, @Query("page_size") Integer pageSize, @Tag BaseReq baseReq); + @GET("/v1/space/published_bots_list") + Call> list( + @Query("space_id") String spaceID, + @Query("page_index") Integer page, + @Query("page_size") Integer pageSize, + @Tag BaseReq baseReq); - @GET("/v1/bot/get_online_info") - Call> retrieve(@Query("bot_id") String botID, @Tag BaseReq baseReq); + @GET("/v1/bot/get_online_info") + Call> retrieve(@Query("bot_id") String botID, @Tag BaseReq baseReq); - @POST("/v1/bot/create") - Call> create(@Body CreateBotReq req, @Tag BaseReq baseReq); + @POST("/v1/bot/create") + Call> create(@Body CreateBotReq req, @Tag BaseReq baseReq); - @POST("/v1/bot/update") - Call> update(@Body UpdateBotReq req, @Tag BaseReq baseReq); + @POST("/v1/bot/update") + Call> update(@Body UpdateBotReq req, @Tag BaseReq baseReq); - @POST("/v1/bot/publish") - Call> publish(@Body PublishBotReq req, @Tag BaseReq baseReq); -} + @POST("/v1/bot/publish") + Call> publish(@Body PublishBotReq req, @Tag BaseReq baseReq); +} diff --git a/api/src/main/java/com/coze/openapi/api/ChatAPI.java b/api/src/main/java/com/coze/openapi/api/ChatAPI.java index 4d2f1984..dbcde203 100644 --- a/api/src/main/java/com/coze/openapi/api/ChatAPI.java +++ b/api/src/main/java/com/coze/openapi/api/ChatAPI.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.api; import com.coze.openapi.client.chat.CancelChatReq; @@ -7,10 +8,8 @@ import com.coze.openapi.client.common.BaseReq; import com.coze.openapi.client.common.BaseResponse; -import io.reactivex.Single; import okhttp3.ResponseBody; import retrofit2.Call; -import retrofit2.Response; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.POST; @@ -20,25 +19,40 @@ public interface ChatAPI { - @POST("/v3/chat") - Call> chat(@Query("conversation_id") String conversationID, @Body CreateChatReq req, @Tag BaseReq baseReq); - - @POST("/v3/chat") - @Streaming - Call stream(@Query("conversation_id") String conversationID, @Body CreateChatReq req, @Tag BaseReq baseReq); - - @GET("/v3/chat/retrieve") - Call> retrieve(@Query("conversation_id") String conversationID, @Query("chat_id") String chatID, @Tag BaseReq baseReq); - - @POST("/v3/chat/cancel") - Call> cancel(@Body CancelChatReq req, @Tag BaseReq baseReq); - - @POST("/v3/chat/submit_tool_outputs") - @Streaming - Call streamSubmitToolOutputs(@Query("conversation_id") String conversationID, @Query("chat_id") String chatID, @Body SubmitToolOutputsReq req, @Tag BaseReq baseReq); - - @POST("/v3/chat/submit_tool_outputs") - Call> submitToolOutputs(@Query("conversation_id") String conversationID, @Query("chat_id") String chatID, @Body SubmitToolOutputsReq req, @Tag BaseReq baseReq); - - + @POST("/v3/chat") + Call> chat( + @Query("conversation_id") String conversationID, + @Body CreateChatReq req, + @Tag BaseReq baseReq); + + @POST("/v3/chat") + @Streaming + Call stream( + @Query("conversation_id") String conversationID, + @Body CreateChatReq req, + @Tag BaseReq baseReq); + + @GET("/v3/chat/retrieve") + Call> retrieve( + @Query("conversation_id") String conversationID, + @Query("chat_id") String chatID, + @Tag BaseReq baseReq); + + @POST("/v3/chat/cancel") + Call> cancel(@Body CancelChatReq req, @Tag BaseReq baseReq); + + @POST("/v3/chat/submit_tool_outputs") + @Streaming + Call streamSubmitToolOutputs( + @Query("conversation_id") String conversationID, + @Query("chat_id") String chatID, + @Body SubmitToolOutputsReq req, + @Tag BaseReq baseReq); + + @POST("/v3/chat/submit_tool_outputs") + Call> submitToolOutputs( + @Query("conversation_id") String conversationID, + @Query("chat_id") String chatID, + @Body SubmitToolOutputsReq req, + @Tag BaseReq baseReq); } diff --git a/api/src/main/java/com/coze/openapi/api/ChatMessageAPI.java b/api/src/main/java/com/coze/openapi/api/ChatMessageAPI.java index 9f55e5bc..91700ec6 100644 --- a/api/src/main/java/com/coze/openapi/api/ChatMessageAPI.java +++ b/api/src/main/java/com/coze/openapi/api/ChatMessageAPI.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.api; import java.util.List; @@ -6,15 +7,16 @@ import com.coze.openapi.client.common.BaseResponse; import com.coze.openapi.client.connversations.message.model.Message; -import io.reactivex.Single; import retrofit2.Call; -import retrofit2.Response; import retrofit2.http.GET; import retrofit2.http.Query; import retrofit2.http.Tag; public interface ChatMessageAPI { - @GET("/v3/chat/message/list") - Call>> list(@Query("conversation_id") String conversationID, @Query("chat_id") String chatID, @Tag BaseReq baseReq); -} + @GET("/v3/chat/message/list") + Call>> list( + @Query("conversation_id") String conversationID, + @Query("chat_id") String chatID, + @Tag BaseReq baseReq); +} diff --git a/api/src/main/java/com/coze/openapi/api/ConversationAPI.java b/api/src/main/java/com/coze/openapi/api/ConversationAPI.java index e7f8ae98..12f32a65 100644 --- a/api/src/main/java/com/coze/openapi/api/ConversationAPI.java +++ b/api/src/main/java/com/coze/openapi/api/ConversationAPI.java @@ -1,29 +1,36 @@ +/* (C)2024 */ package com.coze.openapi.api; +import com.coze.openapi.client.common.BaseReq; import com.coze.openapi.client.common.BaseResponse; import com.coze.openapi.client.connversations.ClearConversationResp; import com.coze.openapi.client.connversations.CreateConversationReq; import com.coze.openapi.client.connversations.ListConversationResp; - import com.coze.openapi.client.connversations.model.Conversation; + import retrofit2.Call; import retrofit2.http.*; -import com.coze.openapi.client.common.BaseReq; public interface ConversationAPI { - @Headers({"Content-Type: application/json"}) - @POST("/v1/conversation/create") - Call> create(@Body CreateConversationReq req, @Tag BaseReq baseReq); - - @Headers({"Content-Type: application/json"}) - @GET("/v1/conversation/retrieve") - Call> retrieve(@Query("conversation_id")String id, @Tag BaseReq baseReq); + @Headers({"Content-Type: application/json"}) + @POST("/v1/conversation/create") + Call> create(@Body CreateConversationReq req, @Tag BaseReq baseReq); + + @Headers({"Content-Type: application/json"}) + @GET("/v1/conversation/retrieve") + Call> retrieve( + @Query("conversation_id") String id, @Tag BaseReq baseReq); - @Headers({"Content-Type: application/json"}) - @GET("/v1/conversations") - Call> list(@Query("bot_id") String botID, @Query("page_num") Integer pageNum, @Query("page_size") Integer pageSize, @Tag BaseReq baseReq); + @Headers({"Content-Type: application/json"}) + @GET("/v1/conversations") + Call> list( + @Query("bot_id") String botID, + @Query("page_num") Integer pageNum, + @Query("page_size") Integer pageSize, + @Tag BaseReq baseReq); - @Headers({"Content-Type: application/json"}) - @POST("/v1/conversations/{conversation_id}/clear") - Call> clear(@Path("conversation_id") String conversationID, @Tag BaseReq baseReq); + @Headers({"Content-Type: application/json"}) + @POST("/v1/conversations/{conversation_id}/clear") + Call> clear( + @Path("conversation_id") String conversationID, @Tag BaseReq baseReq); } diff --git a/api/src/main/java/com/coze/openapi/api/ConversationMessageAPI.java b/api/src/main/java/com/coze/openapi/api/ConversationMessageAPI.java index 181ee801..ee577f50 100644 --- a/api/src/main/java/com/coze/openapi/api/ConversationMessageAPI.java +++ b/api/src/main/java/com/coze/openapi/api/ConversationMessageAPI.java @@ -1,6 +1,7 @@ +/* (C)2024 */ package com.coze.openapi.api; - +import com.coze.openapi.client.common.BaseReq; import com.coze.openapi.client.common.BaseResponse; import com.coze.openapi.client.connversations.message.CreateMessageReq; import com.coze.openapi.client.connversations.message.ListMessageReq; @@ -8,11 +9,8 @@ import com.coze.openapi.client.connversations.message.UpdateMessageReq; import com.coze.openapi.client.connversations.message.UpdateMessageResp; import com.coze.openapi.client.connversations.message.model.Message; -import com.coze.openapi.client.common.BaseReq; -import io.reactivex.Single; import retrofit2.Call; -import retrofit2.Response; import retrofit2.http.Body; import retrofit2.http.Headers; import retrofit2.http.POST; @@ -20,24 +18,39 @@ import retrofit2.http.Tag; public interface ConversationMessageAPI { - @Headers({"Content-Type: application/json"}) - @POST("/v1/conversation/message/create") - Call> create(@Query("conversation_id")String conversationID, @Body CreateMessageReq req, @Tag BaseReq baseReq); - - - @Headers({"Content-Type: application/json"}) - @POST("/v1/conversation/message/list") - Call list(@Query("conversation_id") String conversationID, @Body ListMessageReq req, @Tag BaseReq baseReq); - - @Headers({"Content-Type: application/json"}) - @POST("/v1/conversation/message/retrieve") - Call> retrieve(@Query("conversation_id")String conversationID, @Query("message_id")String messageID, @Tag BaseReq baseReq); - - @Headers({"Content-Type: application/json"}) - @POST("/v1/conversation/message/modify") - Call update(@Query("conversation_id")String conversationID, @Query("message_id")String messageID, @Body UpdateMessageReq req, @Tag BaseReq baseReq); - - @Headers({"Content-Type: application/json"}) - @POST("/v1/conversation/message/delete") - Call> delete(@Query("conversation_id")String conversationID, @Query("message_id")String messageID, @Tag BaseReq baseReq); + @Headers({"Content-Type: application/json"}) + @POST("/v1/conversation/message/create") + Call> create( + @Query("conversation_id") String conversationID, + @Body CreateMessageReq req, + @Tag BaseReq baseReq); + + @Headers({"Content-Type: application/json"}) + @POST("/v1/conversation/message/list") + Call list( + @Query("conversation_id") String conversationID, + @Body ListMessageReq req, + @Tag BaseReq baseReq); + + @Headers({"Content-Type: application/json"}) + @POST("/v1/conversation/message/retrieve") + Call> retrieve( + @Query("conversation_id") String conversationID, + @Query("message_id") String messageID, + @Tag BaseReq baseReq); + + @Headers({"Content-Type: application/json"}) + @POST("/v1/conversation/message/modify") + Call update( + @Query("conversation_id") String conversationID, + @Query("message_id") String messageID, + @Body UpdateMessageReq req, + @Tag BaseReq baseReq); + + @Headers({"Content-Type: application/json"}) + @POST("/v1/conversation/message/delete") + Call> delete( + @Query("conversation_id") String conversationID, + @Query("message_id") String messageID, + @Tag BaseReq baseReq); } diff --git a/api/src/main/java/com/coze/openapi/api/CozeAuthAPI.java b/api/src/main/java/com/coze/openapi/api/CozeAuthAPI.java index ffc93fd7..f963b414 100644 --- a/api/src/main/java/com/coze/openapi/api/CozeAuthAPI.java +++ b/api/src/main/java/com/coze/openapi/api/CozeAuthAPI.java @@ -1,22 +1,26 @@ +/* (C)2024 */ package com.coze.openapi.api; +import java.util.Map; + +import com.coze.openapi.client.auth.*; + import io.reactivex.Single; import retrofit2.Response; import retrofit2.http.*; -import com.coze.openapi.client.auth.*; - -import java.util.Map; public interface CozeAuthAPI { - @Headers({"Content-Type: application/json"}) - @POST("/api/permission/oauth2/token") - Single> retrieve(@HeaderMap Map headers, @Body GetAccessTokenReq req); + @Headers({"Content-Type: application/json"}) + @POST("/api/permission/oauth2/token") + Single> retrieve( + @HeaderMap Map headers, @Body GetAccessTokenReq req); - @Headers({"Content-Type: application/json"}) - @POST("/api/permission/oauth2/device/code") - Single> device(@Body DeviceAuthReq req); + @Headers({"Content-Type: application/json"}) + @POST("/api/permission/oauth2/device/code") + Single> device(@Body DeviceAuthReq req); - @Headers({"Content-Type: application/json"}) - @POST("/api/permission/oauth2/workspace_id/{workspace_id}/device/code") - Single> device(@Path("workspace_id") String workspaceID, @Body DeviceAuthReq req); + @Headers({"Content-Type: application/json"}) + @POST("/api/permission/oauth2/workspace_id/{workspace_id}/device/code") + Single> device( + @Path("workspace_id") String workspaceID, @Body DeviceAuthReq req); } diff --git a/api/src/main/java/com/coze/openapi/api/DocumentAPI.java b/api/src/main/java/com/coze/openapi/api/DocumentAPI.java index 7d63cb0f..e9218cb3 100644 --- a/api/src/main/java/com/coze/openapi/api/DocumentAPI.java +++ b/api/src/main/java/com/coze/openapi/api/DocumentAPI.java @@ -1,5 +1,7 @@ +/* (C)2024 */ package com.coze.openapi.api; +import com.coze.openapi.client.common.BaseReq; import com.coze.openapi.client.common.BaseResponse; import com.coze.openapi.client.dataset.document.CreateDocumentReq; import com.coze.openapi.client.dataset.document.CreateDocumentResp; @@ -7,7 +9,6 @@ import com.coze.openapi.client.dataset.document.ListDocumentReq; import com.coze.openapi.client.dataset.document.ListDocumentResp; import com.coze.openapi.client.dataset.document.UpdateDocumentReq; -import com.coze.openapi.client.common.BaseReq; import retrofit2.Call; import retrofit2.http.Body; @@ -17,19 +18,19 @@ public interface DocumentAPI { - @POST("/open_api/knowledge/document/create") - @Headers({"Content-Type: application/json","Agw-Js-Conv: str"}) - Call create(@Body CreateDocumentReq req, @Tag BaseReq baseReq); + @POST("/open_api/knowledge/document/create") + @Headers({"Content-Type: application/json", "Agw-Js-Conv: str"}) + Call create(@Body CreateDocumentReq req, @Tag BaseReq baseReq); - @POST("/open_api/knowledge/document/update") - @Headers({"Content-Type: application/json","Agw-Js-Conv: str"}) - Call> update(@Body UpdateDocumentReq req, @Tag BaseReq baseReq); + @POST("/open_api/knowledge/document/update") + @Headers({"Content-Type: application/json", "Agw-Js-Conv: str"}) + Call> update(@Body UpdateDocumentReq req, @Tag BaseReq baseReq); - @POST("/open_api/knowledge/document/delete") - @Headers({"Content-Type: application/json","Agw-Js-Conv: str"}) - Call> delete(@Body DeleteDocumentReq req, @Tag BaseReq baseReq); + @POST("/open_api/knowledge/document/delete") + @Headers({"Content-Type: application/json", "Agw-Js-Conv: str"}) + Call> delete(@Body DeleteDocumentReq req, @Tag BaseReq baseReq); - @POST("/open_api/knowledge/document/list") - @Headers({"Content-Type: application/json","Agw-Js-Conv: str"}) - Call list(@Body ListDocumentReq req, @Tag BaseReq baseReq); + @POST("/open_api/knowledge/document/list") + @Headers({"Content-Type: application/json", "Agw-Js-Conv: str"}) + Call list(@Body ListDocumentReq req, @Tag BaseReq baseReq); } diff --git a/api/src/main/java/com/coze/openapi/api/FileAPI.java b/api/src/main/java/com/coze/openapi/api/FileAPI.java index e5dca30f..232164ca 100644 --- a/api/src/main/java/com/coze/openapi/api/FileAPI.java +++ b/api/src/main/java/com/coze/openapi/api/FileAPI.java @@ -1,14 +1,12 @@ +/* (C)2024 */ package com.coze.openapi.api; +import com.coze.openapi.client.common.BaseReq; import com.coze.openapi.client.common.BaseResponse; import com.coze.openapi.client.files.model.FileInfo; -import com.coze.openapi.client.common.BaseReq; - -import io.reactivex.Single; import okhttp3.MultipartBody; import retrofit2.Call; -import retrofit2.Response; import retrofit2.http.GET; import retrofit2.http.Multipart; import retrofit2.http.POST; @@ -17,11 +15,10 @@ import retrofit2.http.Tag; public interface FileAPI { - @Multipart - @POST("/v1/files/upload") - Call> upload(@Part MultipartBody.Part file, @Tag BaseReq baseReq); + @Multipart + @POST("/v1/files/upload") + Call> upload(@Part MultipartBody.Part file, @Tag BaseReq baseReq); - - @GET("/v1/files/retrieve") - Call> retrieve(@Query("file_id") String fileID, @Tag BaseReq baseReq); + @GET("/v1/files/retrieve") + Call> retrieve(@Query("file_id") String fileID, @Tag BaseReq baseReq); } diff --git a/api/src/main/java/com/coze/openapi/api/WorkflowRunAPI.java b/api/src/main/java/com/coze/openapi/api/WorkflowRunAPI.java index 4f3598c5..3f6c57a5 100644 --- a/api/src/main/java/com/coze/openapi/api/WorkflowRunAPI.java +++ b/api/src/main/java/com/coze/openapi/api/WorkflowRunAPI.java @@ -1,12 +1,11 @@ +/* (C)2024 */ package com.coze.openapi.api; +import com.coze.openapi.client.common.BaseReq; import com.coze.openapi.client.workflows.run.ResumeRunReq; import com.coze.openapi.client.workflows.run.RunWorkflowReq; import com.coze.openapi.client.workflows.run.RunWorkflowResp; -import com.coze.openapi.client.common.BaseReq; -import io.reactivex.Single; -import retrofit2.Response; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.http.Body; @@ -16,14 +15,14 @@ public interface WorkflowRunAPI { - @POST("/v1/workflow/run") - Call run(@Body RunWorkflowReq req, @Tag BaseReq baseReq); + @POST("/v1/workflow/run") + Call run(@Body RunWorkflowReq req, @Tag BaseReq baseReq); - @POST("/v1/workflow/stream_run") - @Streaming - Call stream(@Body RunWorkflowReq req, @Tag BaseReq baseReq); + @POST("/v1/workflow/stream_run") + @Streaming + Call stream(@Body RunWorkflowReq req, @Tag BaseReq baseReq); - @POST("/v1/workflow/stream_resume") - @Streaming - Call resume(@Body ResumeRunReq req, @Tag BaseReq baseReq); -} \ No newline at end of file + @POST("/v1/workflow/stream_resume") + @Streaming + Call resume(@Body ResumeRunReq req, @Tag BaseReq baseReq); +} diff --git a/api/src/main/java/com/coze/openapi/api/WorkflowRunHistoryAPI.java b/api/src/main/java/com/coze/openapi/api/WorkflowRunHistoryAPI.java index b880e68e..7db65767 100644 --- a/api/src/main/java/com/coze/openapi/api/WorkflowRunHistoryAPI.java +++ b/api/src/main/java/com/coze/openapi/api/WorkflowRunHistoryAPI.java @@ -1,19 +1,21 @@ +/* (C)2024 */ package com.coze.openapi.api; +import java.util.List; + +import com.coze.openapi.client.common.BaseReq; import com.coze.openapi.client.common.BaseResponse; import com.coze.openapi.client.workflows.run.model.WorkflowRunHistory; -import io.reactivex.Single; + import retrofit2.Call; -import retrofit2.Response; import retrofit2.http.GET; import retrofit2.http.Path; -import com.coze.openapi.client.common.BaseReq; import retrofit2.http.Tag; -import java.util.List; - public interface WorkflowRunHistoryAPI { - @GET("/v1/workflows/{workflow_id}/run_histories/{execute_id}") - Call>> retrieve(@Path("workflow_id")String workflow_id, @Path("execute_id")String execute_id, @Tag BaseReq baseReq); - + @GET("/v1/workflows/{workflow_id}/run_histories/{execute_id}") + Call>> retrieve( + @Path("workflow_id") String workflow_id, + @Path("execute_id") String execute_id, + @Tag BaseReq baseReq); } diff --git a/api/src/main/java/com/coze/openapi/api/WorkspaceAPI.java b/api/src/main/java/com/coze/openapi/api/WorkspaceAPI.java index 97715f05..7c55d07f 100644 --- a/api/src/main/java/com/coze/openapi/api/WorkspaceAPI.java +++ b/api/src/main/java/com/coze/openapi/api/WorkspaceAPI.java @@ -1,20 +1,20 @@ +/* (C)2024 */ package com.coze.openapi.api; +import com.coze.openapi.client.common.BaseReq; import com.coze.openapi.client.common.BaseResponse; import com.coze.openapi.client.workspace.ListWorkspaceResp; -import io.reactivex.Single; import retrofit2.Call; -import retrofit2.Response; import retrofit2.http.GET; import retrofit2.http.Headers; import retrofit2.http.Query; -import com.coze.openapi.client.common.BaseReq; import retrofit2.http.Tag; public interface WorkspaceAPI { - @Headers({"Content-Type: application/json"}) - @GET("/v1/workspaces") - Call> list(@Query("page_num") Integer page, @Query("page_size") Integer pageSize, @Tag BaseReq baseReq ); + @Headers({"Content-Type: application/json"}) + @GET("/v1/workspaces") + Call> list( + @Query("page_num") Integer page, @Query("page_size") Integer pageSize, @Tag BaseReq baseReq); } diff --git a/api/src/main/java/com/coze/openapi/client/audio/common/AudioFormat.java b/api/src/main/java/com/coze/openapi/client/audio/common/AudioFormat.java index a246ed4e..fc65f8e3 100644 --- a/api/src/main/java/com/coze/openapi/client/audio/common/AudioFormat.java +++ b/api/src/main/java/com/coze/openapi/client/audio/common/AudioFormat.java @@ -1,36 +1,36 @@ +/* (C)2024 */ package com.coze.openapi.client.audio.common; + import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -/** - * Audio format types. - */ +/** Audio format types. */ public enum AudioFormat { - WAV("wav"), - PCM("pcm"), - OGG_OPUS("ogg_opus"), - M4A("m4a"), - AAC("aac"), - MP3("mp3"); + WAV("wav"), + PCM("pcm"), + OGG_OPUS("ogg_opus"), + M4A("m4a"), + AAC("aac"), + MP3("mp3"); - private final String value; + private final String value; - AudioFormat(String value) { - this.value = value; - } + AudioFormat(String value) { + this.value = value; + } - @JsonValue - public String getValue() { - return value; - } + @JsonValue + public String getValue() { + return value; + } - @JsonCreator - public static AudioFormat fromString(String value) { - for (AudioFormat format : AudioFormat.values()) { - if (format.value.equals(value)) { - return format; - } - } - throw new IllegalArgumentException("Unknown AudioFormat: " + value); + @JsonCreator + public static AudioFormat fromString(String value) { + for (AudioFormat format : AudioFormat.values()) { + if (format.value.equals(value)) { + return format; + } } -} \ No newline at end of file + throw new IllegalArgumentException("Unknown AudioFormat: " + value); + } +} diff --git a/api/src/main/java/com/coze/openapi/client/audio/common/LanguageCode.java b/api/src/main/java/com/coze/openapi/client/audio/common/LanguageCode.java index b6591695..57548199 100644 --- a/api/src/main/java/com/coze/openapi/client/audio/common/LanguageCode.java +++ b/api/src/main/java/com/coze/openapi/client/audio/common/LanguageCode.java @@ -1,36 +1,36 @@ +/* (C)2024 */ package com.coze.openapi.client.audio.common; + import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -/** - * Language codes. - */ +/** Language codes. */ public enum LanguageCode { - ZH("zh"), - EN("en"), - JA("ja"), - ES("es"), - ID("id"), - PT("pt"); + ZH("zh"), + EN("en"), + JA("ja"), + ES("es"), + ID("id"), + PT("pt"); - private final String value; + private final String value; - LanguageCode(String value) { - this.value = value; - } + LanguageCode(String value) { + this.value = value; + } - @JsonValue - public String getValue() { - return value; - } + @JsonValue + public String getValue() { + return value; + } - @JsonCreator - public static LanguageCode fromString(String value) { - for (LanguageCode code : LanguageCode.values()) { - if (code.value.equals(value)) { - return code; - } - } - throw new IllegalArgumentException("Unknown LanguageCode: " + value); + @JsonCreator + public static LanguageCode fromString(String value) { + for (LanguageCode code : LanguageCode.values()) { + if (code.value.equals(value)) { + return code; + } } -} \ No newline at end of file + throw new IllegalArgumentException("Unknown LanguageCode: " + value); + } +} diff --git a/api/src/main/java/com/coze/openapi/client/audio/rooms/CreateRoomReq.java b/api/src/main/java/com/coze/openapi/client/audio/rooms/CreateRoomReq.java index 9023cf2f..a8749340 100644 --- a/api/src/main/java/com/coze/openapi/client/audio/rooms/CreateRoomReq.java +++ b/api/src/main/java/com/coze/openapi/client/audio/rooms/CreateRoomReq.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.audio.rooms; import com.coze.openapi.client.audio.rooms.model.RoomConfig; @@ -17,15 +18,16 @@ @AllArgsConstructor @EqualsAndHashCode(callSuper = true) public class CreateRoomReq extends BaseReq { - @NonNull - @JsonProperty("bot_id") - private String botID; - @JsonProperty("conversation_id") - private String conversationID; - @JsonProperty("voice_id") - private String voiceID; + @NonNull + @JsonProperty("bot_id") + private String botID; - @JsonProperty("config") - private RoomConfig config; + @JsonProperty("conversation_id") + private String conversationID; + @JsonProperty("voice_id") + private String voiceID; + + @JsonProperty("config") + private RoomConfig config; } diff --git a/api/src/main/java/com/coze/openapi/client/audio/rooms/CreateRoomResp.java b/api/src/main/java/com/coze/openapi/client/audio/rooms/CreateRoomResp.java index 5ba9b309..e9b09253 100644 --- a/api/src/main/java/com/coze/openapi/client/audio/rooms/CreateRoomResp.java +++ b/api/src/main/java/com/coze/openapi/client/audio/rooms/CreateRoomResp.java @@ -1,8 +1,9 @@ +/* (C)2024 */ package com.coze.openapi.client.audio.rooms; - import com.coze.openapi.client.common.BaseResp; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.*; @Data @@ -11,28 +12,20 @@ @AllArgsConstructor @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) -public class CreateRoomResp extends BaseResp{ - /** - * 房间 id - */ - @JsonProperty("room_id") - private String roomID; +public class CreateRoomResp extends BaseResp { + /** 房间 id */ + @JsonProperty("room_id") + private String roomID; - /** - * app_id - */ - @JsonProperty("app_id") - private String appID; + /** app_id */ + @JsonProperty("app_id") + private String appID; - /** - * token - */ - @JsonProperty("token") - private String token; + /** token */ + @JsonProperty("token") + private String token; - /** - * uid - */ - @JsonProperty("uid") - private String uid; -} \ No newline at end of file + /** uid */ + @JsonProperty("uid") + private String uid; +} diff --git a/api/src/main/java/com/coze/openapi/client/audio/rooms/model/AudioCodec.java b/api/src/main/java/com/coze/openapi/client/audio/rooms/model/AudioCodec.java index c1a0d751..5f8a4fc5 100644 --- a/api/src/main/java/com/coze/openapi/client/audio/rooms/model/AudioCodec.java +++ b/api/src/main/java/com/coze/openapi/client/audio/rooms/model/AudioCodec.java @@ -1,32 +1,33 @@ +/* (C)2024 */ package com.coze.openapi.client.audio.rooms.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; public enum AudioCodec { - AACLC("AACLC"), - G711A("G711A"), - OPUS("OPUS"), - G722("G722"); + AACLC("AACLC"), + G711A("G711A"), + OPUS("OPUS"), + G722("G722"); - private final String value; + private final String value; - AudioCodec(String value) { - this.value = value; - } + AudioCodec(String value) { + this.value = value; + } - @JsonValue - public String getValue() { - return value; - } + @JsonValue + public String getValue() { + return value; + } - @JsonCreator - public static AudioCodec fromString(String value) { - for (AudioCodec codec : AudioCodec.values()) { - if (codec.value.equals(value)) { - return codec; - } - } - throw new IllegalArgumentException("Invalid audio codec: " + value); + @JsonCreator + public static AudioCodec fromString(String value) { + for (AudioCodec codec : AudioCodec.values()) { + if (codec.value.equals(value)) { + return codec; + } } -} \ No newline at end of file + throw new IllegalArgumentException("Invalid audio codec: " + value); + } +} diff --git a/api/src/main/java/com/coze/openapi/client/audio/rooms/model/RoomAudioConfig.java b/api/src/main/java/com/coze/openapi/client/audio/rooms/model/RoomAudioConfig.java index ea5f497e..80b79d35 100644 --- a/api/src/main/java/com/coze/openapi/client/audio/rooms/model/RoomAudioConfig.java +++ b/api/src/main/java/com/coze/openapi/client/audio/rooms/model/RoomAudioConfig.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.audio.rooms.model; import lombok.AllArgsConstructor; @@ -10,6 +11,5 @@ @NoArgsConstructor @AllArgsConstructor public class RoomAudioConfig { - @Builder.Default - private AudioCodec codec = AudioCodec.OPUS; + @Builder.Default private AudioCodec codec = AudioCodec.OPUS; } diff --git a/api/src/main/java/com/coze/openapi/client/audio/rooms/model/RoomConfig.java b/api/src/main/java/com/coze/openapi/client/audio/rooms/model/RoomConfig.java index 3c132978..17b57a2c 100644 --- a/api/src/main/java/com/coze/openapi/client/audio/rooms/model/RoomConfig.java +++ b/api/src/main/java/com/coze/openapi/client/audio/rooms/model/RoomConfig.java @@ -1,6 +1,6 @@ +/* (C)2024 */ package com.coze.openapi.client.audio.rooms.model; - import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; @@ -13,10 +13,10 @@ @NoArgsConstructor @AllArgsConstructor public class RoomConfig { - @JsonProperty("audio_config") - private RoomAudioConfig audioConfig; + @JsonProperty("audio_config") + private RoomAudioConfig audioConfig; - public static RoomConfig of(AudioCodec codec) { - return RoomConfig.builder().audioConfig(RoomAudioConfig.builder().codec(codec).build()).build(); - } + public static RoomConfig of(AudioCodec codec) { + return RoomConfig.builder().audioConfig(RoomAudioConfig.builder().codec(codec).build()).build(); + } } diff --git a/api/src/main/java/com/coze/openapi/client/audio/speech/CreateSpeechReq.java b/api/src/main/java/com/coze/openapi/client/audio/speech/CreateSpeechReq.java index 538e1932..c91327b0 100644 --- a/api/src/main/java/com/coze/openapi/client/audio/speech/CreateSpeechReq.java +++ b/api/src/main/java/com/coze/openapi/client/audio/speech/CreateSpeechReq.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.audio.speech; import com.coze.openapi.client.audio.common.AudioFormat; @@ -13,16 +14,19 @@ @AllArgsConstructor @EqualsAndHashCode(callSuper = true) public class CreateSpeechReq extends BaseReq { - @NonNull - @JsonProperty("input") - private String input; - @NonNull - @JsonProperty("voice_id") - private String voiceID; - @Builder.Default - @JsonProperty("response_format") - private AudioFormat responseFormat = AudioFormat.MP3; - @JsonProperty("speed") - @Builder.Default - private float speed = 1.0f; + @NonNull + @JsonProperty("input") + private String input; + + @NonNull + @JsonProperty("voice_id") + private String voiceID; + + @Builder.Default + @JsonProperty("response_format") + private AudioFormat responseFormat = AudioFormat.MP3; + + @JsonProperty("speed") + @Builder.Default + private float speed = 1.0f; } diff --git a/api/src/main/java/com/coze/openapi/client/audio/speech/CreateSpeechResp.java b/api/src/main/java/com/coze/openapi/client/audio/speech/CreateSpeechResp.java index bc066fda..3a9ab614 100644 --- a/api/src/main/java/com/coze/openapi/client/audio/speech/CreateSpeechResp.java +++ b/api/src/main/java/com/coze/openapi/client/audio/speech/CreateSpeechResp.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.audio.speech; import com.coze.openapi.client.common.FileResponse; @@ -12,8 +13,8 @@ @SuperBuilder @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) -public class CreateSpeechResp extends FileResponse{ - public CreateSpeechResp(ResponseBody response) { - super(response); - } +public class CreateSpeechResp extends FileResponse { + public CreateSpeechResp(ResponseBody response) { + super(response); + } } diff --git a/api/src/main/java/com/coze/openapi/client/audio/voices/CloneVoiceReq.java b/api/src/main/java/com/coze/openapi/client/audio/voices/CloneVoiceReq.java index 581a2b8a..9c863ed8 100644 --- a/api/src/main/java/com/coze/openapi/client/audio/voices/CloneVoiceReq.java +++ b/api/src/main/java/com/coze/openapi/client/audio/voices/CloneVoiceReq.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.audio.voices; import com.coze.openapi.client.audio.common.AudioFormat; @@ -18,20 +19,26 @@ @AllArgsConstructor @EqualsAndHashCode(callSuper = true) public class CloneVoiceReq extends BaseReq { - @NonNull - @JsonProperty("voice_name") - private String voiceName; - @NonNull - @JsonProperty("file_path") - private String filePath; - @NonNull - @JsonProperty("audio_format") - private AudioFormat audioFormat; - @JsonProperty("language") - private LanguageCode language; - @JsonProperty("voice_id") - private String voiceID; - @JsonProperty("preview_text") - private String previewText; - private String text; + @NonNull + @JsonProperty("voice_name") + private String voiceName; + + @NonNull + @JsonProperty("file_path") + private String filePath; + + @NonNull + @JsonProperty("audio_format") + private AudioFormat audioFormat; + + @JsonProperty("language") + private LanguageCode language; + + @JsonProperty("voice_id") + private String voiceID; + + @JsonProperty("preview_text") + private String previewText; + + private String text; } diff --git a/api/src/main/java/com/coze/openapi/client/audio/voices/CloneVoiceResp.java b/api/src/main/java/com/coze/openapi/client/audio/voices/CloneVoiceResp.java index e3a7dad2..29881949 100644 --- a/api/src/main/java/com/coze/openapi/client/audio/voices/CloneVoiceResp.java +++ b/api/src/main/java/com/coze/openapi/client/audio/voices/CloneVoiceResp.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.audio.voices; import com.coze.openapi.client.common.BaseResp; @@ -17,6 +18,6 @@ @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) public class CloneVoiceResp extends BaseResp { - @JsonProperty("voice_id") - private String voiceID; + @JsonProperty("voice_id") + private String voiceID; } diff --git a/api/src/main/java/com/coze/openapi/client/audio/voices/ListVoiceReq.java b/api/src/main/java/com/coze/openapi/client/audio/voices/ListVoiceReq.java index 07d3737b..2485a909 100644 --- a/api/src/main/java/com/coze/openapi/client/audio/voices/ListVoiceReq.java +++ b/api/src/main/java/com/coze/openapi/client/audio/voices/ListVoiceReq.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.audio.voices; import com.coze.openapi.client.common.BaseReq; @@ -16,14 +17,14 @@ @AllArgsConstructor @EqualsAndHashCode(callSuper = true) public class ListVoiceReq extends BaseReq { - @JsonProperty("filter_system_voice") - private Boolean filterSystemVoice; + @JsonProperty("filter_system_voice") + private Boolean filterSystemVoice; - @JsonProperty("page_num") - @Builder.Default - private Integer pageNum = 1; + @JsonProperty("page_num") + @Builder.Default + private Integer pageNum = 1; - @JsonProperty("page_size") - @Builder.Default - private Integer pageSize = 100; + @JsonProperty("page_size") + @Builder.Default + private Integer pageSize = 100; } diff --git a/api/src/main/java/com/coze/openapi/client/audio/voices/ListVoiceResp.java b/api/src/main/java/com/coze/openapi/client/audio/voices/ListVoiceResp.java index e5945422..63df1603 100644 --- a/api/src/main/java/com/coze/openapi/client/audio/voices/ListVoiceResp.java +++ b/api/src/main/java/com/coze/openapi/client/audio/voices/ListVoiceResp.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.audio.voices; import java.util.List; @@ -7,7 +8,6 @@ import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; -import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; @@ -21,6 +21,6 @@ @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) public class ListVoiceResp extends BaseResp { - @JsonProperty("voice_list") - private List voiceList; + @JsonProperty("voice_list") + private List voiceList; } diff --git a/api/src/main/java/com/coze/openapi/client/audio/voices/model/Voice.java b/api/src/main/java/com/coze/openapi/client/audio/voices/model/Voice.java index 38304881..aab3e4d2 100644 --- a/api/src/main/java/com/coze/openapi/client/audio/voices/model/Voice.java +++ b/api/src/main/java/com/coze/openapi/client/audio/voices/model/Voice.java @@ -1,5 +1,8 @@ +/* (C)2024 */ package com.coze.openapi.client.audio.voices.model; + import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -10,63 +13,43 @@ @NoArgsConstructor @AllArgsConstructor public class Voice { - /** - * The id of voice. - */ - @JsonProperty("voice_id") - private String voiceID; - - /** - * The name of voice. - */ - @JsonProperty("name") - private String name; - - /** - * If is system voice. - */ - @JsonProperty("is_system_voice") - private boolean isSystemVoice; - - /** - * Language code. - */ - @JsonProperty("language_code") - private String languageCode; - - /** - * Language name. - */ - @JsonProperty("language_name") - private String languageName; - - /** - * Preview text for the voice. - */ - @JsonProperty("preview_text") - private String previewText; - - /** - * Preview audio URL for the voice. - */ - @JsonProperty("preview_audio") - private String previewAudio; - - /** - * Number of remaining training times available for current voice. - */ - @JsonProperty("available_training_times") - private int availableTrainingTimes; - - /** - * Voice creation timestamp. - */ - @JsonProperty("create_time") - private int createTime; - - /** - * Voice last update timestamp. - */ - @JsonProperty("update_time") - private int updateTime; -} \ No newline at end of file + /** The id of voice. */ + @JsonProperty("voice_id") + private String voiceID; + + /** The name of voice. */ + @JsonProperty("name") + private String name; + + /** If is system voice. */ + @JsonProperty("is_system_voice") + private boolean isSystemVoice; + + /** Language code. */ + @JsonProperty("language_code") + private String languageCode; + + /** Language name. */ + @JsonProperty("language_name") + private String languageName; + + /** Preview text for the voice. */ + @JsonProperty("preview_text") + private String previewText; + + /** Preview audio URL for the voice. */ + @JsonProperty("preview_audio") + private String previewAudio; + + /** Number of remaining training times available for current voice. */ + @JsonProperty("available_training_times") + private int availableTrainingTimes; + + /** Voice creation timestamp. */ + @JsonProperty("create_time") + private int createTime; + + /** Voice last update timestamp. */ + @JsonProperty("update_time") + private int updateTime; +} diff --git a/api/src/main/java/com/coze/openapi/client/auth/DeviceAuthReq.java b/api/src/main/java/com/coze/openapi/client/auth/DeviceAuthReq.java index 2baf1f79..ba4835e6 100644 --- a/api/src/main/java/com/coze/openapi/client/auth/DeviceAuthReq.java +++ b/api/src/main/java/com/coze/openapi/client/auth/DeviceAuthReq.java @@ -1,8 +1,10 @@ +/* (C)2024 */ package com.coze.openapi.client.auth; import com.coze.openapi.client.common.BaseReq; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; @@ -16,6 +18,6 @@ @JsonInclude(JsonInclude.Include.NON_NULL) @EqualsAndHashCode(callSuper = true) public class DeviceAuthReq extends BaseReq { - @JsonProperty("client_id") - public String clientID; + @JsonProperty("client_id") + public String clientID; } diff --git a/api/src/main/java/com/coze/openapi/client/auth/DeviceAuthResp.java b/api/src/main/java/com/coze/openapi/client/auth/DeviceAuthResp.java index e8fb996a..64170ee7 100644 --- a/api/src/main/java/com/coze/openapi/client/auth/DeviceAuthResp.java +++ b/api/src/main/java/com/coze/openapi/client/auth/DeviceAuthResp.java @@ -1,8 +1,10 @@ +/* (C)2024 */ package com.coze.openapi.client.auth; import com.coze.openapi.client.common.BaseResp; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -18,21 +20,21 @@ @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) public class DeviceAuthResp extends BaseResp { - @JsonProperty("device_code") - private String deviceCode; + @JsonProperty("device_code") + private String deviceCode; - @JsonProperty("user_code") - private String userCode; + @JsonProperty("user_code") + private String userCode; - @JsonProperty("verification_uri") - private String verificationURI; + @JsonProperty("verification_uri") + private String verificationURI; - @JsonProperty("verification_url") - private String verificationURL; + @JsonProperty("verification_url") + private String verificationURL; - @JsonProperty("expires_in") - private int expiresIn; + @JsonProperty("expires_in") + private int expiresIn; - @JsonProperty("interval") - private int interval; + @JsonProperty("interval") + private int interval; } diff --git a/api/src/main/java/com/coze/openapi/client/auth/GetAccessTokenReq.java b/api/src/main/java/com/coze/openapi/client/auth/GetAccessTokenReq.java index 70ef930b..0812a7b7 100644 --- a/api/src/main/java/com/coze/openapi/client/auth/GetAccessTokenReq.java +++ b/api/src/main/java/com/coze/openapi/client/auth/GetAccessTokenReq.java @@ -1,15 +1,16 @@ +/* (C)2024 */ package com.coze.openapi.client.auth; import com.coze.openapi.client.auth.scope.Scope; import com.coze.openapi.client.common.BaseReq; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; -import lombok.experimental.SuperBuilder; - -import com.fasterxml.jackson.annotation.JsonProperty; import lombok.NoArgsConstructor; +import lombok.experimental.SuperBuilder; @Data @SuperBuilder @@ -18,30 +19,30 @@ @JsonInclude(JsonInclude.Include.NON_NULL) @EqualsAndHashCode(callSuper = true) public class GetAccessTokenReq extends BaseReq { - @JsonProperty("client_id") - private String clientID; + @JsonProperty("client_id") + private String clientID; - @JsonProperty("code") - private String code; + @JsonProperty("code") + private String code; - @JsonProperty("grant_type") - private String grantType; + @JsonProperty("grant_type") + private String grantType; - @JsonProperty("redirect_uri") - private String redirectUri; + @JsonProperty("redirect_uri") + private String redirectUri; - @JsonProperty("refresh_token") - private String refreshToken; + @JsonProperty("refresh_token") + private String refreshToken; - @JsonProperty("code_verifier") - private String codeVerifier; + @JsonProperty("code_verifier") + private String codeVerifier; - @JsonProperty("device_code") - private String deviceCode; + @JsonProperty("device_code") + private String deviceCode; - @JsonProperty("duration_seconds") - private Integer durationSeconds; + @JsonProperty("duration_seconds") + private Integer durationSeconds; - @JsonProperty("scope") - private Scope scope; + @JsonProperty("scope") + private Scope scope; } diff --git a/api/src/main/java/com/coze/openapi/client/auth/GetPKCEAuthURLResp.java b/api/src/main/java/com/coze/openapi/client/auth/GetPKCEAuthURLResp.java index a100b9e6..6121ae9c 100644 --- a/api/src/main/java/com/coze/openapi/client/auth/GetPKCEAuthURLResp.java +++ b/api/src/main/java/com/coze/openapi/client/auth/GetPKCEAuthURLResp.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.auth; import lombok.AllArgsConstructor; @@ -8,6 +9,6 @@ @NoArgsConstructor @AllArgsConstructor public class GetPKCEAuthURLResp { - private String codeVerifier; - private String authorizationURL; + private String codeVerifier; + private String authorizationURL; } diff --git a/api/src/main/java/com/coze/openapi/client/auth/GrantType.java b/api/src/main/java/com/coze/openapi/client/auth/GrantType.java index 0a093278..19d07845 100644 --- a/api/src/main/java/com/coze/openapi/client/auth/GrantType.java +++ b/api/src/main/java/com/coze/openapi/client/auth/GrantType.java @@ -1,19 +1,21 @@ +/* (C)2024 */ package com.coze.openapi.client.auth; + import lombok.AllArgsConstructor; import lombok.Getter; @Getter @AllArgsConstructor public enum GrantType { - AuthorizationCode("authorization_code"), - DeviceCode("urn:ietf:params:oauth:grant-type:device_code"), - JWTCode("urn:ietf:params:oauth:grant-type:jwt-bearer"), - RefreshToken("refresh_token"); + AuthorizationCode("authorization_code"), + DeviceCode("urn:ietf:params:oauth:grant-type:device_code"), + JWTCode("urn:ietf:params:oauth:grant-type:jwt-bearer"), + RefreshToken("refresh_token"); - private final String value; + private final String value; - @Override - public String toString() { - return this.value; - } + @Override + public String toString() { + return this.value; + } } diff --git a/api/src/main/java/com/coze/openapi/client/auth/OAuthToken.java b/api/src/main/java/com/coze/openapi/client/auth/OAuthToken.java index b4c50538..ae7571ef 100644 --- a/api/src/main/java/com/coze/openapi/client/auth/OAuthToken.java +++ b/api/src/main/java/com/coze/openapi/client/auth/OAuthToken.java @@ -1,12 +1,14 @@ +/* (C)2024 */ package com.coze.openapi.client.auth; -import com.fasterxml.jackson.annotation.JsonProperty; import com.coze.openapi.client.common.BaseResp; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Data; -import lombok.NoArgsConstructor; import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; import lombok.ToString; @Data @@ -16,11 +18,12 @@ @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) public class OAuthToken extends BaseResp { - @JsonProperty("access_token") - private String accessToken; - @JsonProperty("expires_in") - private Integer expiresIn; - @JsonProperty("refresh_token") - private String refreshToken; + @JsonProperty("access_token") + private String accessToken; + + @JsonProperty("expires_in") + private Integer expiresIn; + @JsonProperty("refresh_token") + private String refreshToken; } diff --git a/api/src/main/java/com/coze/openapi/client/auth/scope/Scope.java b/api/src/main/java/com/coze/openapi/client/auth/scope/Scope.java index 8ef5c309..c60eb5b6 100644 --- a/api/src/main/java/com/coze/openapi/client/auth/scope/Scope.java +++ b/api/src/main/java/com/coze/openapi/client/auth/scope/Scope.java @@ -1,4 +1,7 @@ +/* (C)2024 */ package com.coze.openapi.client.auth.scope; + +import java.util.Collections; import java.util.List; import java.util.Map; @@ -8,34 +11,29 @@ import lombok.AllArgsConstructor; import lombok.Data; -import java.util.Collections; - @Data @AllArgsConstructor public class Scope { - private ScopeAccountPermission accountPermission; - private ScopeAttributeConstraint attributeConstraint; + private ScopeAccountPermission accountPermission; + private ScopeAttributeConstraint attributeConstraint; + + public Map toMap() { + ObjectMapper mapper = new ObjectMapper(); + return mapper.convertValue(this, new TypeReference>() {}); + } - public Map toMap() { - ObjectMapper mapper = new ObjectMapper(); - return mapper.convertValue(this, new TypeReference>() {}); + public static Scope buildBotChat(List botIDList, List permissionList) { + if (permissionList == null || permissionList.isEmpty()) { + permissionList = Collections.singletonList("Connector.botChat"); } - public static Scope buildBotChat(List botIDList, List permissionList) { - if (permissionList == null || permissionList.isEmpty()) { - permissionList = Collections.singletonList("Connector.botChat"); - } - - ScopeAttributeConstraint attributeConstraint = null; - if (botIDList != null && !botIDList.isEmpty()) { - ScopeAttributeConstraintConnectorBotChatAttribute chatAttribute = - new ScopeAttributeConstraintConnectorBotChatAttribute(botIDList); - attributeConstraint = new ScopeAttributeConstraint(chatAttribute); - } - - return new Scope( - new ScopeAccountPermission(permissionList), - attributeConstraint - ); + ScopeAttributeConstraint attributeConstraint = null; + if (botIDList != null && !botIDList.isEmpty()) { + ScopeAttributeConstraintConnectorBotChatAttribute chatAttribute = + new ScopeAttributeConstraintConnectorBotChatAttribute(botIDList); + attributeConstraint = new ScopeAttributeConstraint(chatAttribute); } -} \ No newline at end of file + + return new Scope(new ScopeAccountPermission(permissionList), attributeConstraint); + } +} diff --git a/api/src/main/java/com/coze/openapi/client/auth/scope/ScopeAccountPermission.java b/api/src/main/java/com/coze/openapi/client/auth/scope/ScopeAccountPermission.java index b57a55a7..bbc15f29 100644 --- a/api/src/main/java/com/coze/openapi/client/auth/scope/ScopeAccountPermission.java +++ b/api/src/main/java/com/coze/openapi/client/auth/scope/ScopeAccountPermission.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.auth.scope; import java.util.List; @@ -8,5 +9,5 @@ @Data @AllArgsConstructor public class ScopeAccountPermission { - private List permissionList; -} \ No newline at end of file + private List permissionList; +} diff --git a/api/src/main/java/com/coze/openapi/client/auth/scope/ScopeAttributeConstraint.java b/api/src/main/java/com/coze/openapi/client/auth/scope/ScopeAttributeConstraint.java index 40ee6067..6291800e 100644 --- a/api/src/main/java/com/coze/openapi/client/auth/scope/ScopeAttributeConstraint.java +++ b/api/src/main/java/com/coze/openapi/client/auth/scope/ScopeAttributeConstraint.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.auth.scope; import lombok.AllArgsConstructor; @@ -6,5 +7,5 @@ @Data @AllArgsConstructor public class ScopeAttributeConstraint { - private ScopeAttributeConstraintConnectorBotChatAttribute connectorBotChatAttribute; + private ScopeAttributeConstraintConnectorBotChatAttribute connectorBotChatAttribute; } diff --git a/api/src/main/java/com/coze/openapi/client/auth/scope/ScopeAttributeConstraintConnectorBotChatAttribute.java b/api/src/main/java/com/coze/openapi/client/auth/scope/ScopeAttributeConstraintConnectorBotChatAttribute.java index a2aa8ef5..13d77860 100644 --- a/api/src/main/java/com/coze/openapi/client/auth/scope/ScopeAttributeConstraintConnectorBotChatAttribute.java +++ b/api/src/main/java/com/coze/openapi/client/auth/scope/ScopeAttributeConstraintConnectorBotChatAttribute.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.auth.scope; import java.util.List; @@ -8,5 +9,5 @@ @AllArgsConstructor @Data public class ScopeAttributeConstraintConnectorBotChatAttribute { - private List botIDList; -} \ No newline at end of file + private List botIDList; +} diff --git a/api/src/main/java/com/coze/openapi/client/bots/CreateBotReq.java b/api/src/main/java/com/coze/openapi/client/bots/CreateBotReq.java index 04d2d7d1..e68ec1f2 100644 --- a/api/src/main/java/com/coze/openapi/client/bots/CreateBotReq.java +++ b/api/src/main/java/com/coze/openapi/client/bots/CreateBotReq.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.bots; import org.jetbrains.annotations.NotNull; @@ -7,10 +8,10 @@ import com.coze.openapi.client.common.BaseReq; import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; -import lombok.AllArgsConstructor; import lombok.experimental.SuperBuilder; @Data @@ -19,23 +20,23 @@ @AllArgsConstructor @EqualsAndHashCode(callSuper = true) public class CreateBotReq extends BaseReq { - @NotNull - @JsonProperty("space_id") - String spaceID; + @NotNull + @JsonProperty("space_id") + String spaceID; - @NotNull - @JsonProperty("name") - String name; + @NotNull + @JsonProperty("name") + String name; - @JsonProperty("description") - String description; + @JsonProperty("description") + String description; - @JsonProperty("icon_file_id") - String iconFileID; + @JsonProperty("icon_file_id") + String iconFileID; - @JsonProperty("prompt_info") - BotPromptInfo promptInfo; + @JsonProperty("prompt_info") + BotPromptInfo promptInfo; - @JsonProperty("onboarding_info") - BotOnboardingInfo onboardingInfo; + @JsonProperty("onboarding_info") + BotOnboardingInfo onboardingInfo; } diff --git a/api/src/main/java/com/coze/openapi/client/bots/CreateBotResp.java b/api/src/main/java/com/coze/openapi/client/bots/CreateBotResp.java index bc2990c5..a3115558 100644 --- a/api/src/main/java/com/coze/openapi/client/bots/CreateBotResp.java +++ b/api/src/main/java/com/coze/openapi/client/bots/CreateBotResp.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.bots; import com.coze.openapi.client.common.BaseResp; @@ -17,6 +18,6 @@ @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) public class CreateBotResp extends BaseResp { - @JsonProperty("bot_id") - private String botID; + @JsonProperty("bot_id") + private String botID; } diff --git a/api/src/main/java/com/coze/openapi/client/bots/ListBotReq.java b/api/src/main/java/com/coze/openapi/client/bots/ListBotReq.java index 7e06a65e..036381bb 100644 --- a/api/src/main/java/com/coze/openapi/client/bots/ListBotReq.java +++ b/api/src/main/java/com/coze/openapi/client/bots/ListBotReq.java @@ -1,21 +1,21 @@ +/* (C)2024 */ package com.coze.openapi.client.bots; +import com.coze.openapi.client.common.BaseReq; + +import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.experimental.SuperBuilder; -import com.coze.openapi.client.common.BaseReq; - -import lombok.AllArgsConstructor; - @Data @SuperBuilder @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode(callSuper = true) public class ListBotReq extends BaseReq { - private String spaceID; - private Integer pageNum; - private Integer pageSize; + private String spaceID; + private Integer pageNum; + private Integer pageSize; } diff --git a/api/src/main/java/com/coze/openapi/client/bots/ListBotResp.java b/api/src/main/java/com/coze/openapi/client/bots/ListBotResp.java index 1e2d683e..32f59917 100644 --- a/api/src/main/java/com/coze/openapi/client/bots/ListBotResp.java +++ b/api/src/main/java/com/coze/openapi/client/bots/ListBotResp.java @@ -1,18 +1,18 @@ +/* (C)2024 */ package com.coze.openapi.client.bots; -import com.coze.openapi.client.bots.model.SimpleBot; -import com.coze.openapi.client.common.BaseResp; - import java.util.List; +import com.coze.openapi.client.bots.model.SimpleBot; +import com.coze.openapi.client.common.BaseResp; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; @Data @Builder @@ -20,10 +20,10 @@ @AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) @EqualsAndHashCode(callSuper = true) -public class ListBotResp extends BaseResp{ - @JsonProperty("space_bots") - private List bots; +public class ListBotResp extends BaseResp { + @JsonProperty("space_bots") + private List bots; - @JsonProperty("total") - private Integer total; + @JsonProperty("total") + private Integer total; } diff --git a/api/src/main/java/com/coze/openapi/client/bots/PublishBotReq.java b/api/src/main/java/com/coze/openapi/client/bots/PublishBotReq.java index 48b6f62c..6c9872dc 100644 --- a/api/src/main/java/com/coze/openapi/client/bots/PublishBotReq.java +++ b/api/src/main/java/com/coze/openapi/client/bots/PublishBotReq.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.bots; import java.util.List; @@ -14,9 +15,10 @@ @AllArgsConstructor @EqualsAndHashCode(callSuper = true) public class PublishBotReq extends BaseReq { - @NonNull - @JsonProperty("bot_id") - private String botID; - @JsonProperty("connector_ids") - private List connectorIDs; + @NonNull + @JsonProperty("bot_id") + private String botID; + + @JsonProperty("connector_ids") + private List connectorIDs; } diff --git a/api/src/main/java/com/coze/openapi/client/bots/PublishBotResp.java b/api/src/main/java/com/coze/openapi/client/bots/PublishBotResp.java index a4cdbe77..c933bcd0 100644 --- a/api/src/main/java/com/coze/openapi/client/bots/PublishBotResp.java +++ b/api/src/main/java/com/coze/openapi/client/bots/PublishBotResp.java @@ -1,19 +1,21 @@ +/* (C)2024 */ package com.coze.openapi.client.bots; -import lombok.*; - import com.coze.openapi.client.common.BaseResp; import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.*; + @Data @Builder @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) -public class PublishBotResp extends BaseResp{ - @JsonProperty("bot_id") - private String botID; - @JsonProperty("version") - private String botVersion; +public class PublishBotResp extends BaseResp { + @JsonProperty("bot_id") + private String botID; + + @JsonProperty("version") + private String botVersion; } diff --git a/api/src/main/java/com/coze/openapi/client/bots/RetrieveBotReq.java b/api/src/main/java/com/coze/openapi/client/bots/RetrieveBotReq.java index 6ab07e75..1bb628a6 100644 --- a/api/src/main/java/com/coze/openapi/client/bots/RetrieveBotReq.java +++ b/api/src/main/java/com/coze/openapi/client/bots/RetrieveBotReq.java @@ -1,7 +1,9 @@ +/* (C)2024 */ package com.coze.openapi.client.bots; import com.coze.openapi.client.common.BaseReq; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; @@ -14,10 +16,10 @@ @NoArgsConstructor @EqualsAndHashCode(callSuper = true) public class RetrieveBotReq extends BaseReq { - @JsonProperty("bot_id") - private String botID; + @JsonProperty("bot_id") + private String botID; - public static RetrieveBotReq of(String botID) { - return RetrieveBotReq.builder().botID(botID).build(); - } + public static RetrieveBotReq of(String botID) { + return RetrieveBotReq.builder().botID(botID).build(); + } } diff --git a/api/src/main/java/com/coze/openapi/client/bots/RetrieveBotResp.java b/api/src/main/java/com/coze/openapi/client/bots/RetrieveBotResp.java index 4e3334b8..3baff173 100644 --- a/api/src/main/java/com/coze/openapi/client/bots/RetrieveBotResp.java +++ b/api/src/main/java/com/coze/openapi/client/bots/RetrieveBotResp.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.bots; import com.coze.openapi.client.bots.model.Bot; @@ -14,6 +15,6 @@ @NoArgsConstructor @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) -public class RetrieveBotResp extends BaseResp{ - private Bot bot; +public class RetrieveBotResp extends BaseResp { + private Bot bot; } diff --git a/api/src/main/java/com/coze/openapi/client/bots/UpdateBotReq.java b/api/src/main/java/com/coze/openapi/client/bots/UpdateBotReq.java index aba14892..aebd2460 100644 --- a/api/src/main/java/com/coze/openapi/client/bots/UpdateBotReq.java +++ b/api/src/main/java/com/coze/openapi/client/bots/UpdateBotReq.java @@ -1,15 +1,18 @@ +/* (C)2024 */ package com.coze.openapi.client.bots; +import org.jetbrains.annotations.NotNull; + import com.coze.openapi.client.bots.model.BotKnowledge; import com.coze.openapi.client.bots.model.BotOnboardingInfo; import com.coze.openapi.client.bots.model.BotPromptInfo; import com.coze.openapi.client.common.BaseReq; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; -import org.jetbrains.annotations.NotNull; import lombok.experimental.SuperBuilder; @Data @@ -19,25 +22,25 @@ @EqualsAndHashCode(callSuper = true) public class UpdateBotReq extends BaseReq { - @NotNull - @JsonProperty("bot_id") - private String botID; + @NotNull + @JsonProperty("bot_id") + private String botID; - @JsonProperty("name") - private String name; + @JsonProperty("name") + private String name; - @JsonProperty("description") - private String description; + @JsonProperty("description") + private String description; - @JsonProperty("icon_file_id") - private String iconFileID; + @JsonProperty("icon_file_id") + private String iconFileID; - @JsonProperty("prompt_info") - private BotPromptInfo promptInfo; + @JsonProperty("prompt_info") + private BotPromptInfo promptInfo; - @JsonProperty("onboarding_info") - private BotOnboardingInfo onboardingInfo; + @JsonProperty("onboarding_info") + private BotOnboardingInfo onboardingInfo; - @JsonProperty("knowledge") - private BotKnowledge knowledge; -} \ No newline at end of file + @JsonProperty("knowledge") + private BotKnowledge knowledge; +} diff --git a/api/src/main/java/com/coze/openapi/client/bots/UpdateBotResp.java b/api/src/main/java/com/coze/openapi/client/bots/UpdateBotResp.java index 1d453640..6e6d2b47 100644 --- a/api/src/main/java/com/coze/openapi/client/bots/UpdateBotResp.java +++ b/api/src/main/java/com/coze/openapi/client/bots/UpdateBotResp.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.bots; import com.coze.openapi.client.common.BaseResp; @@ -13,6 +14,4 @@ @NoArgsConstructor @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) -public class UpdateBotResp extends BaseResp{ - -} +public class UpdateBotResp extends BaseResp {} diff --git a/api/src/main/java/com/coze/openapi/client/bots/model/Bot.java b/api/src/main/java/com/coze/openapi/client/bots/model/Bot.java index f3f5f1f9..d476d70a 100644 --- a/api/src/main/java/com/coze/openapi/client/bots/model/Bot.java +++ b/api/src/main/java/com/coze/openapi/client/bots/model/Bot.java @@ -1,50 +1,53 @@ +/* (C)2024 */ package com.coze.openapi.client.bots.model; +import java.util.List; + import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; -import java.util.List; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class Bot { - @JsonProperty("bot_id") - private String botID; + @JsonProperty("bot_id") + private String botID; - @JsonProperty("name") - private String name; + @JsonProperty("name") + private String name; - @JsonProperty("description") - private String description; + @JsonProperty("description") + private String description; - @JsonProperty("icon_url") - private String iconURL; + @JsonProperty("icon_url") + private String iconURL; - @JsonProperty("create_time") - private Long createTime; + @JsonProperty("create_time") + private Long createTime; - @JsonProperty("update_time") - private Long updateTime; + @JsonProperty("update_time") + private Long updateTime; - @JsonProperty("version") - private String version; + @JsonProperty("version") + private String version; - @JsonProperty("prompt_info") - private BotPromptInfo promptInfo; + @JsonProperty("prompt_info") + private BotPromptInfo promptInfo; - @JsonProperty("onboarding_info") - private BotOnboardingInfo onboardingInfo; + @JsonProperty("onboarding_info") + private BotOnboardingInfo onboardingInfo; - @JsonProperty("bot_mode") - private BotMode botMode; + @JsonProperty("bot_mode") + private BotMode botMode; - @JsonProperty("plugin_info_list") - private List pluginInfoList; + @JsonProperty("plugin_info_list") + private List pluginInfoList; - @JsonProperty("model_info") - private BotModelInfo modelInfo; -} \ No newline at end of file + @JsonProperty("model_info") + private BotModelInfo modelInfo; +} diff --git a/api/src/main/java/com/coze/openapi/client/bots/model/BotKnowledge.java b/api/src/main/java/com/coze/openapi/client/bots/model/BotKnowledge.java index 1599f786..e50a4977 100644 --- a/api/src/main/java/com/coze/openapi/client/bots/model/BotKnowledge.java +++ b/api/src/main/java/com/coze/openapi/client/bots/model/BotKnowledge.java @@ -1,7 +1,10 @@ +/* (C)2024 */ package com.coze.openapi.client.bots.model; import java.util.List; + import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -12,12 +15,12 @@ @NoArgsConstructor @AllArgsConstructor public class BotKnowledge { - @JsonProperty("dataset_ids") - private List datasetIDs; + @JsonProperty("dataset_ids") + private List datasetIDs; - @JsonProperty("auto_call") - private boolean autoCall; + @JsonProperty("auto_call") + private boolean autoCall; - @JsonProperty("search_strategy") - private int searchStrategy; + @JsonProperty("search_strategy") + private int searchStrategy; } diff --git a/api/src/main/java/com/coze/openapi/client/bots/model/BotMode.java b/api/src/main/java/com/coze/openapi/client/bots/model/BotMode.java index 8e1818ec..56321af0 100644 --- a/api/src/main/java/com/coze/openapi/client/bots/model/BotMode.java +++ b/api/src/main/java/com/coze/openapi/client/bots/model/BotMode.java @@ -1,31 +1,32 @@ +/* (C)2024 */ package com.coze.openapi.client.bots.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; public enum BotMode { - SINGLE_AGENT(0), - MULTI_AGENT(1), - SINGLE_AGENT_WORKFLOW(2); + SINGLE_AGENT(0), + MULTI_AGENT(1), + SINGLE_AGENT_WORKFLOW(2); - private final int value; + private final int value; - BotMode(int value) { - this.value = value; - } + BotMode(int value) { + this.value = value; + } - @JsonValue - public int getValue() { - return value; - } + @JsonValue + public int getValue() { + return value; + } - @JsonCreator - public static BotMode fromValue(int value) { - for (BotMode mode : BotMode.values()) { - if (mode.value == value) { - return mode; - } - } - throw new IllegalArgumentException("Unknown BotMode value: " + value); + @JsonCreator + public static BotMode fromValue(int value) { + for (BotMode mode : BotMode.values()) { + if (mode.value == value) { + return mode; + } } -} \ No newline at end of file + throw new IllegalArgumentException("Unknown BotMode value: " + value); + } +} diff --git a/api/src/main/java/com/coze/openapi/client/bots/model/BotModelInfo.java b/api/src/main/java/com/coze/openapi/client/bots/model/BotModelInfo.java index 86efea81..9ec8ba65 100644 --- a/api/src/main/java/com/coze/openapi/client/bots/model/BotModelInfo.java +++ b/api/src/main/java/com/coze/openapi/client/bots/model/BotModelInfo.java @@ -1,19 +1,21 @@ +/* (C)2024 */ package com.coze.openapi.client.bots.model; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; -@Data +@Data @Builder @NoArgsConstructor @AllArgsConstructor public class BotModelInfo { - @JsonProperty("model_id") - private String modelID; + @JsonProperty("model_id") + private String modelID; - @JsonProperty("model_name") - private String modelName; -} \ No newline at end of file + @JsonProperty("model_name") + private String modelName; +} diff --git a/api/src/main/java/com/coze/openapi/client/bots/model/BotOnboardingInfo.java b/api/src/main/java/com/coze/openapi/client/bots/model/BotOnboardingInfo.java index 1635ef13..b517f352 100644 --- a/api/src/main/java/com/coze/openapi/client/bots/model/BotOnboardingInfo.java +++ b/api/src/main/java/com/coze/openapi/client/bots/model/BotOnboardingInfo.java @@ -1,20 +1,23 @@ +/* (C)2024 */ package com.coze.openapi.client.bots.model; +import java.util.List; + import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; -import java.util.List; -@Data +@Data @Builder @NoArgsConstructor @AllArgsConstructor public class BotOnboardingInfo { - @JsonProperty("prologue") - private String prologue; + @JsonProperty("prologue") + private String prologue; - @JsonProperty("suggested_questions") - private List suggestedQuestions; -} \ No newline at end of file + @JsonProperty("suggested_questions") + private List suggestedQuestions; +} diff --git a/api/src/main/java/com/coze/openapi/client/bots/model/BotPluginAPIInfo.java b/api/src/main/java/com/coze/openapi/client/bots/model/BotPluginAPIInfo.java index c0804c8a..11cd99b3 100644 --- a/api/src/main/java/com/coze/openapi/client/bots/model/BotPluginAPIInfo.java +++ b/api/src/main/java/com/coze/openapi/client/bots/model/BotPluginAPIInfo.java @@ -1,22 +1,24 @@ +/* (C)2024 */ package com.coze.openapi.client.bots.model; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; -@Data +@Data @Builder @NoArgsConstructor @AllArgsConstructor public class BotPluginAPIInfo { - @JsonProperty("api_id") - private String apiID; + @JsonProperty("api_id") + private String apiID; - @JsonProperty("name") - private String name; + @JsonProperty("name") + private String name; - @JsonProperty("description") - private String description; -} \ No newline at end of file + @JsonProperty("description") + private String description; +} diff --git a/api/src/main/java/com/coze/openapi/client/bots/model/BotPluginInfo.java b/api/src/main/java/com/coze/openapi/client/bots/model/BotPluginInfo.java index 3b573d41..802f59c4 100644 --- a/api/src/main/java/com/coze/openapi/client/bots/model/BotPluginInfo.java +++ b/api/src/main/java/com/coze/openapi/client/bots/model/BotPluginInfo.java @@ -1,29 +1,32 @@ +/* (C)2024 */ package com.coze.openapi.client.bots.model; +import java.util.List; + import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; -import java.util.List; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class BotPluginInfo { - @JsonProperty("plugin_id") - private String pluginID; + @JsonProperty("plugin_id") + private String pluginID; - @JsonProperty("name") - private String name; + @JsonProperty("name") + private String name; - @JsonProperty("description") - private String description; + @JsonProperty("description") + private String description; - @JsonProperty("icon_url") - private String iconURL; + @JsonProperty("icon_url") + private String iconURL; - @JsonProperty("api_info_list") - private List apiInfoList; -} \ No newline at end of file + @JsonProperty("api_info_list") + private List apiInfoList; +} diff --git a/api/src/main/java/com/coze/openapi/client/bots/model/BotPromptInfo.java b/api/src/main/java/com/coze/openapi/client/bots/model/BotPromptInfo.java index 4edb301d..9be039ce 100644 --- a/api/src/main/java/com/coze/openapi/client/bots/model/BotPromptInfo.java +++ b/api/src/main/java/com/coze/openapi/client/bots/model/BotPromptInfo.java @@ -1,6 +1,8 @@ +/* (C)2024 */ package com.coze.openapi.client.bots.model; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -11,6 +13,6 @@ @NoArgsConstructor @AllArgsConstructor public class BotPromptInfo { - @JsonProperty("prompt") - private String prompt; -} \ No newline at end of file + @JsonProperty("prompt") + private String prompt; +} diff --git a/api/src/main/java/com/coze/openapi/client/bots/model/SimpleBot.java b/api/src/main/java/com/coze/openapi/client/bots/model/SimpleBot.java index d512d068..50f3990e 100644 --- a/api/src/main/java/com/coze/openapi/client/bots/model/SimpleBot.java +++ b/api/src/main/java/com/coze/openapi/client/bots/model/SimpleBot.java @@ -1,6 +1,8 @@ +/* (C)2024 */ package com.coze.openapi.client.bots.model; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -11,18 +13,18 @@ @NoArgsConstructor @AllArgsConstructor public class SimpleBot { - @JsonProperty("bot_id") - private String botID; + @JsonProperty("bot_id") + private String botID; - @JsonProperty("bot_name") - private String botName; + @JsonProperty("bot_name") + private String botName; - @JsonProperty("description") - private String description; + @JsonProperty("description") + private String description; - @JsonProperty("icon_url") - private String iconURL; + @JsonProperty("icon_url") + private String iconURL; - @JsonProperty("publish_time") - private String publishTime; -} \ No newline at end of file + @JsonProperty("publish_time") + private String publishTime; +} diff --git a/api/src/main/java/com/coze/openapi/client/chat/CancelChatReq.java b/api/src/main/java/com/coze/openapi/client/chat/CancelChatReq.java index fa0c9168..747541df 100644 --- a/api/src/main/java/com/coze/openapi/client/chat/CancelChatReq.java +++ b/api/src/main/java/com/coze/openapi/client/chat/CancelChatReq.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.chat; import com.coze.openapi.client.common.BaseReq; @@ -15,31 +16,28 @@ @EqualsAndHashCode(callSuper = true) public class CancelChatReq extends BaseReq { - /* - * The Conversation ID can be viewed in the 'conversation_id' field of the Response when - * initiating a conversation through the Chat API. - * */ - @NonNull - @JsonProperty("conversation_id") - private String conversationID; + /* + * The Conversation ID can be viewed in the 'conversation_id' field of the Response when + * initiating a conversation through the Chat API. + * */ + @NonNull + @JsonProperty("conversation_id") + private String conversationID; - /* - * The Chat ID can be viewed in the 'id' field of the Response when initiating a chat through the - * Chat API. If it is a streaming response, check the 'id' field in the chat event of the Response. - * */ - @NonNull - @JsonProperty("chat_id") - private String chatID; + /* + * The Chat ID can be viewed in the 'id' field of the Response when initiating a chat through the + * Chat API. If it is a streaming response, check the 'id' field in the chat event of the Response. + * */ + @NonNull + @JsonProperty("chat_id") + private String chatID; - private CancelChatReq(String conversationID, String chatID) { - this.conversationID = conversationID; - this.chatID = chatID; - } + private CancelChatReq(String conversationID, String chatID) { + this.conversationID = conversationID; + this.chatID = chatID; + } - public static CancelChatReq of(String conversationID, String chatID) { - return CancelChatReq.builder() - .conversationID(conversationID) - .chatID(chatID) - .build(); - } + public static CancelChatReq of(String conversationID, String chatID) { + return CancelChatReq.builder().conversationID(conversationID).chatID(chatID).build(); + } } diff --git a/api/src/main/java/com/coze/openapi/client/chat/CancelChatResp.java b/api/src/main/java/com/coze/openapi/client/chat/CancelChatResp.java index 890f7e61..ddb95a74 100644 --- a/api/src/main/java/com/coze/openapi/client/chat/CancelChatResp.java +++ b/api/src/main/java/com/coze/openapi/client/chat/CancelChatResp.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.chat; import com.coze.openapi.client.chat.model.Chat; @@ -14,7 +15,6 @@ @NoArgsConstructor @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) -public class CancelChatResp extends BaseResp{ - private Chat chat; - +public class CancelChatResp extends BaseResp { + private Chat chat; } diff --git a/api/src/main/java/com/coze/openapi/client/chat/CreateChatReq.java b/api/src/main/java/com/coze/openapi/client/chat/CreateChatReq.java index ac1fad49..eb1ed04c 100644 --- a/api/src/main/java/com/coze/openapi/client/chat/CreateChatReq.java +++ b/api/src/main/java/com/coze/openapi/client/chat/CreateChatReq.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.chat; import java.util.List; @@ -8,11 +9,11 @@ import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; -import lombok.experimental.SuperBuilder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.NonNull; +import lombok.experimental.SuperBuilder; @Data @SuperBuilder @@ -20,68 +21,67 @@ @AllArgsConstructor @EqualsAndHashCode(callSuper = true) public class CreateChatReq extends BaseReq { - /* - * Indicate which conversation the chat is taking place in. - * */ - @JsonProperty("conversation_id") - private String conversationID; - - /* - * The ID of the bot that the API interacts with. - * */ - @NonNull - @JsonProperty("bot_id") - private String botID; + /* + * Indicate which conversation the chat is taking place in. + * */ + @JsonProperty("conversation_id") + private String conversationID; - /* - * The user who calls the API to chat with the bot. - * */ - @NonNull - @JsonProperty("user_id") - private String userID; + /* + * The ID of the bot that the API interacts with. + * */ + @NonNull + @JsonProperty("bot_id") + private String botID; - /* - * Additional information for the conversation. You can pass the user's query for this - * conversation through this field. The array length is limited to 100, meaning up to 100 messages can be input. - * */ - @JsonProperty("additional_messages") - private List messages; + /* + * The user who calls the API to chat with the bot. + * */ + @NonNull + @JsonProperty("user_id") + private String userID; - /* - * developer can ignore this param - * */ - @JsonProperty("stream") - private Boolean stream; + /* + * Additional information for the conversation. You can pass the user's query for this + * conversation through this field. The array length is limited to 100, meaning up to 100 messages can be input. + * */ + @JsonProperty("additional_messages") + private List messages; - /* - * The customized variable in a key-value pair. - * */ - @JsonProperty("custom_variables") - private Map customVariables; + /* + * developer can ignore this param + * */ + @JsonProperty("stream") + private Boolean stream; - /* - * Whether to automatically save the history of conversation records. - * */ - @JsonProperty("auto_save_history") - private Boolean autoSaveHistory; + /* + * The customized variable in a key-value pair. + * */ + @JsonProperty("custom_variables") + private Map customVariables; - /* - * Additional information, typically used to encapsulate some business-related fields. - * */ - @JsonProperty("meta_data") - private Map metaData; + /* + * Whether to automatically save the history of conversation records. + * */ + @JsonProperty("auto_save_history") + private Boolean autoSaveHistory; - public void enableStream() { - this.stream = true; - } + /* + * Additional information, typically used to encapsulate some business-related fields. + * */ + @JsonProperty("meta_data") + private Map metaData; - public void disableStream() { - this.stream = false; - this.autoSaveHistory = true; - } + public void enableStream() { + this.stream = true; + } - public void clearBeforeReq() { - this.conversationID = null; - } + public void disableStream() { + this.stream = false; + this.autoSaveHistory = true; + } + public void clearBeforeReq() { + this.conversationID = null; + } } diff --git a/api/src/main/java/com/coze/openapi/client/chat/CreateChatResp.java b/api/src/main/java/com/coze/openapi/client/chat/CreateChatResp.java index 7e52c4f4..9107e37c 100644 --- a/api/src/main/java/com/coze/openapi/client/chat/CreateChatResp.java +++ b/api/src/main/java/com/coze/openapi/client/chat/CreateChatResp.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.chat; import com.coze.openapi.client.chat.model.Chat; @@ -12,6 +13,6 @@ @AllArgsConstructor @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) -public class CreateChatResp extends BaseResp{ - private Chat chat; +public class CreateChatResp extends BaseResp { + private Chat chat; } diff --git a/api/src/main/java/com/coze/openapi/client/chat/RetrieveChatReq.java b/api/src/main/java/com/coze/openapi/client/chat/RetrieveChatReq.java index 362884df..f8eb3421 100644 --- a/api/src/main/java/com/coze/openapi/client/chat/RetrieveChatReq.java +++ b/api/src/main/java/com/coze/openapi/client/chat/RetrieveChatReq.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.chat; import com.coze.openapi.client.common.BaseReq; @@ -14,31 +15,28 @@ @NoArgsConstructor @EqualsAndHashCode(callSuper = true) public class RetrieveChatReq extends BaseReq { - /* - * The Conversation ID can be viewed in the 'conversation_id' field of the Response when - * initiating a conversation through the Chat API. - * */ - @NonNull - @JsonProperty("conversation_id") - private String conversationID; + /* + * The Conversation ID can be viewed in the 'conversation_id' field of the Response when + * initiating a conversation through the Chat API. + * */ + @NonNull + @JsonProperty("conversation_id") + private String conversationID; - /* - * The Chat ID can be viewed in the 'id' field of the Response when initiating a chat through the - * Chat API. If it is a streaming response, check the 'id' field in the chat event of the Response. - * */ - @NonNull - @JsonProperty("chat_id") - private String chatID; + /* + * The Chat ID can be viewed in the 'id' field of the Response when initiating a chat through the + * Chat API. If it is a streaming response, check the 'id' field in the chat event of the Response. + * */ + @NonNull + @JsonProperty("chat_id") + private String chatID; - private RetrieveChatReq(String conversationID, String chatID) { - this.conversationID = conversationID; - this.chatID = chatID; - } + private RetrieveChatReq(String conversationID, String chatID) { + this.conversationID = conversationID; + this.chatID = chatID; + } - public static RetrieveChatReq of(String conversationID, String chatID) { - return RetrieveChatReq.builder() - .conversationID(conversationID) - .chatID(chatID) - .build(); - } + public static RetrieveChatReq of(String conversationID, String chatID) { + return RetrieveChatReq.builder().conversationID(conversationID).chatID(chatID).build(); + } } diff --git a/api/src/main/java/com/coze/openapi/client/chat/RetrieveChatResp.java b/api/src/main/java/com/coze/openapi/client/chat/RetrieveChatResp.java index ec28d259..25fadb63 100644 --- a/api/src/main/java/com/coze/openapi/client/chat/RetrieveChatResp.java +++ b/api/src/main/java/com/coze/openapi/client/chat/RetrieveChatResp.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.chat; import com.coze.openapi.client.chat.model.Chat; @@ -12,6 +13,6 @@ @AllArgsConstructor @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) -public class RetrieveChatResp extends BaseResp{ - private Chat chat; +public class RetrieveChatResp extends BaseResp { + private Chat chat; } diff --git a/api/src/main/java/com/coze/openapi/client/chat/SubmitToolOutputsReq.java b/api/src/main/java/com/coze/openapi/client/chat/SubmitToolOutputsReq.java index e4f7b8f0..3583b1db 100644 --- a/api/src/main/java/com/coze/openapi/client/chat/SubmitToolOutputsReq.java +++ b/api/src/main/java/com/coze/openapi/client/chat/SubmitToolOutputsReq.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.chat; import java.util.List; @@ -8,54 +9,54 @@ import lombok.AllArgsConstructor; import lombok.Data; +import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.experimental.SuperBuilder; -import lombok.EqualsAndHashCode; @Data @SuperBuilder @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode(callSuper = true) -public class SubmitToolOutputsReq extends BaseReq{ - - /* - * The Conversation ID can be viewed in the 'conversation_id' field of the Response when - * initiating a conversation through the Chat API. - * */ - @NonNull - @JsonProperty("conversation_id") - private String conversationID; - - /* - * The Chat ID can be viewed in the 'id' field of the Response when initiating a chat through the - * Chat API. If it is a streaming response, check the 'id' field in the chat event of the Response. - * */ - @NonNull - @JsonProperty("chat_id") - private String chatID; - - /* - * The execution result of the tool. For detailed instructions, refer to the ToolOutput Object - * */ - @NonNull - @JsonProperty("tool_outputs") - private List toolOutputs; - - @JsonProperty("stream") - private Boolean stream; - - public void enableStream() { - this.stream = true; - } - - public void disableStream() { - this.stream = false; - } - - public void clearBeforeReq(){ - this.chatID = null; - this.conversationID = null; - } +public class SubmitToolOutputsReq extends BaseReq { + + /* + * The Conversation ID can be viewed in the 'conversation_id' field of the Response when + * initiating a conversation through the Chat API. + * */ + @NonNull + @JsonProperty("conversation_id") + private String conversationID; + + /* + * The Chat ID can be viewed in the 'id' field of the Response when initiating a chat through the + * Chat API. If it is a streaming response, check the 'id' field in the chat event of the Response. + * */ + @NonNull + @JsonProperty("chat_id") + private String chatID; + + /* + * The execution result of the tool. For detailed instructions, refer to the ToolOutput Object + * */ + @NonNull + @JsonProperty("tool_outputs") + private List toolOutputs; + + @JsonProperty("stream") + private Boolean stream; + + public void enableStream() { + this.stream = true; + } + + public void disableStream() { + this.stream = false; + } + + public void clearBeforeReq() { + this.chatID = null; + this.conversationID = null; + } } diff --git a/api/src/main/java/com/coze/openapi/client/chat/SubmitToolOutputsResp.java b/api/src/main/java/com/coze/openapi/client/chat/SubmitToolOutputsResp.java index a534cbe3..4e488cf6 100644 --- a/api/src/main/java/com/coze/openapi/client/chat/SubmitToolOutputsResp.java +++ b/api/src/main/java/com/coze/openapi/client/chat/SubmitToolOutputsResp.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.chat; import com.coze.openapi.client.chat.model.Chat; @@ -12,6 +13,6 @@ @AllArgsConstructor @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) -public class SubmitToolOutputsResp extends BaseResp{ - private Chat chat; +public class SubmitToolOutputsResp extends BaseResp { + private Chat chat; } diff --git a/api/src/main/java/com/coze/openapi/client/chat/message/ListMessageReq.java b/api/src/main/java/com/coze/openapi/client/chat/message/ListMessageReq.java index bf82d029..d3709a85 100644 --- a/api/src/main/java/com/coze/openapi/client/chat/message/ListMessageReq.java +++ b/api/src/main/java/com/coze/openapi/client/chat/message/ListMessageReq.java @@ -1,14 +1,15 @@ +/* (C)2024 */ package com.coze.openapi.client.chat.message; import com.coze.openapi.client.common.BaseReq; import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.experimental.SuperBuilder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.NonNull; +import lombok.experimental.SuperBuilder; @Data @Getter @@ -16,22 +17,20 @@ @NoArgsConstructor @EqualsAndHashCode(callSuper = true) public class ListMessageReq extends BaseReq { - @NonNull - @JsonProperty("conversation_id") - private String conversationID; - @NonNull - @JsonProperty("chat_id") - private String chatID; + @NonNull + @JsonProperty("conversation_id") + private String conversationID; + + @NonNull + @JsonProperty("chat_id") + private String chatID; - private ListMessageReq(String conversationID, String chatID) { - this.conversationID = conversationID; - this.chatID = chatID; - } + private ListMessageReq(String conversationID, String chatID) { + this.conversationID = conversationID; + this.chatID = chatID; + } - public static ListMessageReq of(String conversationID, String chatID) { - return ListMessageReq.builder() - .conversationID(conversationID) - .chatID(chatID) - .build(); - } + public static ListMessageReq of(String conversationID, String chatID) { + return ListMessageReq.builder().conversationID(conversationID).chatID(chatID).build(); + } } diff --git a/api/src/main/java/com/coze/openapi/client/chat/message/ListMessageResp.java b/api/src/main/java/com/coze/openapi/client/chat/message/ListMessageResp.java index 06becd3c..319b1a71 100644 --- a/api/src/main/java/com/coze/openapi/client/chat/message/ListMessageResp.java +++ b/api/src/main/java/com/coze/openapi/client/chat/message/ListMessageResp.java @@ -1,19 +1,20 @@ +/* (C)2024 */ package com.coze.openapi.client.chat.message; +import java.util.List; + import com.coze.openapi.client.common.BaseResp; import com.coze.openapi.client.connversations.message.model.Message; import lombok.*; import lombok.experimental.SuperBuilder; -import java.util.List; - @Data @SuperBuilder @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) -public class ListMessageResp extends BaseResp{ - private List messages; +public class ListMessageResp extends BaseResp { + private List messages; } diff --git a/api/src/main/java/com/coze/openapi/client/chat/model/Chat.java b/api/src/main/java/com/coze/openapi/client/chat/model/Chat.java index 2bb8faa4..02e326ad 100644 --- a/api/src/main/java/com/coze/openapi/client/chat/model/Chat.java +++ b/api/src/main/java/com/coze/openapi/client/chat/model/Chat.java @@ -1,97 +1,84 @@ +/* (C)2024 */ package com.coze.openapi.client.chat.model; +import java.util.Map; + import com.coze.openapi.service.utils.Utils; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; -import java.util.Map; - @Data @Builder @NoArgsConstructor @AllArgsConstructor public class Chat { - /** - * The ID of the chat. - */ - @JsonProperty("id") - private String id; - public String getID(){ - return id; - } - - /** - * The ID of the conversation. - */ - @JsonProperty("conversation_id") - private String conversationID; - - /** - * The ID of the bot. - */ - @JsonProperty("bot_id") - private String botID; - - /** - * Indicates the create time of the chat. The value format is Unix timestamp in seconds. - */ - @JsonProperty("created_at") - private Integer createdAt; - - /** - * Indicates the end time of the chat. The value format is Unix timestamp in seconds. - */ - @JsonProperty("completed_at") - private Integer completedAt; - - /** - * Indicates the failure time of the chat. The value format is Unix timestamp in seconds. - */ - @JsonProperty("failed_at") - private Integer failedAt; - - /** - * Additional information when creating a message, and this additional information will also be returned when retrieving messages. - * Custom key-value pairs should be specified in Map object format, with a length of 16 key-value pairs. The length of the key should be between 1 and 64 characters, and the length of the value should be between 1 and 512 characters. - */ - @JsonProperty("meta_data") - private Map metaData; - - /** - * When the chat encounters an exception, this field returns detailed error information, including: - * Code: The error code. An integer type. 0 indicates success, other values indicate failure. - * Msg: The error message. A string type. - */ - @JsonProperty("last_error") - private ChatError lastError; - - /** - * The running status of the session. The values are: - * created: The session has been created. - * in_progress: The Bot is processing. - * completed: The Bot has finished processing, and the session has ended. - * failed: The session has failed. - * requires_action: The session is interrupted and requires further processing. - */ - @JsonProperty("status") - private ChatStatus status; - - /** - * Details of the information needed for execution. - */ - @JsonProperty("required_action") - private ChatRequiredAction requiredAction; - - /** - * Detailed information about Token consumption. - */ - @JsonProperty("usage") - private ChatUsage usage; - - public static Chat fromJson(String json) { - return Utils.fromJson(json, Chat.class); - } -} \ No newline at end of file + /** The ID of the chat. */ + @JsonProperty("id") + private String id; + + public String getID() { + return id; + } + + /** The ID of the conversation. */ + @JsonProperty("conversation_id") + private String conversationID; + + /** The ID of the bot. */ + @JsonProperty("bot_id") + private String botID; + + /** Indicates the create time of the chat. The value format is Unix timestamp in seconds. */ + @JsonProperty("created_at") + private Integer createdAt; + + /** Indicates the end time of the chat. The value format is Unix timestamp in seconds. */ + @JsonProperty("completed_at") + private Integer completedAt; + + /** Indicates the failure time of the chat. The value format is Unix timestamp in seconds. */ + @JsonProperty("failed_at") + private Integer failedAt; + + /** + * Additional information when creating a message, and this additional information will also be + * returned when retrieving messages. Custom key-value pairs should be specified in Map object + * format, with a length of 16 key-value pairs. The length of the key should be between 1 and 64 + * characters, and the length of the value should be between 1 and 512 characters. + */ + @JsonProperty("meta_data") + private Map metaData; + + /** + * When the chat encounters an exception, this field returns detailed error information, + * including: Code: The error code. An integer type. 0 indicates success, other values indicate + * failure. Msg: The error message. A string type. + */ + @JsonProperty("last_error") + private ChatError lastError; + + /** + * The running status of the session. The values are: created: The session has been created. + * in_progress: The Bot is processing. completed: The Bot has finished processing, and the session + * has ended. failed: The session has failed. requires_action: The session is interrupted and + * requires further processing. + */ + @JsonProperty("status") + private ChatStatus status; + + /** Details of the information needed for execution. */ + @JsonProperty("required_action") + private ChatRequiredAction requiredAction; + + /** Detailed information about Token consumption. */ + @JsonProperty("usage") + private ChatUsage usage; + + public static Chat fromJson(String json) { + return Utils.fromJson(json, Chat.class); + } +} diff --git a/api/src/main/java/com/coze/openapi/client/chat/model/ChatError.java b/api/src/main/java/com/coze/openapi/client/chat/model/ChatError.java index f184cdfa..f324f8a5 100644 --- a/api/src/main/java/com/coze/openapi/client/chat/model/ChatError.java +++ b/api/src/main/java/com/coze/openapi/client/chat/model/ChatError.java @@ -1,6 +1,8 @@ +/* (C)2024 */ package com.coze.openapi.client.chat.model; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -11,15 +13,11 @@ @NoArgsConstructor @AllArgsConstructor public class ChatError { - /** - * The error code. An integer type. 0 indicates success, other values indicate failure. - */ - @JsonProperty("code") - private int code; + /** The error code. An integer type. 0 indicates success, other values indicate failure. */ + @JsonProperty("code") + private int code; - /** - * The error message. A string type. - */ - @JsonProperty("msg") - private String msg; -} \ No newline at end of file + /** The error message. A string type. */ + @JsonProperty("msg") + private String msg; +} diff --git a/api/src/main/java/com/coze/openapi/client/chat/model/ChatEvent.java b/api/src/main/java/com/coze/openapi/client/chat/model/ChatEvent.java index b9fa8e25..2db66818 100644 --- a/api/src/main/java/com/coze/openapi/client/chat/model/ChatEvent.java +++ b/api/src/main/java/com/coze/openapi/client/chat/model/ChatEvent.java @@ -1,73 +1,63 @@ +/* (C)2024 */ package com.coze.openapi.client.chat.model; +import java.util.Map; + +import com.coze.openapi.client.common.BaseResp; +import com.coze.openapi.client.connversations.message.model.Message; +import com.coze.openapi.client.exception.CozeApiExcetion; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.ToString; import lombok.experimental.SuperBuilder; -import java.util.Map; - -import com.coze.openapi.client.common.BaseResp; -import com.coze.openapi.client.connversations.message.model.Message; -import com.coze.openapi.client.exception.CozeApiExcetion; - @Data @SuperBuilder @NoArgsConstructor @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) public class ChatEvent extends BaseResp { - @JsonProperty("event") - private ChatEventType event; - - @JsonProperty("chat") - private Chat chat; + @JsonProperty("event") + private ChatEventType event; - @JsonProperty("message") - private Message message; + @JsonProperty("chat") + private Chat chat; + @JsonProperty("message") + private Message message; - public static ChatEvent parseEvent(Map eventLine, String logID) { - ChatEventType eventType = ChatEventType.fromString(eventLine.get("event")); - String data = eventLine.get("data"); - if (ChatEventType.DONE.equals(eventType)) { - return ChatEvent.builder() - .event(eventType) - .logID(logID) - .build(); - } - if (ChatEventType.ERROR.equals(eventType)) { - throw new CozeApiExcetion(0, data, logID); - } - if (ChatEventType.CONVERSATION_MESSAGE_DELTA.equals(eventType) || - ChatEventType.CONVERSATION_MESSAGE_COMPLETED.equals(eventType) || - ChatEventType.CONVERSATION_AUDIO_DELTA.equals(eventType)) { - return ChatEvent.builder() - .event(eventType) - .message(Message.fromJson(data)) - .logID(logID) - .build(); - } - if (ChatEventType.CONVERSATION_CHAT_CREATED.equals(eventType) || - ChatEventType.CONVERSATION_CHAT_IN_PROGRESS.equals(eventType) || - ChatEventType.CONVERSATION_CHAT_COMPLETED.equals(eventType) || - ChatEventType.CONVERSATION_CHAT_FAILED.equals(eventType) || - ChatEventType.CONVERSATION_CHAT_REQUIRES_ACTION.equals(eventType)) { - return ChatEvent.builder() - .event(eventType) - .chat(Chat.fromJson(data)) - .logID(logID) - .build(); - } - return ChatEvent.builder() - .event(eventType) - .logID(logID) - .build(); + public static ChatEvent parseEvent(Map eventLine, String logID) { + ChatEventType eventType = ChatEventType.fromString(eventLine.get("event")); + String data = eventLine.get("data"); + if (ChatEventType.DONE.equals(eventType)) { + return ChatEvent.builder().event(eventType).logID(logID).build(); } - - public boolean isDone() { - return ChatEventType.DONE.equals(this.event) || ChatEventType.ERROR.equals(this.event); + if (ChatEventType.ERROR.equals(eventType)) { + throw new CozeApiExcetion(0, data, logID); + } + if (ChatEventType.CONVERSATION_MESSAGE_DELTA.equals(eventType) + || ChatEventType.CONVERSATION_MESSAGE_COMPLETED.equals(eventType) + || ChatEventType.CONVERSATION_AUDIO_DELTA.equals(eventType)) { + return ChatEvent.builder() + .event(eventType) + .message(Message.fromJson(data)) + .logID(logID) + .build(); } -} \ No newline at end of file + if (ChatEventType.CONVERSATION_CHAT_CREATED.equals(eventType) + || ChatEventType.CONVERSATION_CHAT_IN_PROGRESS.equals(eventType) + || ChatEventType.CONVERSATION_CHAT_COMPLETED.equals(eventType) + || ChatEventType.CONVERSATION_CHAT_FAILED.equals(eventType) + || ChatEventType.CONVERSATION_CHAT_REQUIRES_ACTION.equals(eventType)) { + return ChatEvent.builder().event(eventType).chat(Chat.fromJson(data)).logID(logID).build(); + } + return ChatEvent.builder().event(eventType).logID(logID).build(); + } + + public boolean isDone() { + return ChatEventType.DONE.equals(this.event) || ChatEventType.ERROR.equals(this.event); + } +} diff --git a/api/src/main/java/com/coze/openapi/client/chat/model/ChatEventType.java b/api/src/main/java/com/coze/openapi/client/chat/model/ChatEventType.java index d82b1b7e..ac2cee4d 100644 --- a/api/src/main/java/com/coze/openapi/client/chat/model/ChatEventType.java +++ b/api/src/main/java/com/coze/openapi/client/chat/model/ChatEventType.java @@ -1,90 +1,81 @@ +/* (C)2024 */ package com.coze.openapi.client.chat.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; + import lombok.Getter; -/** - * Event types for chat. - */ +/** Event types for chat. */ @Getter public class ChatEventType { - /** - * Event for creating a conversation, indicating the start of the conversation. - */ - public static final ChatEventType CONVERSATION_CHAT_CREATED = new ChatEventType("conversation.chat.created"); - - /** - * The server is processing the conversation. - */ - public static final ChatEventType CONVERSATION_CHAT_IN_PROGRESS = new ChatEventType("conversation.chat.in_progress"); - - /** - * Incremental message, usually an incremental message when type=answer. - */ - public static final ChatEventType CONVERSATION_MESSAGE_DELTA = new ChatEventType("conversation.message.delta"); - - /** - * The message has been completely replied to. - */ - public static final ChatEventType CONVERSATION_MESSAGE_COMPLETED = new ChatEventType("conversation.message.completed"); - - /** - * The conversation is completed. - */ - public static final ChatEventType CONVERSATION_CHAT_COMPLETED = new ChatEventType("conversation.chat.completed"); - - /** - * This event is used to mark a failed conversation. - */ - public static final ChatEventType CONVERSATION_CHAT_FAILED = new ChatEventType("conversation.chat.failed"); - - /** - * The conversation is interrupted and requires the user to report the execution results of the tool. - */ - public static final ChatEventType CONVERSATION_CHAT_REQUIRES_ACTION = new ChatEventType("conversation.chat.requires_action"); - - /** - * Audio delta event - */ - public static final ChatEventType CONVERSATION_AUDIO_DELTA = new ChatEventType("conversation.audio.delta"); - - /** - * Error events during the streaming response process. - */ - public static final ChatEventType ERROR = new ChatEventType("error"); - - /** - * The streaming response for this session ended normally. - */ - public static final ChatEventType DONE = new ChatEventType("done"); - - private final String value; - - private ChatEventType(String value) { - this.value = value; - } + /** Event for creating a conversation, indicating the start of the conversation. */ + public static final ChatEventType CONVERSATION_CHAT_CREATED = + new ChatEventType("conversation.chat.created"); - @JsonValue - public String getValue() { - return value; - } + /** The server is processing the conversation. */ + public static final ChatEventType CONVERSATION_CHAT_IN_PROGRESS = + new ChatEventType("conversation.chat.in_progress"); + + /** Incremental message, usually an incremental message when type=answer. */ + public static final ChatEventType CONVERSATION_MESSAGE_DELTA = + new ChatEventType("conversation.message.delta"); + + /** The message has been completely replied to. */ + public static final ChatEventType CONVERSATION_MESSAGE_COMPLETED = + new ChatEventType("conversation.message.completed"); + + /** The conversation is completed. */ + public static final ChatEventType CONVERSATION_CHAT_COMPLETED = + new ChatEventType("conversation.chat.completed"); + + /** This event is used to mark a failed conversation. */ + public static final ChatEventType CONVERSATION_CHAT_FAILED = + new ChatEventType("conversation.chat.failed"); + + /** + * The conversation is interrupted and requires the user to report the execution results of the + * tool. + */ + public static final ChatEventType CONVERSATION_CHAT_REQUIRES_ACTION = + new ChatEventType("conversation.chat.requires_action"); + + /** Audio delta event */ + public static final ChatEventType CONVERSATION_AUDIO_DELTA = + new ChatEventType("conversation.audio.delta"); + + /** Error events during the streaming response process. */ + public static final ChatEventType ERROR = new ChatEventType("error"); + + /** The streaming response for this session ended normally. */ + public static final ChatEventType DONE = new ChatEventType("done"); + + private final String value; + + private ChatEventType(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @JsonCreator + public static ChatEventType fromString(String value) { + ChatEventType[] types = { + CONVERSATION_CHAT_CREATED, CONVERSATION_CHAT_IN_PROGRESS, + CONVERSATION_MESSAGE_DELTA, CONVERSATION_MESSAGE_COMPLETED, + CONVERSATION_CHAT_COMPLETED, CONVERSATION_CHAT_FAILED, + CONVERSATION_CHAT_REQUIRES_ACTION, CONVERSATION_AUDIO_DELTA, + ERROR, DONE + }; - @JsonCreator - public static ChatEventType fromString(String value) { - ChatEventType[] types = { - CONVERSATION_CHAT_CREATED, CONVERSATION_CHAT_IN_PROGRESS, - CONVERSATION_MESSAGE_DELTA, CONVERSATION_MESSAGE_COMPLETED, - CONVERSATION_CHAT_COMPLETED, CONVERSATION_CHAT_FAILED, - CONVERSATION_CHAT_REQUIRES_ACTION, CONVERSATION_AUDIO_DELTA, - ERROR, DONE - }; - - for (ChatEventType type : types) { - if (type.value.equals(value)) { - return type; - } - } - return new ChatEventType(value); + for (ChatEventType type : types) { + if (type.value.equals(value)) { + return type; + } } -} \ No newline at end of file + return new ChatEventType(value); + } +} diff --git a/api/src/main/java/com/coze/openapi/client/chat/model/ChatPoll.java b/api/src/main/java/com/coze/openapi/client/chat/model/ChatPoll.java index bee693f2..400614c4 100644 --- a/api/src/main/java/com/coze/openapi/client/chat/model/ChatPoll.java +++ b/api/src/main/java/com/coze/openapi/client/chat/model/ChatPoll.java @@ -1,21 +1,24 @@ +/* (C)2024 */ package com.coze.openapi.client.chat.model; +import java.util.List; + +import com.coze.openapi.client.connversations.message.model.Message; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; -import java.util.List; -import com.coze.openapi.client.connversations.message.model.Message; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class ChatPoll { - @JsonProperty("chat") - private Chat chat; + @JsonProperty("chat") + private Chat chat; - @JsonProperty("messages") - private List messages; -} \ No newline at end of file + @JsonProperty("messages") + private List messages; +} diff --git a/api/src/main/java/com/coze/openapi/client/chat/model/ChatRequiredAction.java b/api/src/main/java/com/coze/openapi/client/chat/model/ChatRequiredAction.java index ae404c78..e2971127 100644 --- a/api/src/main/java/com/coze/openapi/client/chat/model/ChatRequiredAction.java +++ b/api/src/main/java/com/coze/openapi/client/chat/model/ChatRequiredAction.java @@ -1,6 +1,8 @@ +/* (C)2024 */ package com.coze.openapi.client.chat.model; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -11,16 +13,14 @@ @NoArgsConstructor @AllArgsConstructor public class ChatRequiredAction { - /** - * The type of additional operation, with the enum value of submit_tool_outputs. - */ - @JsonProperty("type") - private ChatRequiredActionType type; + /** The type of additional operation, with the enum value of submit_tool_outputs. */ + @JsonProperty("type") + private ChatRequiredActionType type; - /** - * Details of the results that need to be submitted, uploaded through the submission API, and - * the chat can continue afterward. - */ - @JsonProperty("submit_tool_outputs") - private ChatSubmitToolOutputs submitToolOutputs; -} \ No newline at end of file + /** + * Details of the results that need to be submitted, uploaded through the submission API, and the + * chat can continue afterward. + */ + @JsonProperty("submit_tool_outputs") + private ChatSubmitToolOutputs submitToolOutputs; +} diff --git a/api/src/main/java/com/coze/openapi/client/chat/model/ChatRequiredActionType.java b/api/src/main/java/com/coze/openapi/client/chat/model/ChatRequiredActionType.java index 88e544b5..6b174774 100644 --- a/api/src/main/java/com/coze/openapi/client/chat/model/ChatRequiredActionType.java +++ b/api/src/main/java/com/coze/openapi/client/chat/model/ChatRequiredActionType.java @@ -1,29 +1,32 @@ +/* (C)2024 */ package com.coze.openapi.client.chat.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; + import lombok.Getter; @Getter public class ChatRequiredActionType { - public static final ChatRequiredActionType SUBMIT_TOOL_OUTPUTS = new ChatRequiredActionType("submit_tool_outputs"); + public static final ChatRequiredActionType SUBMIT_TOOL_OUTPUTS = + new ChatRequiredActionType("submit_tool_outputs"); - private final String value; + private final String value; - private ChatRequiredActionType(String value) { - this.value = value; - } + private ChatRequiredActionType(String value) { + this.value = value; + } - @JsonValue - public String getValue() { - return value; - } + @JsonValue + public String getValue() { + return value; + } - @JsonCreator - public static ChatRequiredActionType fromString(String value) { - if (SUBMIT_TOOL_OUTPUTS.value.equals(value)) { - return SUBMIT_TOOL_OUTPUTS; - } - return new ChatRequiredActionType(value); + @JsonCreator + public static ChatRequiredActionType fromString(String value) { + if (SUBMIT_TOOL_OUTPUTS.value.equals(value)) { + return SUBMIT_TOOL_OUTPUTS; } -} \ No newline at end of file + return new ChatRequiredActionType(value); + } +} diff --git a/api/src/main/java/com/coze/openapi/client/chat/model/ChatStatus.java b/api/src/main/java/com/coze/openapi/client/chat/model/ChatStatus.java index 4cdf8e46..38c5d9bb 100644 --- a/api/src/main/java/com/coze/openapi/client/chat/model/ChatStatus.java +++ b/api/src/main/java/com/coze/openapi/client/chat/model/ChatStatus.java @@ -1,60 +1,47 @@ +/* (C)2024 */ package com.coze.openapi.client.chat.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -/** - * The running status of the session. - */ +/** The running status of the session. */ public enum ChatStatus { - /** - * The session has been created. - */ - CREATED("created"), - - /** - * The Bot is processing. - */ - IN_PROGRESS("in_progress"), - - /** - * The Bot has finished processing, and the session has ended. - */ - COMPLETED("completed"), - - /** - * The session has failed. - */ - FAILED("failed"), - - /** - * The session is interrupted and requires further processing. - */ - REQUIRES_ACTION("requires_action"), - - /** - * The session is user cancelled chat. - */ - CANCELLED("canceled"); - - private final String value; - - ChatStatus(String value) { - this.value = value; - } + /** The session has been created. */ + CREATED("created"), - @JsonValue - public String getValue() { - return value; - } + /** The Bot is processing. */ + IN_PROGRESS("in_progress"), + + /** The Bot has finished processing, and the session has ended. */ + COMPLETED("completed"), + + /** The session has failed. */ + FAILED("failed"), + + /** The session is interrupted and requires further processing. */ + REQUIRES_ACTION("requires_action"), + + /** The session is user cancelled chat. */ + CANCELLED("canceled"); + + private final String value; + + ChatStatus(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } - @JsonCreator - public static ChatStatus fromString(String value) { - for (ChatStatus status : ChatStatus.values()) { - if (status.value.equals(value)) { - return status; - } - } - throw new IllegalArgumentException("Unknown ChatStatus: " + value); + @JsonCreator + public static ChatStatus fromString(String value) { + for (ChatStatus status : ChatStatus.values()) { + if (status.value.equals(value)) { + return status; + } } -} \ No newline at end of file + throw new IllegalArgumentException("Unknown ChatStatus: " + value); + } +} diff --git a/api/src/main/java/com/coze/openapi/client/chat/model/ChatSubmitToolOutputs.java b/api/src/main/java/com/coze/openapi/client/chat/model/ChatSubmitToolOutputs.java index fdbe9245..bdd44d97 100644 --- a/api/src/main/java/com/coze/openapi/client/chat/model/ChatSubmitToolOutputs.java +++ b/api/src/main/java/com/coze/openapi/client/chat/model/ChatSubmitToolOutputs.java @@ -1,21 +1,21 @@ +/* (C)2024 */ package com.coze.openapi.client.chat.model; +import java.util.List; + import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; -import java.util.List; - @Data @Builder @NoArgsConstructor @AllArgsConstructor public class ChatSubmitToolOutputs { - /** - * Details of the specific reported information. - */ - @JsonProperty("tool_calls") - private List toolCalls; -} \ No newline at end of file + /** Details of the specific reported information. */ + @JsonProperty("tool_calls") + private List toolCalls; +} diff --git a/api/src/main/java/com/coze/openapi/client/chat/model/ChatToolCall.java b/api/src/main/java/com/coze/openapi/client/chat/model/ChatToolCall.java index 6f206898..54ea7e4b 100644 --- a/api/src/main/java/com/coze/openapi/client/chat/model/ChatToolCall.java +++ b/api/src/main/java/com/coze/openapi/client/chat/model/ChatToolCall.java @@ -1,6 +1,8 @@ +/* (C)2024 */ package com.coze.openapi.client.chat.model; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -11,25 +13,19 @@ @NoArgsConstructor @AllArgsConstructor public class ChatToolCall { - /** - * The ID for reporting the running results. - */ - @JsonProperty("id") - private String id; - public String getID(){ - return id; - } + /** The ID for reporting the running results. */ + @JsonProperty("id") + private String id; + public String getID() { + return id; + } - /** - * The type of tool, with the enum value of function. - */ - @JsonProperty("type") - private ChatToolCallType type; + /** The type of tool, with the enum value of function. */ + @JsonProperty("type") + private ChatToolCallType type; - /** - * The definition of the execution method function. - */ - @JsonProperty("function") - private ChatToolCallFunction function; -} \ No newline at end of file + /** The definition of the execution method function. */ + @JsonProperty("function") + private ChatToolCallFunction function; +} diff --git a/api/src/main/java/com/coze/openapi/client/chat/model/ChatToolCallFunction.java b/api/src/main/java/com/coze/openapi/client/chat/model/ChatToolCallFunction.java index 113be295..5358c7f7 100644 --- a/api/src/main/java/com/coze/openapi/client/chat/model/ChatToolCallFunction.java +++ b/api/src/main/java/com/coze/openapi/client/chat/model/ChatToolCallFunction.java @@ -1,6 +1,8 @@ +/* (C)2024 */ package com.coze.openapi.client.chat.model; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -11,15 +13,11 @@ @NoArgsConstructor @AllArgsConstructor public class ChatToolCallFunction { - /** - * The name of the method. - */ - @JsonProperty("name") - private String name; + /** The name of the method. */ + @JsonProperty("name") + private String name; - /** - * The parameters of the method. - */ - @JsonProperty("arguments") - private String arguments; -} \ No newline at end of file + /** The parameters of the method. */ + @JsonProperty("arguments") + private String arguments; +} diff --git a/api/src/main/java/com/coze/openapi/client/chat/model/ChatToolCallType.java b/api/src/main/java/com/coze/openapi/client/chat/model/ChatToolCallType.java index 0b62a1a0..c0563d44 100644 --- a/api/src/main/java/com/coze/openapi/client/chat/model/ChatToolCallType.java +++ b/api/src/main/java/com/coze/openapi/client/chat/model/ChatToolCallType.java @@ -1,29 +1,31 @@ +/* (C)2024 */ package com.coze.openapi.client.chat.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; + import lombok.Getter; @Getter public class ChatToolCallType { - public static final ChatToolCallType FUNCTION = new ChatToolCallType("function"); + public static final ChatToolCallType FUNCTION = new ChatToolCallType("function"); - private final String value; + private final String value; - private ChatToolCallType(String value) { - this.value = value; - } + private ChatToolCallType(String value) { + this.value = value; + } - @JsonValue - public String getValue() { - return value; - } + @JsonValue + public String getValue() { + return value; + } - @JsonCreator - public static ChatToolCallType fromString(String value) { - if (FUNCTION.value.equals(value)) { - return FUNCTION; - } - throw new IllegalArgumentException("Unknown ChatToolCallType: " + value); + @JsonCreator + public static ChatToolCallType fromString(String value) { + if (FUNCTION.value.equals(value)) { + return FUNCTION; } -} \ No newline at end of file + throw new IllegalArgumentException("Unknown ChatToolCallType: " + value); + } +} diff --git a/api/src/main/java/com/coze/openapi/client/chat/model/ChatUsage.java b/api/src/main/java/com/coze/openapi/client/chat/model/ChatUsage.java index 2aceeb68..6a05d2c6 100644 --- a/api/src/main/java/com/coze/openapi/client/chat/model/ChatUsage.java +++ b/api/src/main/java/com/coze/openapi/client/chat/model/ChatUsage.java @@ -1,6 +1,8 @@ +/* (C)2024 */ package com.coze.openapi.client.chat.model; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -11,22 +13,18 @@ @NoArgsConstructor @AllArgsConstructor public class ChatUsage { - /** - * The total number of Tokens consumed in this chat, including the consumption for both the input - * and output parts. - */ - @JsonProperty("token_count") - private int tokenCount; + /** + * The total number of Tokens consumed in this chat, including the consumption for both the input + * and output parts. + */ + @JsonProperty("token_count") + private int tokenCount; - /** - * The total number of Tokens consumed for the output part. - */ - @JsonProperty("output_count") - private int outputCount; + /** The total number of Tokens consumed for the output part. */ + @JsonProperty("output_count") + private int outputCount; - /** - * The total number of Tokens consumed for the input part. - */ - @JsonProperty("input_count") - private int inputCount; -} \ No newline at end of file + /** The total number of Tokens consumed for the input part. */ + @JsonProperty("input_count") + private int inputCount; +} diff --git a/api/src/main/java/com/coze/openapi/client/chat/model/ToolOutput.java b/api/src/main/java/com/coze/openapi/client/chat/model/ToolOutput.java index 21784914..b74331eb 100644 --- a/api/src/main/java/com/coze/openapi/client/chat/model/ToolOutput.java +++ b/api/src/main/java/com/coze/openapi/client/chat/model/ToolOutput.java @@ -1,6 +1,8 @@ +/* (C)2024 */ package com.coze.openapi.client.chat.model; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -12,21 +14,20 @@ @NoArgsConstructor @AllArgsConstructor public class ToolOutput { - /** - * The ID for reporting the running results. You can get this ID under the tool_calls field in response of the Chat API. - */ - @NonNull - @JsonProperty("tool_call_id") - private String toolCallID; + /** + * The ID for reporting the running results. You can get this ID under the tool_calls field in + * response of the Chat API. + */ + @NonNull + @JsonProperty("tool_call_id") + private String toolCallID; - /** - * The execution result of the tool. - */ - @NonNull - @JsonProperty("output") - private String output; + /** The execution result of the tool. */ + @NonNull + @JsonProperty("output") + private String output; - public static ToolOutput of(String toolCallID, String output){ - return ToolOutput.builder().toolCallID(toolCallID).output(output).build(); - } + public static ToolOutput of(String toolCallID, String output) { + return ToolOutput.builder().toolCallID(toolCallID).output(output).build(); + } } diff --git a/api/src/main/java/com/coze/openapi/client/common/BaseReq.java b/api/src/main/java/com/coze/openapi/client/common/BaseReq.java index 9860f9eb..cf62a06f 100644 --- a/api/src/main/java/com/coze/openapi/client/common/BaseReq.java +++ b/api/src/main/java/com/coze/openapi/client/common/BaseReq.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.common; import com.fasterxml.jackson.annotation.JsonIgnore; @@ -10,10 +11,7 @@ @SuperBuilder @NoArgsConstructor public class BaseReq { - @JsonIgnore - private Integer connectTimeout; - @JsonIgnore - private Integer readTimeout; - @JsonIgnore - private Integer writeTimeout; + @JsonIgnore private Integer connectTimeout; + @JsonIgnore private Integer readTimeout; + @JsonIgnore private Integer writeTimeout; } diff --git a/api/src/main/java/com/coze/openapi/client/common/BaseResp.java b/api/src/main/java/com/coze/openapi/client/common/BaseResp.java index 4a9f685b..2e6f394b 100644 --- a/api/src/main/java/com/coze/openapi/client/common/BaseResp.java +++ b/api/src/main/java/com/coze/openapi/client/common/BaseResp.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.common; import lombok.Data; @@ -8,5 +9,5 @@ @SuperBuilder @NoArgsConstructor public abstract class BaseResp { - private String logID; + private String logID; } diff --git a/api/src/main/java/com/coze/openapi/client/common/BaseResponse.java b/api/src/main/java/com/coze/openapi/client/common/BaseResponse.java index 1eed813c..1fb4676c 100644 --- a/api/src/main/java/com/coze/openapi/client/common/BaseResponse.java +++ b/api/src/main/java/com/coze/openapi/client/common/BaseResponse.java @@ -1,7 +1,9 @@ +/* (C)2024 */ package com.coze.openapi.client.common; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.*; import lombok.experimental.SuperBuilder; @@ -14,24 +16,24 @@ @JsonInclude(JsonInclude.Include.NON_NULL) @ToString(callSuper = true) public class BaseResponse extends BaseResp { - @JsonProperty("msg") - private String msg; + @JsonProperty("msg") + private String msg; - @JsonProperty("code") - private Integer code; + @JsonProperty("code") + private Integer code; - @JsonProperty("data") - private T data; + @JsonProperty("data") + private T data; - @JsonProperty("detail") - private Detail detail; + @JsonProperty("detail") + private Detail detail; - @Data - @Builder - @NoArgsConstructor - @AllArgsConstructor - public static class Detail { - @JsonProperty("logid") - private String logID; - } + @Data + @Builder + @NoArgsConstructor + @AllArgsConstructor + public static class Detail { + @JsonProperty("logid") + private String logID; + } } diff --git a/api/src/main/java/com/coze/openapi/client/common/FileResponse.java b/api/src/main/java/com/coze/openapi/client/common/FileResponse.java index acba130e..c3b5dc0e 100644 --- a/api/src/main/java/com/coze/openapi/client/common/FileResponse.java +++ b/api/src/main/java/com/coze/openapi/client/common/FileResponse.java @@ -1,39 +1,38 @@ +/* (C)2024 */ package com.coze.openapi.client.common; -import lombok.Data; -import lombok.ToString; -import okhttp3.ResponseBody; - import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; +import lombok.Data; import lombok.EqualsAndHashCode; +import lombok.ToString; import lombok.experimental.SuperBuilder; +import okhttp3.ResponseBody; @Data @SuperBuilder @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) public class FileResponse extends BaseResp { - private final ResponseBody response; - - public FileResponse(ResponseBody response) { - this.response = response; - } + private final ResponseBody response; + public FileResponse(ResponseBody response) { + this.response = response; + } - public void writeToFile(String filePath) throws IOException { - File file = new File(filePath); - try (InputStream inputStream = response.byteStream(); - FileOutputStream outputStream = new FileOutputStream(file)) { - byte[] buffer = new byte[4096]; - int bytesRead; - while ((bytesRead = inputStream.read(buffer)) != -1) { - outputStream.write(buffer, 0, bytesRead); - } - outputStream.flush(); - } + public void writeToFile(String filePath) throws IOException { + File file = new File(filePath); + try (InputStream inputStream = response.byteStream(); + FileOutputStream outputStream = new FileOutputStream(file)) { + byte[] buffer = new byte[4096]; + int bytesRead; + while ((bytesRead = inputStream.read(buffer)) != -1) { + outputStream.write(buffer, 0, bytesRead); + } + outputStream.flush(); } + } } diff --git a/api/src/main/java/com/coze/openapi/client/common/Sort.java b/api/src/main/java/com/coze/openapi/client/common/Sort.java index d1a23282..fcf60f44 100644 --- a/api/src/main/java/com/coze/openapi/client/common/Sort.java +++ b/api/src/main/java/com/coze/openapi/client/common/Sort.java @@ -1,20 +1,21 @@ +/* (C)2024 */ package com.coze.openapi.client.common; import com.fasterxml.jackson.annotation.JsonValue; public enum Sort { - DESC("desc"), - // Indicates that the content of the message is sent by the user. - ASC("asc"); + DESC("desc"), + // Indicates that the content of the message is sent by the user. + ASC("asc"); - private final String value; + private final String value; - Sort(String value) { - this.value = value; - } + Sort(String value) { + this.value = value; + } - @JsonValue - public String getValue() { - return value; - } + @JsonValue + public String getValue() { + return value; + } } diff --git a/api/src/main/java/com/coze/openapi/client/common/pagination/PageFetcher.java b/api/src/main/java/com/coze/openapi/client/common/pagination/PageFetcher.java index 40f68a6b..04ac1810 100644 --- a/api/src/main/java/com/coze/openapi/client/common/pagination/PageFetcher.java +++ b/api/src/main/java/com/coze/openapi/client/common/pagination/PageFetcher.java @@ -1,7 +1,7 @@ +/* (C)2024 */ package com.coze.openapi.client.common.pagination; - @FunctionalInterface public interface PageFetcher { - PageResponse fetch(PageRequest request); -} \ No newline at end of file + PageResponse fetch(PageRequest request); +} diff --git a/api/src/main/java/com/coze/openapi/client/common/pagination/PageNumBasedPaginator.java b/api/src/main/java/com/coze/openapi/client/common/pagination/PageNumBasedPaginator.java index e9a9e933..d83e04d7 100644 --- a/api/src/main/java/com/coze/openapi/client/common/pagination/PageNumBasedPaginator.java +++ b/api/src/main/java/com/coze/openapi/client/common/pagination/PageNumBasedPaginator.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.common.pagination; import java.util.Iterator; @@ -7,54 +8,52 @@ import com.coze.openapi.service.service.common.CozeLoggerFactory; - public class PageNumBasedPaginator implements Iterator { - private final PageFetcher pageFetcher; - private final int pageSize; - private static final Logger logger = CozeLoggerFactory.getLogger(); - private Iterator currentIterator; - private PageResponse currentPage; - private int currentPageNum = 1; - - public PageNumBasedPaginator(PageFetcher pageFetcher, int pageSize) { - this.pageFetcher = pageFetcher; - this.pageSize = pageSize; - this.fetchNextPage(); + private final PageFetcher pageFetcher; + private final int pageSize; + private static final Logger logger = CozeLoggerFactory.getLogger(); + private Iterator currentIterator; + private PageResponse currentPage; + private int currentPageNum = 1; + + public PageNumBasedPaginator(PageFetcher pageFetcher, int pageSize) { + this.pageFetcher = pageFetcher; + this.pageSize = pageSize; + this.fetchNextPage(); + } + + private void fetchNextPage() { + try { + PageRequest request = + PageRequest.builder().pageNum(currentPageNum).pageSize(pageSize).build(); + currentPage = pageFetcher.fetch(request); + logger.info( + "Fetched page: {} success, got{} items", currentPageNum, currentPage.getData().size()); + currentIterator = currentPage.getData().iterator(); + currentPageNum++; + } catch (Exception e) { + throw new RuntimeException("Failed to fetch page", e); } + } - private void fetchNextPage() { - try { - PageRequest request = PageRequest.builder() - .pageNum(currentPageNum) - .pageSize(pageSize) - .build(); - currentPage = pageFetcher.fetch(request); - logger.info("Fetched page: {} success, got{} items", currentPageNum, currentPage.getData().size()); - currentIterator = currentPage.getData().iterator(); - currentPageNum++; - } catch (Exception e) { - throw new RuntimeException("Failed to fetch page", e); - } + @Override + public boolean hasNext() { + if (currentIterator.hasNext()) { + return true; } - - @Override - public boolean hasNext() { - if (currentIterator.hasNext()) { - return true; - } - if (currentPage.isHasMore()) { - logger.info("Fetching next page: {}", currentPageNum); - fetchNextPage(); - return currentIterator.hasNext(); - } - return false; + if (currentPage.isHasMore()) { + logger.info("Fetching next page: {}", currentPageNum); + fetchNextPage(); + return currentIterator.hasNext(); } + return false; + } - @Override - public T next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } - return currentIterator.next(); + @Override + public T next() { + if (!hasNext()) { + throw new NoSuchElementException(); } -} \ No newline at end of file + return currentIterator.next(); + } +} diff --git a/api/src/main/java/com/coze/openapi/client/common/pagination/PageRequest.java b/api/src/main/java/com/coze/openapi/client/common/pagination/PageRequest.java index 169a43ab..a6e9c140 100644 --- a/api/src/main/java/com/coze/openapi/client/common/pagination/PageRequest.java +++ b/api/src/main/java/com/coze/openapi/client/common/pagination/PageRequest.java @@ -1,24 +1,25 @@ +/* (C)2024 */ package com.coze.openapi.client.common.pagination; +import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; -import com.fasterxml.jackson.annotation.JsonProperty; - @Data @Builder @NoArgsConstructor @AllArgsConstructor public class PageRequest { - - @JsonProperty("page_token") - private String pageToken; - @JsonProperty("page_num") - private Integer pageNum; - - @JsonProperty("page_size") - private Integer pageSize; -} \ No newline at end of file + @JsonProperty("page_token") + private String pageToken; + + @JsonProperty("page_num") + private Integer pageNum; + + @JsonProperty("page_size") + private Integer pageSize; +} diff --git a/api/src/main/java/com/coze/openapi/client/common/pagination/PageResp.java b/api/src/main/java/com/coze/openapi/client/common/pagination/PageResp.java index 675ca50c..f4a11397 100644 --- a/api/src/main/java/com/coze/openapi/client/common/pagination/PageResp.java +++ b/api/src/main/java/com/coze/openapi/client/common/pagination/PageResp.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.common.pagination; import java.util.Iterator; @@ -13,11 +14,10 @@ @NoArgsConstructor @AllArgsConstructor public class PageResp { - private Integer total; - private List items; - private Iterator iterator; - private Boolean hasMore; - private String lastID; - private String logID; + private Integer total; + private List items; + private Iterator iterator; + private Boolean hasMore; + private String lastID; + private String logID; } - \ No newline at end of file diff --git a/api/src/main/java/com/coze/openapi/client/common/pagination/PageResponse.java b/api/src/main/java/com/coze/openapi/client/common/pagination/PageResponse.java index 7a70b5f3..0aa13c47 100644 --- a/api/src/main/java/com/coze/openapi/client/common/pagination/PageResponse.java +++ b/api/src/main/java/com/coze/openapi/client/common/pagination/PageResponse.java @@ -1,9 +1,8 @@ +/* (C)2024 */ package com.coze.openapi.client.common.pagination; import java.util.List; -import com.fasterxml.jackson.annotation.JsonProperty; - import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -14,19 +13,19 @@ @AllArgsConstructor @NoArgsConstructor public class PageResponse { - private boolean hasMore; - - private Integer pageNum; - - private Integer pageSize; - - private Integer total; - - private List data; + private boolean hasMore; + + private Integer pageNum; + + private Integer pageSize; + + private Integer total; + + private List data; - private String lastID; + private String lastID; - private String nextID; + private String nextID; - private String logID; + private String logID; } diff --git a/api/src/main/java/com/coze/openapi/client/common/pagination/TokenBasedPaginator.java b/api/src/main/java/com/coze/openapi/client/common/pagination/TokenBasedPaginator.java index 88d21d6a..621b2907 100644 --- a/api/src/main/java/com/coze/openapi/client/common/pagination/TokenBasedPaginator.java +++ b/api/src/main/java/com/coze/openapi/client/common/pagination/TokenBasedPaginator.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.common.pagination; import java.util.Iterator; @@ -7,53 +8,50 @@ import com.coze.openapi.service.service.common.CozeLoggerFactory; - public class TokenBasedPaginator implements Iterator { - private final PageFetcher pageFetcher; - private static final Logger logger = CozeLoggerFactory.getLogger(); - private final int pageSize; - private Iterator currentIterator; - private PageResponse currentPage; - private String pageToken; - - public TokenBasedPaginator(PageFetcher pageFetcher, int pageSize) { - this.pageFetcher = pageFetcher; - this.pageSize = pageSize; - this.fetchNextPage(); + private final PageFetcher pageFetcher; + private static final Logger logger = CozeLoggerFactory.getLogger(); + private final int pageSize; + private Iterator currentIterator; + private PageResponse currentPage; + private String pageToken; + + public TokenBasedPaginator(PageFetcher pageFetcher, int pageSize) { + this.pageFetcher = pageFetcher; + this.pageSize = pageSize; + this.fetchNextPage(); + } + + private void fetchNextPage() { + try { + PageRequest request = PageRequest.builder().pageToken(pageToken).pageSize(pageSize).build(); + currentPage = pageFetcher.fetch(request); + logger.info( + "Fetched page: " + pageToken + " success, got" + currentPage.getData().size() + " items"); + currentIterator = currentPage.getData().iterator(); + pageToken = currentPage.getNextID(); + } catch (Exception e) { + throw new RuntimeException("Failed to fetch page", e); } + } - private void fetchNextPage() { - try { - PageRequest request = PageRequest.builder() - .pageToken(pageToken) - .pageSize(pageSize) - .build(); - currentPage = pageFetcher.fetch(request); - logger.info("Fetched page: "+ pageToken + " success, got" + currentPage.getData().size() + " items"); - currentIterator = currentPage.getData().iterator(); - pageToken = currentPage.getNextID(); - } catch (Exception e) { - throw new RuntimeException("Failed to fetch page", e); - } + @Override + public boolean hasNext() { + if (currentIterator.hasNext()) { + return true; } - - @Override - public boolean hasNext() { - if (currentIterator.hasNext()) { - return true; - } - if (currentPage.isHasMore() && pageToken != null) { - fetchNextPage(); - return currentIterator.hasNext(); - } - return false; + if (currentPage.isHasMore() && pageToken != null) { + fetchNextPage(); + return currentIterator.hasNext(); } + return false; + } - @Override - public T next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } - return currentIterator.next(); + @Override + public T next() { + if (!hasNext()) { + throw new NoSuchElementException(); } -} \ No newline at end of file + return currentIterator.next(); + } +} diff --git a/api/src/main/java/com/coze/openapi/client/connversations/ClearConversationReq.java b/api/src/main/java/com/coze/openapi/client/connversations/ClearConversationReq.java index 13ba2271..8ef199f1 100644 --- a/api/src/main/java/com/coze/openapi/client/connversations/ClearConversationReq.java +++ b/api/src/main/java/com/coze/openapi/client/connversations/ClearConversationReq.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.connversations; import com.coze.openapi.client.common.BaseReq; @@ -16,14 +17,12 @@ @AllArgsConstructor @EqualsAndHashCode(callSuper = true) public class ClearConversationReq extends BaseReq { - /** - * The ID of the conversation. - */ - @NonNull - @JsonProperty("conversation_id") - private String conversationID; + /** The ID of the conversation. */ + @NonNull + @JsonProperty("conversation_id") + private String conversationID; - public static ClearConversationReq of(String conversationID) { - return ClearConversationReq.builder().conversationID(conversationID).build(); - } + public static ClearConversationReq of(String conversationID) { + return ClearConversationReq.builder().conversationID(conversationID).build(); + } } diff --git a/api/src/main/java/com/coze/openapi/client/connversations/ClearConversationResp.java b/api/src/main/java/com/coze/openapi/client/connversations/ClearConversationResp.java index 93609bf8..36a87e9c 100644 --- a/api/src/main/java/com/coze/openapi/client/connversations/ClearConversationResp.java +++ b/api/src/main/java/com/coze/openapi/client/connversations/ClearConversationResp.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.connversations; import com.coze.openapi.client.common.BaseResp; @@ -17,6 +18,6 @@ @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) public class ClearConversationResp extends BaseResp { - @JsonProperty("conversation_id") - private String conversationID; + @JsonProperty("conversation_id") + private String conversationID; } diff --git a/api/src/main/java/com/coze/openapi/client/connversations/CreateConversationReq.java b/api/src/main/java/com/coze/openapi/client/connversations/CreateConversationReq.java index 92dfb77a..80c285e6 100644 --- a/api/src/main/java/com/coze/openapi/client/connversations/CreateConversationReq.java +++ b/api/src/main/java/com/coze/openapi/client/connversations/CreateConversationReq.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.connversations; import java.util.List; @@ -16,27 +17,26 @@ @Data @SuperBuilder @NoArgsConstructor -@AllArgsConstructor +@AllArgsConstructor @EqualsAndHashCode(callSuper = true) public class CreateConversationReq extends BaseReq { - /* - * Messages in the conversation. For more information, see EnterMessage object. - * */ - @JsonProperty("messages") - private List messages; - - /* - * Additional information when creating a message, and this additional information will also be - returned when retrieving messages. - * */ - @JsonProperty("meta_data") - private Map metaData; - - - /* - * Bind and isolate conversation on different bots. - * */ - @JsonProperty("bot_id") - private String botID; + /* + * Messages in the conversation. For more information, see EnterMessage object. + * */ + @JsonProperty("messages") + private List messages; + + /* + * Additional information when creating a message, and this additional information will also be + returned when retrieving messages. + * */ + @JsonProperty("meta_data") + private Map metaData; + + /* + * Bind and isolate conversation on different bots. + * */ + @JsonProperty("bot_id") + private String botID; } diff --git a/api/src/main/java/com/coze/openapi/client/connversations/CreateConversationResp.java b/api/src/main/java/com/coze/openapi/client/connversations/CreateConversationResp.java index e2aa6b71..3e224b97 100644 --- a/api/src/main/java/com/coze/openapi/client/connversations/CreateConversationResp.java +++ b/api/src/main/java/com/coze/openapi/client/connversations/CreateConversationResp.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.connversations; import com.coze.openapi.client.common.BaseResp; @@ -12,7 +13,7 @@ @SuperBuilder @NoArgsConstructor @EqualsAndHashCode(callSuper = true) -public class CreateConversationResp extends BaseResp{ +public class CreateConversationResp extends BaseResp { - private Conversation conversation; + private Conversation conversation; } diff --git a/api/src/main/java/com/coze/openapi/client/connversations/ListConversationReq.java b/api/src/main/java/com/coze/openapi/client/connversations/ListConversationReq.java index b87b979a..02f169e3 100644 --- a/api/src/main/java/com/coze/openapi/client/connversations/ListConversationReq.java +++ b/api/src/main/java/com/coze/openapi/client/connversations/ListConversationReq.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.connversations; import com.coze.openapi.client.common.BaseReq; @@ -17,28 +18,22 @@ @AllArgsConstructor @EqualsAndHashCode(callSuper = true) public class ListConversationReq extends BaseReq { - /** - * The ID of the bot. - */ - @NonNull - @JsonProperty("bot_id") - private String botID; + /** The ID of the bot. */ + @NonNull + @JsonProperty("bot_id") + private String botID; - /** - * The page number. - */ - @Builder.Default - @JsonProperty("page_num") - private Integer pageNum = 1; + /** The page number. */ + @Builder.Default + @JsonProperty("page_num") + private Integer pageNum = 1; - /** - * The page size. - */ - @Builder.Default - @JsonProperty("page_size") - private Integer pageSize = 20; + /** The page size. */ + @Builder.Default + @JsonProperty("page_size") + private Integer pageSize = 20; - public static ListConversationReq of(String botID){ - return ListConversationReq.builder().botID(botID).build(); - } + public static ListConversationReq of(String botID) { + return ListConversationReq.builder().botID(botID).build(); + } } diff --git a/api/src/main/java/com/coze/openapi/client/connversations/ListConversationResp.java b/api/src/main/java/com/coze/openapi/client/connversations/ListConversationResp.java index 23b6474b..5744bc96 100644 --- a/api/src/main/java/com/coze/openapi/client/connversations/ListConversationResp.java +++ b/api/src/main/java/com/coze/openapi/client/connversations/ListConversationResp.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.connversations; import java.util.List; @@ -7,7 +8,6 @@ import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; -import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; @@ -20,10 +20,10 @@ @AllArgsConstructor @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) -public class ListConversationResp extends BaseResp{ - @JsonProperty("has_more") - private boolean hasMore; +public class ListConversationResp extends BaseResp { + @JsonProperty("has_more") + private boolean hasMore; - @JsonProperty("conversations") - private List conversations; + @JsonProperty("conversations") + private List conversations; } diff --git a/api/src/main/java/com/coze/openapi/client/connversations/RetrieveConversationReq.java b/api/src/main/java/com/coze/openapi/client/connversations/RetrieveConversationReq.java index 30cf8fd4..a73f6a20 100644 --- a/api/src/main/java/com/coze/openapi/client/connversations/RetrieveConversationReq.java +++ b/api/src/main/java/com/coze/openapi/client/connversations/RetrieveConversationReq.java @@ -1,30 +1,30 @@ +/* (C)2024 */ package com.coze.openapi.client.connversations; -import lombok.AllArgsConstructor; +import com.coze.openapi.client.common.BaseReq; +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.experimental.SuperBuilder; -import com.coze.openapi.client.common.BaseReq; -import com.fasterxml.jackson.annotation.JsonProperty; - @Data @SuperBuilder @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode(callSuper = true) public class RetrieveConversationReq extends BaseReq { - /* - * The ID of the conversation. - * */ - @NonNull - @JsonProperty("conversation_id") - private String conversationID; + /* + * The ID of the conversation. + * */ + @NonNull + @JsonProperty("conversation_id") + private String conversationID; - public static RetrieveConversationReq of(String conversationID) { - return RetrieveConversationReq.builder().conversationID(conversationID).build(); - } + public static RetrieveConversationReq of(String conversationID) { + return RetrieveConversationReq.builder().conversationID(conversationID).build(); + } } diff --git a/api/src/main/java/com/coze/openapi/client/connversations/RetrieveConversationResp.java b/api/src/main/java/com/coze/openapi/client/connversations/RetrieveConversationResp.java index 54cf00ed..41b4517f 100644 --- a/api/src/main/java/com/coze/openapi/client/connversations/RetrieveConversationResp.java +++ b/api/src/main/java/com/coze/openapi/client/connversations/RetrieveConversationResp.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.connversations; import com.coze.openapi.client.common.BaseResp; @@ -14,7 +15,6 @@ @SuperBuilder @NoArgsConstructor @AllArgsConstructor -public class RetrieveConversationResp extends BaseResp{ - private Conversation conversation; +public class RetrieveConversationResp extends BaseResp { + private Conversation conversation; } - diff --git a/api/src/main/java/com/coze/openapi/client/connversations/message/CreateMessageReq.java b/api/src/main/java/com/coze/openapi/client/connversations/message/CreateMessageReq.java index 54295e1f..55a67277 100644 --- a/api/src/main/java/com/coze/openapi/client/connversations/message/CreateMessageReq.java +++ b/api/src/main/java/com/coze/openapi/client/connversations/message/CreateMessageReq.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.connversations.message; import java.util.List; @@ -22,48 +23,46 @@ @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode(callSuper = true) -public class CreateMessageReq extends BaseReq{ - /* - * The ID of the conversation. - * */ - @NonNull - @JsonProperty("conversation_id") - private String conversationID; +public class CreateMessageReq extends BaseReq { + /* + * The ID of the conversation. + * */ + @NonNull + @JsonProperty("conversation_id") + private String conversationID; - /* - * The entity that sent this message. - * */ - @NonNull - private MessageRole role; + /* + * The entity that sent this message. + * */ + @NonNull private MessageRole role; - /* - * The content of the message, supporting pure text, multimodal (mixed input of text, images, files), - * cards, and various types of content. - * */ - @NonNull - private String content; + /* + * The content of the message, supporting pure text, multimodal (mixed input of text, images, files), + * cards, and various types of content. + * */ + @NonNull private String content; - /* - * The type of message content. - * */ - @NonNull - @JsonProperty("content_type") - private MessageContentType contentType; + /* + * The type of message content. + * */ + @NonNull + @JsonProperty("content_type") + private MessageContentType contentType; - /* - * Additional information when creating a message, and this additional information will also be - * returned when retrieving messages. - * */ - @JsonProperty("meta_data") - private Map metadata; - + /* + * Additional information when creating a message, and this additional information will also be + * returned when retrieving messages. + * */ + @JsonProperty("meta_data") + private Map metadata; - public static abstract class CreateMessageReqBuilder> extends BaseReqBuilder { - public B objectContent(List objects) { - this.content = Utils.toJson(objects); - this.contentType = MessageContentType.OBJECT_STRING; - return self(); - } + public abstract static class CreateMessageReqBuilder< + C extends CreateMessageReq, B extends CreateMessageReqBuilder> + extends BaseReqBuilder { + public B objectContent(List objects) { + this.content = Utils.toJson(objects); + this.contentType = MessageContentType.OBJECT_STRING; + return self(); } - + } } diff --git a/api/src/main/java/com/coze/openapi/client/connversations/message/CreateMessageResp.java b/api/src/main/java/com/coze/openapi/client/connversations/message/CreateMessageResp.java index 06ee959a..47d360e9 100644 --- a/api/src/main/java/com/coze/openapi/client/connversations/message/CreateMessageResp.java +++ b/api/src/main/java/com/coze/openapi/client/connversations/message/CreateMessageResp.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.connversations.message; import com.coze.openapi.client.common.BaseResp; @@ -13,5 +14,5 @@ @EqualsAndHashCode(callSuper = true) @NoArgsConstructor public class CreateMessageResp extends BaseResp { - private Message message; + private Message message; } diff --git a/api/src/main/java/com/coze/openapi/client/connversations/message/DeleteMessageReq.java b/api/src/main/java/com/coze/openapi/client/connversations/message/DeleteMessageReq.java index 3c99a0c3..d8e6f28c 100644 --- a/api/src/main/java/com/coze/openapi/client/connversations/message/DeleteMessageReq.java +++ b/api/src/main/java/com/coze/openapi/client/connversations/message/DeleteMessageReq.java @@ -1,5 +1,9 @@ +/* (C)2024 */ package com.coze.openapi.client.connversations.message; +import com.coze.openapi.client.common.BaseReq; +import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; @@ -7,30 +11,27 @@ import lombok.NonNull; import lombok.experimental.SuperBuilder; -import com.coze.openapi.client.common.BaseReq; -import com.fasterxml.jackson.annotation.JsonProperty; - @Data @SuperBuilder @AllArgsConstructor @NoArgsConstructor @EqualsAndHashCode(callSuper = true) -public class DeleteMessageReq extends BaseReq{ - /* - * The ID of the conversation. - * */ - @NonNull - @JsonProperty("conversation_id") - private String conversationID; +public class DeleteMessageReq extends BaseReq { + /* + * The ID of the conversation. + * */ + @NonNull + @JsonProperty("conversation_id") + private String conversationID; - /* - * message id - * */ - @NonNull - @JsonProperty("message_id") - private String messageID; + /* + * message id + * */ + @NonNull + @JsonProperty("message_id") + private String messageID; - public static DeleteMessageReq of(String conversationID, String messageID) { - return DeleteMessageReq.builder().conversationID(conversationID).messageID(messageID).build(); - } + public static DeleteMessageReq of(String conversationID, String messageID) { + return DeleteMessageReq.builder().conversationID(conversationID).messageID(messageID).build(); + } } diff --git a/api/src/main/java/com/coze/openapi/client/connversations/message/DeleteMessageResp.java b/api/src/main/java/com/coze/openapi/client/connversations/message/DeleteMessageResp.java index 2efae315..8fcda19e 100644 --- a/api/src/main/java/com/coze/openapi/client/connversations/message/DeleteMessageResp.java +++ b/api/src/main/java/com/coze/openapi/client/connversations/message/DeleteMessageResp.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.connversations.message; import com.coze.openapi.client.common.BaseResp; @@ -13,5 +14,5 @@ @EqualsAndHashCode(callSuper = true) @NoArgsConstructor public class DeleteMessageResp extends BaseResp { - private Message message; + private Message message; } diff --git a/api/src/main/java/com/coze/openapi/client/connversations/message/ListMessageReq.java b/api/src/main/java/com/coze/openapi/client/connversations/message/ListMessageReq.java index fe4d0b30..7b0f0387 100644 --- a/api/src/main/java/com/coze/openapi/client/connversations/message/ListMessageReq.java +++ b/api/src/main/java/com/coze/openapi/client/connversations/message/ListMessageReq.java @@ -1,5 +1,10 @@ +/* (C)2024 */ package com.coze.openapi.client.connversations.message; +import com.coze.openapi.client.common.BaseReq; +import com.coze.openapi.client.common.Sort; +import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -8,57 +13,42 @@ import lombok.NonNull; import lombok.experimental.SuperBuilder; -import com.coze.openapi.client.common.BaseReq; -import com.coze.openapi.client.common.Sort; -import com.fasterxml.jackson.annotation.JsonProperty; - @Data @SuperBuilder @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode(callSuper = true) public class ListMessageReq extends BaseReq { - /** - * The ID of the conversation. - */ - @NonNull - @JsonProperty("conversation_id") - private String conversationID; - - /** - * The sorting method for the message list. - */ - @JsonProperty("order") - private String order; - - /** - * The ID of the Chat. - */ - @JsonProperty("chat_id") - private String chatID; - - /** - * Get messages before the specified position. - */ - @JsonProperty("before_id") - private String beforeID; - - /** - * Get messages after the specified position. - */ - @JsonProperty("after_id") - private String afterID; - - /** - * The amount of data returned per query. Default is 50, with a range of 1 to 50. - */ - @JsonProperty("limit") - @Builder.Default - private Integer limit = 20; - @JsonProperty("bot_id") - private String botID; - - @JsonProperty("order") - @Builder.Default - private Sort sort = Sort.DESC; + /** The ID of the conversation. */ + @NonNull + @JsonProperty("conversation_id") + private String conversationID; + + /** The sorting method for the message list. */ + @JsonProperty("order") + private String order; + + /** The ID of the Chat. */ + @JsonProperty("chat_id") + private String chatID; + + /** Get messages before the specified position. */ + @JsonProperty("before_id") + private String beforeID; + + /** Get messages after the specified position. */ + @JsonProperty("after_id") + private String afterID; + + /** The amount of data returned per query. Default is 50, with a range of 1 to 50. */ + @JsonProperty("limit") + @Builder.Default + private Integer limit = 20; + + @JsonProperty("bot_id") + private String botID; + + @JsonProperty("order") + @Builder.Default + private Sort sort = Sort.DESC; } diff --git a/api/src/main/java/com/coze/openapi/client/connversations/message/ListMessageResp.java b/api/src/main/java/com/coze/openapi/client/connversations/message/ListMessageResp.java index 26d1c2c3..c63ef318 100644 --- a/api/src/main/java/com/coze/openapi/client/connversations/message/ListMessageResp.java +++ b/api/src/main/java/com/coze/openapi/client/connversations/message/ListMessageResp.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.connversations.message; import java.util.List; @@ -7,7 +8,6 @@ import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; -import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; @@ -21,10 +21,12 @@ @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) public class ListMessageResp extends BaseResponse> { - @JsonProperty("has_more") - private boolean hasMore; - @JsonProperty("first_id") - private String firstID; - @JsonProperty("last_id") - private String lastID; + @JsonProperty("has_more") + private boolean hasMore; + + @JsonProperty("first_id") + private String firstID; + + @JsonProperty("last_id") + private String lastID; } diff --git a/api/src/main/java/com/coze/openapi/client/connversations/message/RetrieveMessageReq.java b/api/src/main/java/com/coze/openapi/client/connversations/message/RetrieveMessageReq.java index 6de596aa..5ffe3afc 100644 --- a/api/src/main/java/com/coze/openapi/client/connversations/message/RetrieveMessageReq.java +++ b/api/src/main/java/com/coze/openapi/client/connversations/message/RetrieveMessageReq.java @@ -1,5 +1,9 @@ +/* (C)2024 */ package com.coze.openapi.client.connversations.message; +import com.coze.openapi.client.common.BaseReq; +import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; @@ -7,19 +11,17 @@ import lombok.NonNull; import lombok.experimental.SuperBuilder; -import com.coze.openapi.client.common.BaseReq; -import com.fasterxml.jackson.annotation.JsonProperty; - @Data @SuperBuilder @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode(callSuper = true) public class RetrieveMessageReq extends BaseReq { - @NonNull - @JsonProperty("conversation_id") - private String conversationID; - @NonNull - @JsonProperty("message_id") - private String messageID; + @NonNull + @JsonProperty("conversation_id") + private String conversationID; + + @NonNull + @JsonProperty("message_id") + private String messageID; } diff --git a/api/src/main/java/com/coze/openapi/client/connversations/message/RetrieveMessageResp.java b/api/src/main/java/com/coze/openapi/client/connversations/message/RetrieveMessageResp.java index 9ada1364..452bc954 100644 --- a/api/src/main/java/com/coze/openapi/client/connversations/message/RetrieveMessageResp.java +++ b/api/src/main/java/com/coze/openapi/client/connversations/message/RetrieveMessageResp.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.connversations.message; import com.coze.openapi.client.common.BaseResp; @@ -6,7 +7,6 @@ import lombok.*; import lombok.experimental.SuperBuilder; - @Data @SuperBuilder @NoArgsConstructor @@ -14,9 +14,5 @@ @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) public class RetrieveMessageResp extends BaseResp { - private Message message; + private Message message; } - - - - diff --git a/api/src/main/java/com/coze/openapi/client/connversations/message/UpdateMessageReq.java b/api/src/main/java/com/coze/openapi/client/connversations/message/UpdateMessageReq.java index 4bb0c8a9..8ef542ec 100644 --- a/api/src/main/java/com/coze/openapi/client/connversations/message/UpdateMessageReq.java +++ b/api/src/main/java/com/coze/openapi/client/connversations/message/UpdateMessageReq.java @@ -1,59 +1,62 @@ +/* (C)2024 */ package com.coze.openapi.client.connversations.message; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.experimental.SuperBuilder; - import java.util.List; import java.util.Map; +import com.coze.openapi.client.common.BaseReq; import com.coze.openapi.client.connversations.message.model.MessageContentType; import com.coze.openapi.client.connversations.message.model.MessageObjectString; -import com.coze.openapi.client.common.BaseReq; import com.coze.openapi.service.utils.Utils; import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import lombok.experimental.SuperBuilder; + @Data @SuperBuilder @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode(callSuper = true) public class UpdateMessageReq extends BaseReq { - /* - * The ID of the conversation. - * */ - @JsonProperty("conversation_id") - private String conversationID; - - /* - * The ID of the message. - * */ - @JsonProperty("message_id") - private String messageID; - - /* - * The content of the message, supporting pure text, multimodal (mixed input of text, images, files), - * cards, and various types of content. - * */ - @JsonProperty("content") - private String content; - - @JsonProperty("meta_data") - private Map metaData; - - /* - * The type of message content. - * */ - @JsonProperty("content_type") - private MessageContentType contentType; - - public static abstract class UpdateMessageReqBuilder> extends BaseReqBuilder { - public B objectContent(List objects) { - this.content = Utils.toJson(objects); - this.contentType = MessageContentType.OBJECT_STRING; - return self(); - } + /* + * The ID of the conversation. + * */ + @JsonProperty("conversation_id") + private String conversationID; + + /* + * The ID of the message. + * */ + @JsonProperty("message_id") + private String messageID; + + /* + * The content of the message, supporting pure text, multimodal (mixed input of text, images, files), + * cards, and various types of content. + * */ + @JsonProperty("content") + private String content; + + @JsonProperty("meta_data") + private Map metaData; + + /* + * The type of message content. + * */ + @JsonProperty("content_type") + private MessageContentType contentType; + + public abstract static class UpdateMessageReqBuilder< + C extends UpdateMessageReq, B extends UpdateMessageReqBuilder> + extends BaseReqBuilder { + public B objectContent(List objects) { + this.content = Utils.toJson(objects); + this.contentType = MessageContentType.OBJECT_STRING; + return self(); } + } } diff --git a/api/src/main/java/com/coze/openapi/client/connversations/message/UpdateMessageResp.java b/api/src/main/java/com/coze/openapi/client/connversations/message/UpdateMessageResp.java index 359620a7..8a498805 100644 --- a/api/src/main/java/com/coze/openapi/client/connversations/message/UpdateMessageResp.java +++ b/api/src/main/java/com/coze/openapi/client/connversations/message/UpdateMessageResp.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.connversations.message; import com.coze.openapi.client.common.BaseResp; @@ -18,6 +19,6 @@ @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) public class UpdateMessageResp extends BaseResp { - @JsonProperty("message") - private Message message; + @JsonProperty("message") + private Message message; } diff --git a/api/src/main/java/com/coze/openapi/client/connversations/message/model/Message.java b/api/src/main/java/com/coze/openapi/client/connversations/message/model/Message.java index 26c5c31e..477837f2 100644 --- a/api/src/main/java/com/coze/openapi/client/connversations/message/model/Message.java +++ b/api/src/main/java/com/coze/openapi/client/connversations/message/model/Message.java @@ -1,124 +1,122 @@ +/* (C)2024 */ package com.coze.openapi.client.connversations.message.model; +import java.util.List; +import java.util.Map; + import com.coze.openapi.service.utils.Utils; 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 @NoArgsConstructor @AllArgsConstructor public class Message { - /** - * The entity that sent this message. - */ - @JsonProperty("role") - private MessageRole role; - - /** - * The type of message. - */ - @JsonProperty("type") - private MessageType type; - - /** - * The content of the message. It supports various types of content, including plain text, multimodal (a mix of text, images, and files), message cards, and more. - * 消息的内容,支持纯文本、多模态(文本、图片、文件混合输入)、卡片等多种类型的内容。 - */ - @JsonProperty("content") - private String content; - - /** - * The type of message content. - * 消息内容的类型 - */ - @JsonProperty("content_type") - private MessageContentType contentType; - - /** - * Additional information when creating a message, and this additional information will also be returned when retrieving messages. - * Custom key-value pairs should be specified in Map object format, with a length of 16 key-value pairs. - * The length of the key should be between 1 and 64 characters, and the length of the value should be between 1 and 512 characters. - * 创建消息时的附加消息,获取消息时也会返回此附加消息。 - * 自定义键值对,应指定为 Map 对象格式。长度为 16 对键值对,其中键(key)的长度范围为 1~64 个字符,值(value)的长度范围为 1~512 个字符。 - */ - @JsonProperty("meta_data") - private Map metaData; - - @JsonProperty("id") - private String id; - - @JsonProperty("conversation_id") - private String conversationId; - - /** - * section_id is used to distinguish the context sections of the session history. The same section is one context. - */ - @JsonProperty("section_id") - private String sectionId; - - @JsonProperty("bot_id") - private String botId; - - @JsonProperty("chat_id") - private String chatId; - - @JsonProperty("created_at") - private Long createdAt; - - @JsonProperty("updated_at") - private Long updatedAt; - - public static Message buildUserQuestionText(String content) { - return buildUserQuestionText(content, null); - } - - public static Message buildUserQuestionText(String content, Map metaData) { - return Message.builder() - .role(MessageRole.USER) - .type(MessageType.QUESTION) - .content(content) - .contentType(MessageContentType.TEXT) - .metaData(metaData) - .build(); - } - - public static Message buildUserQuestionObjects(List objects) { - return buildUserQuestionObjects(objects, null); - } - - public static Message buildUserQuestionObjects(List objects, Map metaData) { - return Message.builder() - .role(MessageRole.USER) - .type(MessageType.QUESTION) - .content(Utils.toJson(objects)) - .contentType(MessageContentType.OBJECT_STRING) - .metaData(metaData) - .build(); - } - - public static Message buildAssistantAnswer(String content) { - return buildAssistantAnswer(content, null); - } - - public static Message buildAssistantAnswer(String content, Map metaData) { - return Message.builder() - .role(MessageRole.ASSISTANT) - .type(MessageType.ANSWER) - .content(content) - .contentType(MessageContentType.TEXT) - .metaData(metaData) - .build(); - } - - - public static Message fromJson(String json) { - return Utils.fromJson(json, Message.class); - } -} \ No newline at end of file + /** The entity that sent this message. */ + @JsonProperty("role") + private MessageRole role; + + /** The type of message. */ + @JsonProperty("type") + private MessageType type; + + /** + * The content of the message. It supports various types of content, including plain text, + * multimodal (a mix of text, images, and files), message cards, and more. + * 消息的内容,支持纯文本、多模态(文本、图片、文件混合输入)、卡片等多种类型的内容。 + */ + @JsonProperty("content") + private String content; + + /** The type of message content. 消息内容的类型 */ + @JsonProperty("content_type") + private MessageContentType contentType; + + /** + * Additional information when creating a message, and this additional information will also be + * returned when retrieving messages. Custom key-value pairs should be specified in Map object + * format, with a length of 16 key-value pairs. The length of the key should be between 1 and 64 + * characters, and the length of the value should be between 1 and 512 characters. + * 创建消息时的附加消息,获取消息时也会返回此附加消息。 自定义键值对,应指定为 Map 对象格式。长度为 16 对键值对,其中键(key)的长度范围为 1~64 + * 个字符,值(value)的长度范围为 1~512 个字符。 + */ + @JsonProperty("meta_data") + private Map metaData; + + @JsonProperty("id") + private String id; + + @JsonProperty("conversation_id") + private String conversationId; + + /** + * section_id is used to distinguish the context sections of the session history. The same section + * is one context. + */ + @JsonProperty("section_id") + private String sectionId; + + @JsonProperty("bot_id") + private String botId; + + @JsonProperty("chat_id") + private String chatId; + + @JsonProperty("created_at") + private Long createdAt; + + @JsonProperty("updated_at") + private Long updatedAt; + + public static Message buildUserQuestionText(String content) { + return buildUserQuestionText(content, null); + } + + public static Message buildUserQuestionText(String content, Map metaData) { + return Message.builder() + .role(MessageRole.USER) + .type(MessageType.QUESTION) + .content(content) + .contentType(MessageContentType.TEXT) + .metaData(metaData) + .build(); + } + + public static Message buildUserQuestionObjects(List objects) { + return buildUserQuestionObjects(objects, null); + } + + public static Message buildUserQuestionObjects( + List objects, Map metaData) { + return Message.builder() + .role(MessageRole.USER) + .type(MessageType.QUESTION) + .content(Utils.toJson(objects)) + .contentType(MessageContentType.OBJECT_STRING) + .metaData(metaData) + .build(); + } + + public static Message buildAssistantAnswer(String content) { + return buildAssistantAnswer(content, null); + } + + public static Message buildAssistantAnswer(String content, Map metaData) { + return Message.builder() + .role(MessageRole.ASSISTANT) + .type(MessageType.ANSWER) + .content(content) + .contentType(MessageContentType.TEXT) + .metaData(metaData) + .build(); + } + + public static Message fromJson(String json) { + return Utils.fromJson(json, Message.class); + } +} diff --git a/api/src/main/java/com/coze/openapi/client/connversations/message/model/MessageContentType.java b/api/src/main/java/com/coze/openapi/client/connversations/message/model/MessageContentType.java index 00fdb6c5..8c8dcd54 100644 --- a/api/src/main/java/com/coze/openapi/client/connversations/message/model/MessageContentType.java +++ b/api/src/main/java/com/coze/openapi/client/connversations/message/model/MessageContentType.java @@ -1,40 +1,44 @@ +/* (C)2024 */ package com.coze.openapi.client.connversations.message.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; public enum MessageContentType { - UNKNOWN("unknown"), - // Text. - TEXT("text"), - - // Multimodal content, that is, a combination of text and files, or a combination of text and images. - OBJECT_STRING("object_string"), - - // Message card. This enum value only appears in the interface response and is not supported as an input parameter. - CARD("card"), - - // If there is a voice message in the input message, the conversation.audio.delta event will be returned in the streaming response event. - AUDIO("audio"); - - private final String value; - - MessageContentType(String value) { - this.value = value; - } - - @JsonValue - public String getValue() { - return value; - } - - @JsonCreator // 反序列化时使用这个方法 - public static MessageContentType fromString(String value) { - for (MessageContentType type : MessageContentType.values()) { - if (type.value.equals(value)) { - return type; - } - } - return UNKNOWN; + UNKNOWN("unknown"), + // Text. + TEXT("text"), + + // Multimodal content, that is, a combination of text and files, or a combination of text and + // images. + OBJECT_STRING("object_string"), + + // Message card. This enum value only appears in the interface response and is not supported as an + // input parameter. + CARD("card"), + + // If there is a voice message in the input message, the conversation.audio.delta event will be + // returned in the streaming response event. + AUDIO("audio"); + + private final String value; + + MessageContentType(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @JsonCreator // 反序列化时使用这个方法 + public static MessageContentType fromString(String value) { + for (MessageContentType type : MessageContentType.values()) { + if (type.value.equals(value)) { + return type; + } } -} \ No newline at end of file + return UNKNOWN; + } +} diff --git a/api/src/main/java/com/coze/openapi/client/connversations/message/model/MessageObjectString.java b/api/src/main/java/com/coze/openapi/client/connversations/message/model/MessageObjectString.java index e29e36b2..cf75feee 100644 --- a/api/src/main/java/com/coze/openapi/client/connversations/message/model/MessageObjectString.java +++ b/api/src/main/java/com/coze/openapi/client/connversations/message/model/MessageObjectString.java @@ -1,7 +1,9 @@ +/* (C)2024 */ package com.coze.openapi.client.connversations.message.model; import com.coze.openapi.service.utils.Utils; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -13,95 +15,80 @@ @AllArgsConstructor public class MessageObjectString { - /** - * The content type of the multimodal message. - * 多模态消息内容类型 - */ - @JsonProperty("type") - private MessageObjectStringType type; - - /** - * Text content. Required when type is text. - * 文本内容。 - */ - @JsonProperty("text") - private String text; - - /** - * The ID of the file or image content. - * 在 type 为 file 或 image 时,file_id 和 file_url 应至少指定一个。 - */ - @JsonProperty("file_id") - private String fileID; - - /** - * The online address of the file or image content. - * Must be a valid address that is publicly accessible. - * file_id or file_url must be specified when type is file or image. - * 文件或图片内容的在线地址。必须是可公共访问的有效地址。 - * 在 type 为 file 或 image 时,file_id 和 file_url 应至少指定一个。 - */ - @JsonProperty("file_url") - private String fileURL; - - public static MessageObjectString buildText(String text) { - return MessageObjectString.builder() - .type(MessageObjectStringType.TEXT) - .text(text) - .build(); - } - - public static MessageObjectString buildImageByID(String fileID) { - return buildImage(fileID, null); - } - - public static MessageObjectString buildImageByURL(String fileURL) { - return buildImage(null, fileURL); - } - - private static MessageObjectString buildImage(String fileID, String fileURL) { - if (fileID == null && fileURL == null) { - throw new IllegalArgumentException("file_id or file_url must be specified"); - } - return MessageObjectString.builder() - .type(MessageObjectStringType.IMAGE) - .fileID(fileID) - .fileURL(fileURL) - .build(); - } - - public static MessageObjectString buildFileByID(String fileID) { - return buildFile(fileID, null); - } - - public static MessageObjectString buildFileByURL(String fileURL) { - return buildFile(null, fileURL); - + /** The content type of the multimodal message. 多模态消息内容类型 */ + @JsonProperty("type") + private MessageObjectStringType type; + + /** Text content. Required when type is text. 文本内容。 */ + @JsonProperty("text") + private String text; + + /** The ID of the file or image content. 在 type 为 file 或 image 时,file_id 和 file_url 应至少指定一个。 */ + @JsonProperty("file_id") + private String fileID; + + /** + * The online address of the file or image content. Must be a valid address that is publicly + * accessible. file_id or file_url must be specified when type is file or image. + * 文件或图片内容的在线地址。必须是可公共访问的有效地址。 在 type 为 file 或 image 时,file_id 和 file_url 应至少指定一个。 + */ + @JsonProperty("file_url") + private String fileURL; + + public static MessageObjectString buildText(String text) { + return MessageObjectString.builder().type(MessageObjectStringType.TEXT).text(text).build(); + } + + public static MessageObjectString buildImageByID(String fileID) { + return buildImage(fileID, null); + } + + public static MessageObjectString buildImageByURL(String fileURL) { + return buildImage(null, fileURL); + } + + private static MessageObjectString buildImage(String fileID, String fileURL) { + if (fileID == null && fileURL == null) { + throw new IllegalArgumentException("file_id or file_url must be specified"); } - - private static MessageObjectString buildFile(String fileID, String fileURL) { - if (fileID == null && fileURL == null) { - throw new IllegalArgumentException("file_id or file_url must be specified"); - } - return MessageObjectString.builder() - .type(MessageObjectStringType.FILE) - .fileID(fileID) - .fileURL(fileURL) - .build(); - } - - public static MessageObjectString buildAudio(String fileID, String fileURL) { - if (fileID == null && fileURL == null) { - throw new IllegalArgumentException("file_id or file_url must be specified"); - } - return MessageObjectString.builder() - .type(MessageObjectStringType.AUDIO) - .fileID(fileID) - .fileURL(fileURL) - .build(); + return MessageObjectString.builder() + .type(MessageObjectStringType.IMAGE) + .fileID(fileID) + .fileURL(fileURL) + .build(); + } + + public static MessageObjectString buildFileByID(String fileID) { + return buildFile(fileID, null); + } + + public static MessageObjectString buildFileByURL(String fileURL) { + return buildFile(null, fileURL); + } + + private static MessageObjectString buildFile(String fileID, String fileURL) { + if (fileID == null && fileURL == null) { + throw new IllegalArgumentException("file_id or file_url must be specified"); } - - public String toJson() { - return Utils.toJson(this); + return MessageObjectString.builder() + .type(MessageObjectStringType.FILE) + .fileID(fileID) + .fileURL(fileURL) + .build(); + } + + public static MessageObjectString buildAudio(String fileID, String fileURL) { + if (fileID == null && fileURL == null) { + throw new IllegalArgumentException("file_id or file_url must be specified"); } -} + return MessageObjectString.builder() + .type(MessageObjectStringType.AUDIO) + .fileID(fileID) + .fileURL(fileURL) + .build(); + } + + public String toJson() { + return Utils.toJson(this); + } +} diff --git a/api/src/main/java/com/coze/openapi/client/connversations/message/model/MessageObjectStringType.java b/api/src/main/java/com/coze/openapi/client/connversations/message/model/MessageObjectStringType.java index 97335047..e79545c2 100644 --- a/api/src/main/java/com/coze/openapi/client/connversations/message/model/MessageObjectStringType.java +++ b/api/src/main/java/com/coze/openapi/client/connversations/message/model/MessageObjectStringType.java @@ -1,36 +1,35 @@ +/* (C)2024 */ package com.coze.openapi.client.connversations.message.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -/** - * The content type of the multimodal message. - */ +/** The content type of the multimodal message. */ public enum MessageObjectStringType { - UNKNOWN("unknown"), - TEXT("text"), - FILE("file"), - IMAGE("image"), - AUDIO("audio"); + UNKNOWN("unknown"), + TEXT("text"), + FILE("file"), + IMAGE("image"), + AUDIO("audio"); - private final String value; + private final String value; - MessageObjectStringType(String value) { - this.value = value; - } + MessageObjectStringType(String value) { + this.value = value; + } - @JsonValue - public String getValue() { - return value; - } + @JsonValue + public String getValue() { + return value; + } - @JsonCreator // 反序列化时使用这个方法 - public static MessageObjectStringType fromString(String value) { - for (MessageObjectStringType type : MessageObjectStringType.values()) { - if (type.value.equals(value)) { - return type; - } - } - return UNKNOWN; + @JsonCreator // 反序列化时使用这个方法 + public static MessageObjectStringType fromString(String value) { + for (MessageObjectStringType type : MessageObjectStringType.values()) { + if (type.value.equals(value)) { + return type; + } } -} \ No newline at end of file + return UNKNOWN; + } +} diff --git a/api/src/main/java/com/coze/openapi/client/connversations/message/model/MessageRole.java b/api/src/main/java/com/coze/openapi/client/connversations/message/model/MessageRole.java index c823180b..00a8c393 100644 --- a/api/src/main/java/com/coze/openapi/client/connversations/message/model/MessageRole.java +++ b/api/src/main/java/com/coze/openapi/client/connversations/message/model/MessageRole.java @@ -1,34 +1,35 @@ +/* (C)2024 */ package com.coze.openapi.client.connversations.message.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; public enum MessageRole { - UNKNOWN("unknown"), - // Indicates that the content of the message is sent by the user. - USER("user"), + UNKNOWN("unknown"), + // Indicates that the content of the message is sent by the user. + USER("user"), - // Indicates that the content of the message is sent by the bot. - ASSISTANT("assistant"); + // Indicates that the content of the message is sent by the bot. + ASSISTANT("assistant"); - private final String value; + private final String value; - MessageRole(String value) { - this.value = value; - } + MessageRole(String value) { + this.value = value; + } - @JsonValue - public String getValue() { - return value; - } + @JsonValue + public String getValue() { + return value; + } - @JsonCreator // 反序列化时使用这个方法 - public static MessageRole fromString(String value) { - for (MessageRole role : MessageRole.values()) { - if (role.value.equals(value)) { - return role; - } - } - return UNKNOWN; + @JsonCreator // 反序列化时使用这个方法 + public static MessageRole fromString(String value) { + for (MessageRole role : MessageRole.values()) { + if (role.value.equals(value)) { + return role; + } } -} \ No newline at end of file + return UNKNOWN; + } +} diff --git a/api/src/main/java/com/coze/openapi/client/connversations/message/model/MessageType.java b/api/src/main/java/com/coze/openapi/client/connversations/message/model/MessageType.java index bd788a90..eaad270b 100644 --- a/api/src/main/java/com/coze/openapi/client/connversations/message/model/MessageType.java +++ b/api/src/main/java/com/coze/openapi/client/connversations/message/model/MessageType.java @@ -1,50 +1,53 @@ +/* (C)2024 */ package com.coze.openapi.client.connversations.message.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; public enum MessageType { - // User input content. - QUESTION("question"), + // User input content. + QUESTION("question"), - // The message content returned by the Bot to the user, supporting incremental return. - ANSWER("answer"), + // The message content returned by the Bot to the user, supporting incremental return. + ANSWER("answer"), - // Intermediate results of the function (function call) called during the Bot conversation process. - FUNCTION_CALL("function_call"), + // Intermediate results of the function (function call) called during the Bot conversation + // process. + FUNCTION_CALL("function_call"), - // Results returned after calling the tool (function call). - TOOL_OUTPUT("tool_output"), + // Results returned after calling the tool (function call). + TOOL_OUTPUT("tool_output"), - // Results returned after calling the tool (function call). - TOOL_RESPONSE("tool_response"), + // Results returned after calling the tool (function call). + TOOL_RESPONSE("tool_response"), - // If the user question suggestion switch is turned on in the Bot configuration, the reply content related to the recommended questions will be returned. - FOLLOW_UP("follow_up"), + // If the user question suggestion switch is turned on in the Bot configuration, the reply content + // related to the recommended questions will be returned. + FOLLOW_UP("follow_up"), - // In the scenario of multiple answers, the server will return a verbose package. - VERBOSE("verbose"), + // In the scenario of multiple answers, the server will return a verbose package. + VERBOSE("verbose"), - UNKNOWN(""); + UNKNOWN(""); - private final String value; + private final String value; - MessageType(String value) { - this.value = value; - } + MessageType(String value) { + this.value = value; + } - @JsonValue - public String getValue() { - return value; - } + @JsonValue + public String getValue() { + return value; + } - @JsonCreator // 反序列化时使用这个方法 - public static MessageType fromString(String value) { - for (MessageType type : MessageType.values()) { - if (type.value.equals(value)) { - return type; - } - } - return UNKNOWN; + @JsonCreator // 反序列化时使用这个方法 + public static MessageType fromString(String value) { + for (MessageType type : MessageType.values()) { + if (type.value.equals(value)) { + return type; + } } -} \ No newline at end of file + return UNKNOWN; + } +} diff --git a/api/src/main/java/com/coze/openapi/client/connversations/model/Conversation.java b/api/src/main/java/com/coze/openapi/client/connversations/model/Conversation.java index 5067a46f..0504a7ff 100644 --- a/api/src/main/java/com/coze/openapi/client/connversations/model/Conversation.java +++ b/api/src/main/java/com/coze/openapi/client/connversations/model/Conversation.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.connversations.model; import java.util.Map; @@ -14,19 +15,19 @@ @NoArgsConstructor @AllArgsConstructor public class Conversation { - @JsonProperty("id") - private String id; + @JsonProperty("id") + private String id; - @JsonProperty("created_at") - private Integer createdAt; + @JsonProperty("created_at") + private Integer createdAt; - @JsonProperty("meta_data") - private Map metaData; + @JsonProperty("meta_data") + private Map metaData; - /* - * section_id is used to distinguish the context sections of the session history. - * The same section is one context. - * */ - @JsonProperty("last_section_id") - private String lastSectionID; + /* + * section_id is used to distinguish the context sections of the session history. + * The same section is one context. + * */ + @JsonProperty("last_section_id") + private String lastSectionID; } diff --git a/api/src/main/java/com/coze/openapi/client/dataset/document/CreateDocumentReq.java b/api/src/main/java/com/coze/openapi/client/dataset/document/CreateDocumentReq.java index 7b53b901..510a201e 100644 --- a/api/src/main/java/com/coze/openapi/client/dataset/document/CreateDocumentReq.java +++ b/api/src/main/java/com/coze/openapi/client/dataset/document/CreateDocumentReq.java @@ -1,21 +1,22 @@ +/* (C)2024 */ package com.coze.openapi.client.dataset.document; import java.util.List; import org.jetbrains.annotations.NotNull; -import lombok.Data; -import lombok.EqualsAndHashCode; -import lombok.NoArgsConstructor; -import lombok.AllArgsConstructor; -import lombok.experimental.SuperBuilder; - import com.coze.openapi.client.common.BaseReq; import com.coze.openapi.client.dataset.document.model.DocumentBase; import com.coze.openapi.client.dataset.document.model.DocumentChunkStrategy; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NoArgsConstructor; +import lombok.experimental.SuperBuilder; + @Data @SuperBuilder @NoArgsConstructor @@ -23,26 +24,26 @@ @JsonInclude(JsonInclude.Include.NON_NULL) @EqualsAndHashCode(callSuper = true) public class CreateDocumentReq extends BaseReq { - /** - * The ID of the knowledge base. - */ - @NotNull - @JsonProperty("dataset_id") - private Long datasetID; + /** The ID of the knowledge base. */ + @NotNull + @JsonProperty("dataset_id") + private Long datasetID; - /** - * The metadata information of the files awaiting upload. The array has a maximum length of 10, meaning up to 10 files can be uploaded at a time. - * For detailed instructions, refer to the DocumentBase object. - */ - @NotNull - @JsonProperty("document_bases") - private List documentBases; + /** + * The metadata information of the files awaiting upload. The array has a maximum length of 10, + * meaning up to 10 files can be uploaded at a time. For detailed instructions, refer to the + * DocumentBase object. + */ + @NotNull + @JsonProperty("document_bases") + private List documentBases; - /** - * Chunk strategy. These rules must be set only when uploading a file to new knowledge for the first time. - * For subsequent file uploads to this knowledge, it is not necessary to pass these rules; the default is to continue using the initial settings, and modifications are not supported. - * For detailed instructions, refer to the ChunkStrategy object. - */ - @JsonProperty("chunk_strategy") - private DocumentChunkStrategy chunkStrategy; + /** + * Chunk strategy. These rules must be set only when uploading a file to new knowledge for the + * first time. For subsequent file uploads to this knowledge, it is not necessary to pass these + * rules; the default is to continue using the initial settings, and modifications are not + * supported. For detailed instructions, refer to the ChunkStrategy object. + */ + @JsonProperty("chunk_strategy") + private DocumentChunkStrategy chunkStrategy; } diff --git a/api/src/main/java/com/coze/openapi/client/dataset/document/CreateDocumentResp.java b/api/src/main/java/com/coze/openapi/client/dataset/document/CreateDocumentResp.java index 5afd9c7b..a7336a6d 100644 --- a/api/src/main/java/com/coze/openapi/client/dataset/document/CreateDocumentResp.java +++ b/api/src/main/java/com/coze/openapi/client/dataset/document/CreateDocumentResp.java @@ -1,5 +1,8 @@ +/* (C)2024 */ package com.coze.openapi.client.dataset.document; +import java.util.List; + import com.coze.openapi.client.common.BaseResponse; import com.coze.openapi.client.dataset.document.model.Document; import com.fasterxml.jackson.annotation.JsonInclude; @@ -8,18 +11,14 @@ import lombok.*; import lombok.experimental.SuperBuilder; -import java.util.List; - - @Data @SuperBuilder @NoArgsConstructor @AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) -@EqualsAndHashCode(callSuper=true) +@EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) -public class CreateDocumentResp extends BaseResponse>{ - @JsonProperty("document_infos") - private List documentInfos; - +public class CreateDocumentResp extends BaseResponse> { + @JsonProperty("document_infos") + private List documentInfos; } diff --git a/api/src/main/java/com/coze/openapi/client/dataset/document/DeleteDocumentReq.java b/api/src/main/java/com/coze/openapi/client/dataset/document/DeleteDocumentReq.java index e956ca3e..345c7db4 100644 --- a/api/src/main/java/com/coze/openapi/client/dataset/document/DeleteDocumentReq.java +++ b/api/src/main/java/com/coze/openapi/client/dataset/document/DeleteDocumentReq.java @@ -1,7 +1,12 @@ +/* (C)2024 */ package com.coze.openapi.client.dataset.document; import java.util.List; +import com.coze.openapi.client.common.BaseReq; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; @@ -9,10 +14,6 @@ import lombok.NonNull; import lombok.experimental.SuperBuilder; -import com.coze.openapi.client.common.BaseReq; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; - @Data @SuperBuilder @NoArgsConstructor @@ -20,7 +21,7 @@ @JsonInclude(JsonInclude.Include.NON_NULL) @EqualsAndHashCode(callSuper = true) public class DeleteDocumentReq extends BaseReq { - @NonNull - @JsonProperty("document_ids") - private List documentIDs; + @NonNull + @JsonProperty("document_ids") + private List documentIDs; } diff --git a/api/src/main/java/com/coze/openapi/client/dataset/document/DeleteDocumentResp.java b/api/src/main/java/com/coze/openapi/client/dataset/document/DeleteDocumentResp.java index 87d56adf..6f6b2e93 100644 --- a/api/src/main/java/com/coze/openapi/client/dataset/document/DeleteDocumentResp.java +++ b/api/src/main/java/com/coze/openapi/client/dataset/document/DeleteDocumentResp.java @@ -1,17 +1,17 @@ +/* (C)2024 */ package com.coze.openapi.client.dataset.document; import com.coze.openapi.client.common.BaseResp; +import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.ToString; import lombok.experimental.SuperBuilder; -import lombok.Data; @Data @SuperBuilder @NoArgsConstructor @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) -public class DeleteDocumentResp extends BaseResp{ -} +public class DeleteDocumentResp extends BaseResp {} diff --git a/api/src/main/java/com/coze/openapi/client/dataset/document/ListDocumentReq.java b/api/src/main/java/com/coze/openapi/client/dataset/document/ListDocumentReq.java index 152858fc..91bf66a9 100644 --- a/api/src/main/java/com/coze/openapi/client/dataset/document/ListDocumentReq.java +++ b/api/src/main/java/com/coze/openapi/client/dataset/document/ListDocumentReq.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.dataset.document; import org.jetbrains.annotations.NotNull; @@ -20,28 +21,25 @@ @JsonInclude(JsonInclude.Include.NON_NULL) @EqualsAndHashCode(callSuper = true) public class ListDocumentReq extends BaseReq { - /** - * The ID of the knowledge base. - */ - @NotNull - @JsonProperty("dataset_id") - private Long datasetID; + /** The ID of the knowledge base. */ + @NotNull + @JsonProperty("dataset_id") + private Long datasetID; - /** - * The page number for paginated queries. Default is 1, meaning the data return starts from the first page. - */ - @JsonProperty("page") - @Builder.Default - private Integer page = 1; + /** + * The page number for paginated queries. Default is 1, meaning the data return starts from the + * first page. + */ + @JsonProperty("page") + @Builder.Default + private Integer page = 1; - /** - * The size of pagination. Default is 10, meaning that 10 data entries are returned per page. - */ - @JsonProperty("size") - @Builder.Default - private Integer size = 10; + /** The size of pagination. Default is 10, meaning that 10 data entries are returned per page. */ + @JsonProperty("size") + @Builder.Default + private Integer size = 10; - public static ListDocumentReq of(Long datasetID, Integer page, Integer size) { - return ListDocumentReq.builder().datasetID(datasetID).page(page).size(size).build(); - } + public static ListDocumentReq of(Long datasetID, Integer page, Integer size) { + return ListDocumentReq.builder().datasetID(datasetID).page(page).size(size).build(); + } } diff --git a/api/src/main/java/com/coze/openapi/client/dataset/document/ListDocumentResp.java b/api/src/main/java/com/coze/openapi/client/dataset/document/ListDocumentResp.java index 2e811acc..6a2a3dfa 100644 --- a/api/src/main/java/com/coze/openapi/client/dataset/document/ListDocumentResp.java +++ b/api/src/main/java/com/coze/openapi/client/dataset/document/ListDocumentResp.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.dataset.document; import java.util.List; @@ -17,10 +18,10 @@ @EqualsAndHashCode(callSuper = true) @JsonInclude(JsonInclude.Include.NON_NULL) @ToString(callSuper = true) -public class ListDocumentResp extends BaseResponse>{ - @JsonProperty("total") - private Long total; - @JsonProperty("document_infos") - private List documentInfos; - +public class ListDocumentResp extends BaseResponse> { + @JsonProperty("total") + private Long total; + + @JsonProperty("document_infos") + private List documentInfos; } diff --git a/api/src/main/java/com/coze/openapi/client/dataset/document/UpdateDocumentReq.java b/api/src/main/java/com/coze/openapi/client/dataset/document/UpdateDocumentReq.java index 0417ab3e..1284e2b2 100644 --- a/api/src/main/java/com/coze/openapi/client/dataset/document/UpdateDocumentReq.java +++ b/api/src/main/java/com/coze/openapi/client/dataset/document/UpdateDocumentReq.java @@ -1,5 +1,7 @@ +/* (C)2024 */ package com.coze.openapi.client.dataset.document; +import com.coze.openapi.client.common.BaseReq; import com.coze.openapi.client.dataset.document.model.DocumentUpdateRule; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; @@ -10,7 +12,6 @@ import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.experimental.SuperBuilder; -import com.coze.openapi.client.common.BaseReq; @Data @SuperBuilder @@ -19,22 +20,18 @@ @JsonInclude(JsonInclude.Include.NON_NULL) @EqualsAndHashCode(callSuper = true) public class UpdateDocumentReq extends BaseReq { - /** - * The ID of the knowledge base file. - */ - @NonNull - @JsonProperty("document_id") - private Long documentID; - /** - * The new name of the knowledge base file. - */ - @JsonProperty("document_name") - private String documentName; + /** The ID of the knowledge base file. */ + @NonNull + @JsonProperty("document_id") + private Long documentID; + /** The new name of the knowledge base file. */ + @JsonProperty("document_name") + private String documentName; - /** - * The update strategy for online web pages. Defaults to no automatic updates. - * For detailed information, refer to the UpdateRule object. - */ - @JsonProperty("update_rule") - private DocumentUpdateRule updateRule; + /** + * The update strategy for online web pages. Defaults to no automatic updates. For detailed + * information, refer to the UpdateRule object. + */ + @JsonProperty("update_rule") + private DocumentUpdateRule updateRule; } diff --git a/api/src/main/java/com/coze/openapi/client/dataset/document/UpdateDocumentResp.java b/api/src/main/java/com/coze/openapi/client/dataset/document/UpdateDocumentResp.java index d1a91d34..92792a4e 100644 --- a/api/src/main/java/com/coze/openapi/client/dataset/document/UpdateDocumentResp.java +++ b/api/src/main/java/com/coze/openapi/client/dataset/document/UpdateDocumentResp.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.dataset.document; import com.coze.openapi.client.common.BaseResp; @@ -13,5 +14,4 @@ @NoArgsConstructor @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) -public class UpdateDocumentResp extends BaseResp{ -} +public class UpdateDocumentResp extends BaseResp {} diff --git a/api/src/main/java/com/coze/openapi/client/dataset/document/model/Document.java b/api/src/main/java/com/coze/openapi/client/dataset/document/model/Document.java index dfedc39d..f00ba08a 100644 --- a/api/src/main/java/com/coze/openapi/client/dataset/document/model/Document.java +++ b/api/src/main/java/com/coze/openapi/client/dataset/document/model/Document.java @@ -1,6 +1,8 @@ +/* (C)2024 */ package com.coze.openapi.client.dataset.document.model; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -11,128 +13,89 @@ @NoArgsConstructor @AllArgsConstructor public class Document { - /** - * The ID of the file. - * 文件的 ID。 - */ - @JsonProperty("document_id") - private String documentID; - - /** - * The total character count of the file content. - * 文件内容的总字符数量。 - */ - @JsonProperty("char_count") - private int charCount; - - /** - * The chunking rules. For detailed instructions, refer to the ChunkStrategy object. - * 分段规则。详细说明可参考 chunk_strategy object。 - */ - @JsonProperty("chunk_strategy") - private DocumentChunkStrategy chunkStrategy; - - /** - * The upload time of the file, in the format of a 10-digit Unix timestamp. - * 文件的上传时间,格式为 10 位的 Unixtime 时间戳。 - */ - @JsonProperty("create_time") - private int createTime; - - /** - * The last modified time of the file, in the format of a 10-digit Unix timestamp. - * 文件的最近一次修改时间,格式为 10 位的 Unixtime 时间戳。 - */ - @JsonProperty("update_time") - private int updateTime; - - /** - * The type of file format. Values include: - * 0: Document type, such as txt, pdf, online web pages, etc. - * 1: Spreadsheet type, such as xls spreadsheets, etc. - * 2: Photo type, such as png images, etc. - * 文件的格式类型。取值包括: - * 0:文档类型,例如 txt 、pdf 、在线网页等格式均属于文档类型。 - * 1:表格类型,例如 xls 表格等格式属于表格类型。 - * 2:照片类型,例如 png 图片等格式属于照片类型。 - */ - @JsonProperty("format_type") - private DocumentFormatType formatType; - - /** - * The number of times the file has been hit in conversations. - * 被对话命中的次数。 - */ - @JsonProperty("hit_count") - private int hitCount; - - /** - * The name of the file. - * 文件的名称。 - */ - @JsonProperty("name") - private String name; - - /** - * The size of the file in bytes. - * 文件的大小,单位为字节。 - */ - @JsonProperty("size") - private int size; - - /** - * The number of slices the file has been divided into. - * 文件的分段数量。 - */ - @JsonProperty("slice_count") - private int sliceCount; - - /** - * The method of uploading the file. Values include: - * 0: Upload local files. - * 1: Upload online web pages. - * 文件的上传方式。取值包括: - * 0:上传本地文件。 - * 1:上传在线网页。 - */ - @JsonProperty("source_type") - private DocumentSourceType sourceType; - - /** - * The processing status of the file. Values include: - * 0: Processing - * 1: Completed - * 9: Processing failed, it is recommended to re-upload - * 文件的处理状态。取值包括: - * 0:处理中 - * 1:处理完毕 - * 9:处理失败,建议重新上传 - */ - @JsonProperty("status") - private DocumentStatus status; - - /** - * The format of the local file, i.e., the file extension, such as "txt". Supported formats include PDF, TXT, DOC, DOCX. - * 本地文件格式,即文件后缀,例如 txt。格式支持 pdf、txt、doc、docx 类型。 - */ - @JsonProperty("type") - private String type; - - /** - * The frequency of automatic updates for online web pages, in hours. - * 在线网页自动更新的频率。单位为小时。 - */ - @JsonProperty("update_interval") - private int updateInterval; - - /** - * Whether the online web page is automatically updated. Values include: - * 0: Do not automatically update - * 1: Automatically update - * 在线网页是否自动更新。取值包括: - * 0:不自动更新 - * 1:自动更新 - */ - @JsonProperty("update_type") - private DocumentUpdateType updateType; -} \ No newline at end of file + /** The ID of the file. 文件的 ID。 */ + @JsonProperty("document_id") + private String documentID; + + /** The total character count of the file content. 文件内容的总字符数量。 */ + @JsonProperty("char_count") + private int charCount; + + /** + * The chunking rules. For detailed instructions, refer to the ChunkStrategy object. 分段规则。详细说明可参考 + * chunk_strategy object。 + */ + @JsonProperty("chunk_strategy") + private DocumentChunkStrategy chunkStrategy; + + /** + * The upload time of the file, in the format of a 10-digit Unix timestamp. 文件的上传时间,格式为 10 位的 + * Unixtime 时间戳。 + */ + @JsonProperty("create_time") + private int createTime; + + /** + * The last modified time of the file, in the format of a 10-digit Unix timestamp. 文件的最近一次修改时间,格式为 + * 10 位的 Unixtime 时间戳。 + */ + @JsonProperty("update_time") + private int updateTime; + + /** + * The type of file format. Values include: 0: Document type, such as txt, pdf, online web pages, + * etc. 1: Spreadsheet type, such as xls spreadsheets, etc. 2: Photo type, such as png images, + * etc. 文件的格式类型。取值包括: 0:文档类型,例如 txt 、pdf 、在线网页等格式均属于文档类型。 1:表格类型,例如 xls 表格等格式属于表格类型。 2:照片类型,例如 png + * 图片等格式属于照片类型。 + */ + @JsonProperty("format_type") + private DocumentFormatType formatType; + + /** The number of times the file has been hit in conversations. 被对话命中的次数。 */ + @JsonProperty("hit_count") + private int hitCount; + + /** The name of the file. 文件的名称。 */ + @JsonProperty("name") + private String name; + + /** The size of the file in bytes. 文件的大小,单位为字节。 */ + @JsonProperty("size") + private int size; + + /** The number of slices the file has been divided into. 文件的分段数量。 */ + @JsonProperty("slice_count") + private int sliceCount; + + /** + * The method of uploading the file. Values include: 0: Upload local files. 1: Upload online web + * pages. 文件的上传方式。取值包括: 0:上传本地文件。 1:上传在线网页。 + */ + @JsonProperty("source_type") + private DocumentSourceType sourceType; + + /** + * The processing status of the file. Values include: 0: Processing 1: Completed 9: Processing + * failed, it is recommended to re-upload 文件的处理状态。取值包括: 0:处理中 1:处理完毕 9:处理失败,建议重新上传 + */ + @JsonProperty("status") + private DocumentStatus status; + + /** + * The format of the local file, i.e., the file extension, such as "txt". Supported formats + * include PDF, TXT, DOC, DOCX. 本地文件格式,即文件后缀,例如 txt。格式支持 pdf、txt、doc、docx 类型。 + */ + @JsonProperty("type") + private String type; + + /** The frequency of automatic updates for online web pages, in hours. 在线网页自动更新的频率。单位为小时。 */ + @JsonProperty("update_interval") + private int updateInterval; + + /** + * Whether the online web page is automatically updated. Values include: 0: Do not automatically + * update 1: Automatically update 在线网页是否自动更新。取值包括: 0:不自动更新 1:自动更新 + */ + @JsonProperty("update_type") + private DocumentUpdateType updateType; +} diff --git a/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentBase.java b/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentBase.java index d101b4c6..82a9aee4 100644 --- a/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentBase.java +++ b/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentBase.java @@ -1,44 +1,49 @@ +/* (C)2024 */ package com.coze.openapi.client.dataset.document.model; -import lombok.*; -import org.jetbrains.annotations.NotNull; - import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.*; + @Data @Builder @NoArgsConstructor @AllArgsConstructor public class DocumentBase { - /** - * 文件名称。 - */ - @NonNull - @JsonProperty("name") - private String name; - - /** - * 文件的元数据信息。详细信息可参考 DocumentSourceInfo object。 - */ - @NonNull - @JsonProperty("source_info") - private DocumentSourceInfo sourceInfo; - - /** - * 在线网页的更新策略。默认不自动更新。 - */ - @JsonProperty("update_rule") - private DocumentUpdateRule updateRule; - - public static DocumentBase buildWebPage(String name, String url) { - return DocumentBase.builder().name(name).sourceInfo(DocumentSourceInfo.buildWebPage(url)).updateRule(DocumentUpdateRule.buildNoAutoUpdate()).build(); - } - - public static DocumentBase buildWebPage(String name, String url, Integer interval) { - return DocumentBase.builder().name(name).sourceInfo(DocumentSourceInfo.buildWebPage(url)).updateRule(DocumentUpdateRule.buildAutoUpdate(interval)).build(); - } - - public static DocumentBase buildLocalFile(String name, String content, String fileType) { - return DocumentBase.builder().name(name).sourceInfo(DocumentSourceInfo.buildLocalFile(content, fileType)).build(); - } -} + /** 文件名称。 */ + @NonNull + @JsonProperty("name") + private String name; + + /** 文件的元数据信息。详细信息可参考 DocumentSourceInfo object。 */ + @NonNull + @JsonProperty("source_info") + private DocumentSourceInfo sourceInfo; + + /** 在线网页的更新策略。默认不自动更新。 */ + @JsonProperty("update_rule") + private DocumentUpdateRule updateRule; + + public static DocumentBase buildWebPage(String name, String url) { + return DocumentBase.builder() + .name(name) + .sourceInfo(DocumentSourceInfo.buildWebPage(url)) + .updateRule(DocumentUpdateRule.buildNoAutoUpdate()) + .build(); + } + + public static DocumentBase buildWebPage(String name, String url, Integer interval) { + return DocumentBase.builder() + .name(name) + .sourceInfo(DocumentSourceInfo.buildWebPage(url)) + .updateRule(DocumentUpdateRule.buildAutoUpdate(interval)) + .build(); + } + + public static DocumentBase buildLocalFile(String name, String content, String fileType) { + return DocumentBase.builder() + .name(name) + .sourceInfo(DocumentSourceInfo.buildLocalFile(content, fileType)) + .build(); + } +} diff --git a/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentChunkStrategy.java b/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentChunkStrategy.java index 36578375..3d65b289 100644 --- a/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentChunkStrategy.java +++ b/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentChunkStrategy.java @@ -1,6 +1,8 @@ +/* (C)2024 */ package com.coze.openapi.client.dataset.document.model; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.*; @Getter @@ -9,91 +11,78 @@ @NoArgsConstructor @AllArgsConstructor public class DocumentChunkStrategy { - /** - * 分段设置。取值包括: - * 0:自动分段与清洗。采用扣子预置规则进行数据分段与处理。 - * 1:自定义。此时需要通过 separator、max_tokens、remove_extra_spaces 和 remove_urls_emails 分段规则细节。 - */ - @JsonProperty("chunk_type") - private Integer chunkType; + /** + * 分段设置。取值包括: 0:自动分段与清洗。采用扣子预置规则进行数据分段与处理。 1:自定义。此时需要通过 separator、max_tokens、remove_extra_spaces 和 + * remove_urls_emails 分段规则细节。 + */ + @JsonProperty("chunk_type") + private Integer chunkType; - /** - * 最大分段长度,取值范围为 100~2000。 - * 在 chunk_type=1 时必选。 - */ - @JsonProperty("max_tokens") - private Integer maxTokens; + /** 最大分段长度,取值范围为 100~2000。 在 chunk_type=1 时必选。 */ + @JsonProperty("max_tokens") + private Integer maxTokens; - /** - * 是否自动过滤连续的空格、换行符和制表符。取值包括: - * true:自动过滤 - * false:(默认)不自动过滤 - * 在 chunk_type=1 时生效。 - */ - @JsonProperty("remove_extra_spaces") - private Boolean removeExtraSpaces; + /** 是否自动过滤连续的空格、换行符和制表符。取值包括: true:自动过滤 false:(默认)不自动过滤 在 chunk_type=1 时生效。 */ + @JsonProperty("remove_extra_spaces") + private Boolean removeExtraSpaces; - /** - * 是否自动过滤所有 URL 和电子邮箱地址。取值包括: - * true:自动过滤 - * false:(默认)不自动过滤 - * 在 chunk_type=1 时生效。 - */ - @JsonProperty("remove_urls_emails") - private Boolean removeUrlsEmails; + /** 是否自动过滤所有 URL 和电子邮箱地址。取值包括: true:自动过滤 false:(默认)不自动过滤 在 chunk_type=1 时生效。 */ + @JsonProperty("remove_urls_emails") + private Boolean removeUrlsEmails; - /** - * 分段标识符。 - * 在 chunk_type=1 时必选。 - */ - @JsonProperty("separator") - private String separator; + /** 分段标识符。 在 chunk_type=1 时必选。 */ + @JsonProperty("separator") + private String separator; - public static class DocumentChunkStrategyBuilder { - public DocumentChunkStrategy build(){ - if (this.chunkType == null) { - throw new IllegalStateException("chunkType is required"); - } - if (this.chunkType == 1) { - if (maxTokens == null || separator == null || removeExtraSpaces == null || removeUrlsEmails == null) { - throw new IllegalStateException("All fields must be non-null when chunk_type is 1"); - } - } - DocumentChunkStrategy strategy = new DocumentChunkStrategy(); - strategy.setChunkType(chunkType); - strategy.setMaxTokens(maxTokens); - strategy.setRemoveExtraSpaces(removeExtraSpaces); - strategy.setRemoveUrlsEmails(removeUrlsEmails); - strategy.setSeparator(separator); - return strategy; + public static class DocumentChunkStrategyBuilder { + public DocumentChunkStrategy build() { + if (this.chunkType == null) { + throw new IllegalStateException("chunkType is required"); + } + if (this.chunkType == 1) { + if (maxTokens == null + || separator == null + || removeExtraSpaces == null + || removeUrlsEmails == null) { + throw new IllegalStateException("All fields must be non-null when chunk_type is 1"); } + } + DocumentChunkStrategy strategy = new DocumentChunkStrategy(); + strategy.setChunkType(chunkType); + strategy.setMaxTokens(maxTokens); + strategy.setRemoveExtraSpaces(removeExtraSpaces); + strategy.setRemoveUrlsEmails(removeUrlsEmails); + strategy.setSeparator(separator); + return strategy; } + } - /** - * 创建自动分段的 DocumentChunkStrategy 实例。 - * @return DocumentChunkStrategy 实例 - */ - public static DocumentChunkStrategy buildAuto() { - return DocumentChunkStrategy.builder() - .chunkType(0) - .build(); - } + /** + * 创建自动分段的 DocumentChunkStrategy 实例。 + * + * @return DocumentChunkStrategy 实例 + */ + public static DocumentChunkStrategy buildAuto() { + return DocumentChunkStrategy.builder().chunkType(0).build(); + } - /** - * 创建自定义分段的 DocumentChunkStrategy 实例。 - * @param maxTokens 最大分段长度 - * @param separator 分段标识符 - * @param removeExtraSpaces 是否自动过滤连续空格 - * @param removeUrlsEmails 是否自动过滤 URL 和电子邮箱 - * @return DocumentChunkStrategy 实例 - */ - public static DocumentChunkStrategy buildCustom(int maxTokens, String separator, boolean removeExtraSpaces, boolean removeUrlsEmails) { - return DocumentChunkStrategy.builder() - .chunkType(1) - .maxTokens(maxTokens) - .separator(separator) - .removeExtraSpaces(removeExtraSpaces) - .removeUrlsEmails(removeUrlsEmails) - .build(); - } -} \ No newline at end of file + /** + * 创建自定义分段的 DocumentChunkStrategy 实例。 + * + * @param maxTokens 最大分段长度 + * @param separator 分段标识符 + * @param removeExtraSpaces 是否自动过滤连续空格 + * @param removeUrlsEmails 是否自动过滤 URL 和电子邮箱 + * @return DocumentChunkStrategy 实例 + */ + public static DocumentChunkStrategy buildCustom( + int maxTokens, String separator, boolean removeExtraSpaces, boolean removeUrlsEmails) { + return DocumentChunkStrategy.builder() + .chunkType(1) + .maxTokens(maxTokens) + .separator(separator) + .removeExtraSpaces(removeExtraSpaces) + .removeUrlsEmails(removeUrlsEmails) + .build(); + } +} diff --git a/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentFormatType.java b/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentFormatType.java index 5fb7c836..eae9a51a 100644 --- a/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentFormatType.java +++ b/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentFormatType.java @@ -1,45 +1,37 @@ +/* (C)2024 */ package com.coze.openapi.client.dataset.document.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; public enum DocumentFormatType { - /** - * Document type, such as txt, pdf, online web pages, etc. - * 文档类型,例如 txt 、pdf 、在线网页等格式均属于文档类型。 - */ - DOCUMENT(0), - - /** - * Spreadsheet type, such as xls spreadsheets, etc. - * 表格类型,例如 xls 表格等格式属于表格类型。 - */ - SPREADSHEET(1), - - /** - * Photo type, such as png images, etc. - * 照片类型,例如 png 图片等格式属于照片类型。 - */ - IMAGE(2); - - private final int value; - - DocumentFormatType(int value) { - this.value = value; - } + /** Document type, such as txt, pdf, online web pages, etc. 文档类型,例如 txt 、pdf 、在线网页等格式均属于文档类型。 */ + DOCUMENT(0), - @JsonValue - public int getValue() { - return value; - } + /** Spreadsheet type, such as xls spreadsheets, etc. 表格类型,例如 xls 表格等格式属于表格类型。 */ + SPREADSHEET(1), + + /** Photo type, such as png images, etc. 照片类型,例如 png 图片等格式属于照片类型。 */ + IMAGE(2); + + private final int value; + + DocumentFormatType(int value) { + this.value = value; + } + + @JsonValue + public int getValue() { + return value; + } - @JsonCreator - public static DocumentFormatType fromValue(int value) { - for (DocumentFormatType type : DocumentFormatType.values()) { - if (type.value == value) { - return type; - } - } - throw new IllegalArgumentException("Unknown DocumentFormatType value: " + value); + @JsonCreator + public static DocumentFormatType fromValue(int value) { + for (DocumentFormatType type : DocumentFormatType.values()) { + if (type.value == value) { + return type; + } } -} \ No newline at end of file + throw new IllegalArgumentException("Unknown DocumentFormatType value: " + value); + } +} diff --git a/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentSourceInfo.java b/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentSourceInfo.java index a7cddaeb..f76e20f2 100644 --- a/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentSourceInfo.java +++ b/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentSourceInfo.java @@ -1,56 +1,48 @@ +/* (C)2024 */ package com.coze.openapi.client.dataset.document.model; + import java.util.Base64; + import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; - @Setter(AccessLevel.PRIVATE) @Getter public class DocumentSourceInfo { - /** - * 本地文件的 Base64 编码。 - * 上传本地文件时必选 - */ - @JsonProperty("file_base64") - private String fileBase64; - - /** - * 本地文件的格式,即文件后缀,例如 txt。格式支持 pdf、txt、doc、docx 类型。 - * 上传的文件类型应与知识库类型匹配,例如 txt 文件只能上传到文档类型的知识库中。 - * 上传本地文件时必选 - */ - @JsonProperty("file_type") - private String fileType; - - /** - * 网页的 URL 地址。 - * 上传网页时必选 - */ - @JsonProperty("web_url") - private String webUrl; - - /** - * 文件的上传方式。支持设置为 1,表示上传在线网页。 - * 上传在线网页时必选 - */ - @JsonProperty("document_source") - private Integer documentSource; - - public static DocumentSourceInfo buildLocalFile(String content, String fileType) { - String encodedContent = Base64.getEncoder().encodeToString(content.getBytes()); - DocumentSourceInfo info = new DocumentSourceInfo(); - info.setFileBase64(encodedContent); - info.setFileType(fileType); - return info; - } - - public static DocumentSourceInfo buildWebPage(String url) { - DocumentSourceInfo info = new DocumentSourceInfo(); - info.setWebUrl(url); - info.setDocumentSource(1); - return info; - } -} \ No newline at end of file + /** 本地文件的 Base64 编码。 上传本地文件时必选 */ + @JsonProperty("file_base64") + private String fileBase64; + + /** + * 本地文件的格式,即文件后缀,例如 txt。格式支持 pdf、txt、doc、docx 类型。 上传的文件类型应与知识库类型匹配,例如 txt 文件只能上传到文档类型的知识库中。 + * 上传本地文件时必选 + */ + @JsonProperty("file_type") + private String fileType; + + /** 网页的 URL 地址。 上传网页时必选 */ + @JsonProperty("web_url") + private String webUrl; + + /** 文件的上传方式。支持设置为 1,表示上传在线网页。 上传在线网页时必选 */ + @JsonProperty("document_source") + private Integer documentSource; + + public static DocumentSourceInfo buildLocalFile(String content, String fileType) { + String encodedContent = Base64.getEncoder().encodeToString(content.getBytes()); + DocumentSourceInfo info = new DocumentSourceInfo(); + info.setFileBase64(encodedContent); + info.setFileType(fileType); + return info; + } + + public static DocumentSourceInfo buildWebPage(String url) { + DocumentSourceInfo info = new DocumentSourceInfo(); + info.setWebUrl(url); + info.setDocumentSource(1); + return info; + } +} diff --git a/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentSourceType.java b/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentSourceType.java index c8493030..4f3af8fb 100644 --- a/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentSourceType.java +++ b/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentSourceType.java @@ -1,39 +1,34 @@ +/* (C)2024 */ package com.coze.openapi.client.dataset.document.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; public enum DocumentSourceType { - /** - * Upload local files. - * 上传本地文件。 - */ - LOCAL_FILE(0), + /** Upload local files. 上传本地文件。 */ + LOCAL_FILE(0), - /** - * Upload online web pages. - * 上传在线网页。 - */ - ONLINE_WEB(1); + /** Upload online web pages. 上传在线网页。 */ + ONLINE_WEB(1); - private final int value; + private final int value; - DocumentSourceType(int value) { - this.value = value; - } + DocumentSourceType(int value) { + this.value = value; + } - @JsonValue - public int getValue() { - return value; - } + @JsonValue + public int getValue() { + return value; + } - @JsonCreator - public static DocumentSourceType fromValue(int value) { - for (DocumentSourceType type : DocumentSourceType.values()) { - if (type.value == value) { - return type; - } - } - throw new IllegalArgumentException("Unknown DocumentSourceType value: " + value); + @JsonCreator + public static DocumentSourceType fromValue(int value) { + for (DocumentSourceType type : DocumentSourceType.values()) { + if (type.value == value) { + return type; + } } -} \ No newline at end of file + throw new IllegalArgumentException("Unknown DocumentSourceType value: " + value); + } +} diff --git a/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentStatus.java b/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentStatus.java index 7686e404..f10edf57 100644 --- a/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentStatus.java +++ b/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentStatus.java @@ -1,45 +1,37 @@ +/* (C)2024 */ package com.coze.openapi.client.dataset.document.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; public enum DocumentStatus { - /** - * Processing - * 处理中 - */ - PROCESSING(0), - - /** - * Completed - * 处理完毕 - */ - COMPLETED(1), - - /** - * Processing failed, it is recommended to re-upload - * 处理失败,建议重新上传 - */ - FAILED(9); - - private final int value; - - DocumentStatus(int value) { - this.value = value; - } + /** Processing 处理中 */ + PROCESSING(0), - @JsonValue - public int getValue() { - return value; - } + /** Completed 处理完毕 */ + COMPLETED(1), + + /** Processing failed, it is recommended to re-upload 处理失败,建议重新上传 */ + FAILED(9); + + private final int value; + + DocumentStatus(int value) { + this.value = value; + } + + @JsonValue + public int getValue() { + return value; + } - @JsonCreator - public static DocumentStatus fromValue(int value) { - for (DocumentStatus status : DocumentStatus.values()) { - if (status.value == value) { - return status; - } - } - throw new IllegalArgumentException("Unknown DocumentStatus value: " + value); + @JsonCreator + public static DocumentStatus fromValue(int value) { + for (DocumentStatus status : DocumentStatus.values()) { + if (status.value == value) { + return status; + } } -} \ No newline at end of file + throw new IllegalArgumentException("Unknown DocumentStatus value: " + value); + } +} diff --git a/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentUpdateRule.java b/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentUpdateRule.java index 651cc518..06428cb8 100644 --- a/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentUpdateRule.java +++ b/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentUpdateRule.java @@ -1,47 +1,45 @@ +/* (C)2024 */ package com.coze.openapi.client.dataset.document.model; import com.fasterxml.jackson.annotation.JsonProperty; -import lombok.Getter; + import lombok.AccessLevel; +import lombok.Getter; import lombok.Setter; @Getter @Setter(AccessLevel.PRIVATE) public class DocumentUpdateRule { - /** - * 在线网页是否自动更新。取值包括: - * 0:不自动更新 - * 1:自动更新 - */ - @JsonProperty("update_type") - private DocumentUpdateType updateType; + /** 在线网页是否自动更新。取值包括: 0:不自动更新 1:自动更新 */ + @JsonProperty("update_type") + private DocumentUpdateType updateType; - /** - * 在线网页自动更新的频率。单位为小时,最小值为 24。 - */ - @JsonProperty("update_interval") - private int updateInterval; + /** 在线网页自动更新的频率。单位为小时,最小值为 24。 */ + @JsonProperty("update_interval") + private int updateInterval; - /** - * 创建不自动更新的 DocumentUpdateRule 实例。 - * @return DocumentUpdateRule 实例 - */ - public static DocumentUpdateRule buildNoAutoUpdate() { - DocumentUpdateRule rule = new DocumentUpdateRule(); - rule.setUpdateType(DocumentUpdateType.NO_AUTO_UPDATE); - rule.setUpdateInterval(24); - return rule; - } + /** + * 创建不自动更新的 DocumentUpdateRule 实例。 + * + * @return DocumentUpdateRule 实例 + */ + public static DocumentUpdateRule buildNoAutoUpdate() { + DocumentUpdateRule rule = new DocumentUpdateRule(); + rule.setUpdateType(DocumentUpdateType.NO_AUTO_UPDATE); + rule.setUpdateInterval(24); + return rule; + } - /** - * 创建自动更新的 DocumentUpdateRule 实例。 - * @param interval 更新频率 - * @return DocumentUpdateRule 实例 - */ - public static DocumentUpdateRule buildAutoUpdate(int interval) { - DocumentUpdateRule rule = new DocumentUpdateRule(); - rule.setUpdateType(DocumentUpdateType.AUTO_UPDATE); - rule.setUpdateInterval(interval); - return rule; - } -} \ No newline at end of file + /** + * 创建自动更新的 DocumentUpdateRule 实例。 + * + * @param interval 更新频率 + * @return DocumentUpdateRule 实例 + */ + public static DocumentUpdateRule buildAutoUpdate(int interval) { + DocumentUpdateRule rule = new DocumentUpdateRule(); + rule.setUpdateType(DocumentUpdateType.AUTO_UPDATE); + rule.setUpdateInterval(interval); + return rule; + } +} diff --git a/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentUpdateType.java b/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentUpdateType.java index d0e542bd..06c6858b 100644 --- a/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentUpdateType.java +++ b/api/src/main/java/com/coze/openapi/client/dataset/document/model/DocumentUpdateType.java @@ -1,39 +1,34 @@ +/* (C)2024 */ package com.coze.openapi.client.dataset.document.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; public enum DocumentUpdateType { - /** - * Do not automatically update - * 不自动更新 - */ - NO_AUTO_UPDATE(0), + /** Do not automatically update 不自动更新 */ + NO_AUTO_UPDATE(0), - /** - * Automatically update - * 自动更新 - */ - AUTO_UPDATE(1); + /** Automatically update 自动更新 */ + AUTO_UPDATE(1); - private final int value; + private final int value; - DocumentUpdateType(int value) { - this.value = value; - } + DocumentUpdateType(int value) { + this.value = value; + } - @JsonValue - public int getValue() { - return value; - } + @JsonValue + public int getValue() { + return value; + } - @JsonCreator - public static DocumentUpdateType fromValue(int value) { - for (DocumentUpdateType updateType : DocumentUpdateType.values()) { - if (updateType.value == value) { - return updateType; - } - } - throw new IllegalArgumentException("Unknown DocumentUpdateType value: " + value); + @JsonCreator + public static DocumentUpdateType fromValue(int value) { + for (DocumentUpdateType updateType : DocumentUpdateType.values()) { + if (updateType.value == value) { + return updateType; + } } -} \ No newline at end of file + throw new IllegalArgumentException("Unknown DocumentUpdateType value: " + value); + } +} diff --git a/api/src/main/java/com/coze/openapi/client/exception/AuthErrorCode.java b/api/src/main/java/com/coze/openapi/client/exception/AuthErrorCode.java index 5b1e4313..53431fbf 100644 --- a/api/src/main/java/com/coze/openapi/client/exception/AuthErrorCode.java +++ b/api/src/main/java/com/coze/openapi/client/exception/AuthErrorCode.java @@ -1,81 +1,80 @@ +/* (C)2024 */ package com.coze.openapi.client.exception; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; + import lombok.Getter; -/** - * 认证错误码类 - */ +/** 认证错误码类 */ @Getter public class AuthErrorCode { - /* - * The user has not completed authorization yet, please try again later - */ - public static final AuthErrorCode AUTHORIZATION_PENDING = new AuthErrorCode("authorization_pending"); + /* + * The user has not completed authorization yet, please try again later + */ + public static final AuthErrorCode AUTHORIZATION_PENDING = + new AuthErrorCode("authorization_pending"); - /* - * The request is too frequent, please try again later - */ - public static final AuthErrorCode SLOW_DOWN = new AuthErrorCode("slow_down"); + /* + * The request is too frequent, please try again later + */ + public static final AuthErrorCode SLOW_DOWN = new AuthErrorCode("slow_down"); - /* - * The user has denied the authorization - */ - public static final AuthErrorCode ACCESS_DENIED = new AuthErrorCode("access_denied"); + /* + * The user has denied the authorization + */ + public static final AuthErrorCode ACCESS_DENIED = new AuthErrorCode("access_denied"); - /* - * The token is expired - */ - public static final AuthErrorCode EXPIRED_TOKEN = new AuthErrorCode("expired_token"); + /* + * The token is expired + */ + public static final AuthErrorCode EXPIRED_TOKEN = new AuthErrorCode("expired_token"); - /** - * 错误码的字符串值 - */ - private final String value; + /** 错误码的字符串值 */ + private final String value; - /** - * 私有构造函数,防止外部创建新实例 - * - * @param value 错误码字符串值 - */ - private AuthErrorCode(String value) { - this.value = value; - } + /** + * 私有构造函数,防止外部创建新实例 + * + * @param value 错误码字符串值 + */ + private AuthErrorCode(String value) { + this.value = value; + } - /** - * 获取错误码的值,用于 JSON 序列化 - * - * @return 错误码字符串值 - */ - @JsonValue - public String getValue() { - return value; - } + /** + * 获取错误码的值,用于 JSON 序列化 + * + * @return 错误码字符串值 + */ + @JsonValue + public String getValue() { + return value; + } - @Override - public String toString() { - return this.value; - } + @Override + public String toString() { + return this.value; + } - /** - * 从字符串创建错误码实例 - * - * @param value 错误码字符串值 - * @return 对应的错误码实例 - * @throws IllegalArgumentException 如果找不到对应的错误码 - */ - @JsonCreator - public static AuthErrorCode fromString(String value) { - if (value == null) { - return null; - } - - if (value.equals(AUTHORIZATION_PENDING.value)) return AUTHORIZATION_PENDING; - if (value.equals(SLOW_DOWN.value)) return SLOW_DOWN; - if (value.equals(ACCESS_DENIED.value)) return ACCESS_DENIED; - if (value.equals(EXPIRED_TOKEN.value)) return EXPIRED_TOKEN; - - return new AuthErrorCode(value); + /** + * 从字符串创建错误码实例 + * + * @param value 错误码字符串值 + * @return 对应的错误码实例 + * @throws IllegalArgumentException 如果找不到对应的错误码 + */ + @JsonCreator + public static AuthErrorCode fromString(String value) { + if (value == null) { + return null; } + + if (value.equals(AUTHORIZATION_PENDING.value)) return AUTHORIZATION_PENDING; + if (value.equals(SLOW_DOWN.value)) return SLOW_DOWN; + if (value.equals(ACCESS_DENIED.value)) return ACCESS_DENIED; + if (value.equals(EXPIRED_TOKEN.value)) return EXPIRED_TOKEN; + + return new AuthErrorCode(value); + } } diff --git a/api/src/main/java/com/coze/openapi/client/exception/CozeApiExcetion.java b/api/src/main/java/com/coze/openapi/client/exception/CozeApiExcetion.java index 3fed9faa..b25a2d7c 100644 --- a/api/src/main/java/com/coze/openapi/client/exception/CozeApiExcetion.java +++ b/api/src/main/java/com/coze/openapi/client/exception/CozeApiExcetion.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.exception; import lombok.Getter; @@ -6,14 +7,14 @@ @Getter @ToString public class CozeApiExcetion extends RuntimeException { - private final int code; - private final String msg; - private final String logID; + private final int code; + private final String msg; + private final String logID; - public CozeApiExcetion(int code, String msg, String logID) { - super(msg); - this.code = code; - this.msg = msg; - this.logID = logID; - } + public CozeApiExcetion(int code, String msg, String logID) { + super(msg); + this.code = code; + this.msg = msg; + this.logID = logID; + } } diff --git a/api/src/main/java/com/coze/openapi/client/exception/CozeAuthException.java b/api/src/main/java/com/coze/openapi/client/exception/CozeAuthException.java index 08d84ae0..3a0e85da 100644 --- a/api/src/main/java/com/coze/openapi/client/exception/CozeAuthException.java +++ b/api/src/main/java/com/coze/openapi/client/exception/CozeAuthException.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.exception; import lombok.Getter; @@ -8,27 +9,27 @@ @ToString public class CozeAuthException extends RuntimeException { - private final int statusCode; - private final AuthErrorCode code; - private final String errorMessage; - private final String param; - private final String logID; - - public CozeAuthException(CozeError error, Exception parent, int statusCode, String logID) { - super(error.errorMessage, parent); - this.statusCode = statusCode; - this.errorMessage = error.errorMessage; - this.code = AuthErrorCode.fromString(error.errorCode); - this.param = error.error; - this.logID = logID; - } + private final int statusCode; + private final AuthErrorCode code; + private final String errorMessage; + private final String param; + private final String logID; - public CozeAuthException(CozeError error, int statusCode, String logID) { - super(error.errorMessage); - this.statusCode = statusCode; - this.errorMessage = error.errorMessage; - this.code = AuthErrorCode.fromString(error.errorCode); - this.param = error.error; - this.logID = logID; - } + public CozeAuthException(CozeError error, Exception parent, int statusCode, String logID) { + super(error.errorMessage, parent); + this.statusCode = statusCode; + this.errorMessage = error.errorMessage; + this.code = AuthErrorCode.fromString(error.errorCode); + this.param = error.error; + this.logID = logID; + } + + public CozeAuthException(CozeError error, int statusCode, String logID) { + super(error.errorMessage); + this.statusCode = statusCode; + this.errorMessage = error.errorMessage; + this.code = AuthErrorCode.fromString(error.errorCode); + this.param = error.error; + this.logID = logID; + } } diff --git a/api/src/main/java/com/coze/openapi/client/exception/CozeError.java b/api/src/main/java/com/coze/openapi/client/exception/CozeError.java index fbbb485a..52619a79 100644 --- a/api/src/main/java/com/coze/openapi/client/exception/CozeError.java +++ b/api/src/main/java/com/coze/openapi/client/exception/CozeError.java @@ -1,7 +1,9 @@ +/* (C)2024 */ package com.coze.openapi.client.exception; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.Data; import lombok.NoArgsConstructor; @@ -9,20 +11,21 @@ @NoArgsConstructor public class CozeError { - @JsonProperty("error_message") - String errorMessage; + @JsonProperty("error_message") + String errorMessage; - @JsonProperty("error_code") - String errorCode; + @JsonProperty("error_code") + String errorCode; - String error; + String error; - @JsonCreator - public CozeError(@JsonProperty("error_message") String errorMessage, - @JsonProperty("error_code") String errorCode, - @JsonProperty("error") String error) { - this.errorMessage = errorMessage; - this.errorCode = errorCode; - this.error = error; - } + @JsonCreator + public CozeError( + @JsonProperty("error_message") String errorMessage, + @JsonProperty("error_code") String errorCode, + @JsonProperty("error") String error) { + this.errorMessage = errorMessage; + this.errorCode = errorCode; + this.error = error; + } } diff --git a/api/src/main/java/com/coze/openapi/client/files/RetrieveFileReq.java b/api/src/main/java/com/coze/openapi/client/files/RetrieveFileReq.java index f1cdcf95..1789b636 100644 --- a/api/src/main/java/com/coze/openapi/client/files/RetrieveFileReq.java +++ b/api/src/main/java/com/coze/openapi/client/files/RetrieveFileReq.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.files; import com.coze.openapi.client.common.BaseReq; @@ -14,9 +15,9 @@ @AllArgsConstructor @EqualsAndHashCode(callSuper = true) public class RetrieveFileReq extends BaseReq { - private String fileID; + private String fileID; - public static RetrieveFileReq of(String fileID) { - return RetrieveFileReq.builder().fileID(fileID).build(); - } + public static RetrieveFileReq of(String fileID) { + return RetrieveFileReq.builder().fileID(fileID).build(); + } } diff --git a/api/src/main/java/com/coze/openapi/client/files/RetrieveFileResp.java b/api/src/main/java/com/coze/openapi/client/files/RetrieveFileResp.java index 21c51944..07de1c4b 100644 --- a/api/src/main/java/com/coze/openapi/client/files/RetrieveFileResp.java +++ b/api/src/main/java/com/coze/openapi/client/files/RetrieveFileResp.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.files; import com.coze.openapi.client.common.BaseResp; @@ -11,7 +12,7 @@ @NoArgsConstructor @AllArgsConstructor @ToString(callSuper = true) -@EqualsAndHashCode(callSuper=true) +@EqualsAndHashCode(callSuper = true) public class RetrieveFileResp extends BaseResp { - private FileInfo fileInfo; + private FileInfo fileInfo; } diff --git a/api/src/main/java/com/coze/openapi/client/files/UploadFileReq.java b/api/src/main/java/com/coze/openapi/client/files/UploadFileReq.java index 094fbc15..d0364063 100644 --- a/api/src/main/java/com/coze/openapi/client/files/UploadFileReq.java +++ b/api/src/main/java/com/coze/openapi/client/files/UploadFileReq.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.files; import java.io.File; @@ -14,35 +15,29 @@ @NoArgsConstructor @EqualsAndHashCode(callSuper = true) public class UploadFileReq extends BaseReq { - /** - * local file path - */ - private String filePath; - - /* - * file byte array - */ - private byte[] fileBytes; - - /** - * file name - */ - private String fileName; - - /** - * file object - */ - private File file; - - public static UploadFileReq of(String fileName, byte[] fileBytes) { - return UploadFileReq.builder().fileName(fileName).fileBytes(fileBytes).build(); - } - - public static UploadFileReq of(File file) { - return UploadFileReq.builder().file(file).build(); - } - - public static UploadFileReq of(String filePath) { - return UploadFileReq.builder().filePath(filePath).build(); - } + /** local file path */ + private String filePath; + + /* + * file byte array + */ + private byte[] fileBytes; + + /** file name */ + private String fileName; + + /** file object */ + private File file; + + public static UploadFileReq of(String fileName, byte[] fileBytes) { + return UploadFileReq.builder().fileName(fileName).fileBytes(fileBytes).build(); + } + + public static UploadFileReq of(File file) { + return UploadFileReq.builder().file(file).build(); + } + + public static UploadFileReq of(String filePath) { + return UploadFileReq.builder().filePath(filePath).build(); + } } diff --git a/api/src/main/java/com/coze/openapi/client/files/UploadFileResp.java b/api/src/main/java/com/coze/openapi/client/files/UploadFileResp.java index 8fa668a8..b3d28e25 100644 --- a/api/src/main/java/com/coze/openapi/client/files/UploadFileResp.java +++ b/api/src/main/java/com/coze/openapi/client/files/UploadFileResp.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.files; import com.coze.openapi.client.common.BaseResp; @@ -11,7 +12,7 @@ @NoArgsConstructor @AllArgsConstructor @ToString(callSuper = true) -@EqualsAndHashCode(callSuper=true) +@EqualsAndHashCode(callSuper = true) public class UploadFileResp extends BaseResp { - private FileInfo fileInfo; + private FileInfo fileInfo; } diff --git a/api/src/main/java/com/coze/openapi/client/files/model/FileInfo.java b/api/src/main/java/com/coze/openapi/client/files/model/FileInfo.java index 8baf4ebc..3279b1f1 100644 --- a/api/src/main/java/com/coze/openapi/client/files/model/FileInfo.java +++ b/api/src/main/java/com/coze/openapi/client/files/model/FileInfo.java @@ -1,7 +1,8 @@ +/* (C)2024 */ package com.coze.openapi.client.files.model; -import com.coze.openapi.client.common.BaseResp; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -11,23 +12,24 @@ @Builder @NoArgsConstructor @AllArgsConstructor -public class FileInfo{ - // The ID of the uploaded file. - @JsonProperty("id") - private String id; - public String getID() { - return id; - } +public class FileInfo { + // The ID of the uploaded file. + @JsonProperty("id") + private String id; + + public String getID() { + return id; + } - // The total byte size of the file. - @JsonProperty("bytes") - private Integer bytes; + // The total byte size of the file. + @JsonProperty("bytes") + private Integer bytes; - // The upload time of the file, in the format of a 10-digit Unix timestamp in seconds (s). - @JsonProperty("created_at") - private Integer createdAt; + // The upload time of the file, in the format of a 10-digit Unix timestamp in seconds (s). + @JsonProperty("created_at") + private Integer createdAt; - // The name of the file. - @JsonProperty("file_name") - private String fileName; -} \ No newline at end of file + // The name of the file. + @JsonProperty("file_name") + private String fileName; +} diff --git a/api/src/main/java/com/coze/openapi/client/workflows/run/ResumeRunReq.java b/api/src/main/java/com/coze/openapi/client/workflows/run/ResumeRunReq.java index 128087bb..8d7ea356 100644 --- a/api/src/main/java/com/coze/openapi/client/workflows/run/ResumeRunReq.java +++ b/api/src/main/java/com/coze/openapi/client/workflows/run/ResumeRunReq.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.workflows.run; import com.coze.openapi.client.common.BaseReq; @@ -14,38 +15,39 @@ @NoArgsConstructor @EqualsAndHashCode(callSuper = true) public class ResumeRunReq extends BaseReq { - /* - * The ID of the workflow, which should have been published. - * */ - @NonNull - @JsonProperty("workflow_id") - private String workflowID; + /* + * The ID of the workflow, which should have been published. + * */ + @NonNull + @JsonProperty("workflow_id") + private String workflowID; - /* - * eventID - * */ - @NonNull - @JsonProperty("event_id") - private String eventID; + /* + * eventID + * */ + @NonNull + @JsonProperty("event_id") + private String eventID; - /* - * resumeData - * */ - @NonNull - @JsonProperty("resume_data") - private String resumeData; + /* + * resumeData + * */ + @NonNull + @JsonProperty("resume_data") + private String resumeData; - /* - * interruptType - * */ - @NonNull - @JsonProperty("interrupt_type") - private Integer interruptType; + /* + * interruptType + * */ + @NonNull + @JsonProperty("interrupt_type") + private Integer interruptType; - protected ResumeRunReq(String workflowID, String eventID, String resumeData, Integer interruptType) { - this.workflowID = workflowID; - this.eventID = eventID; - this.resumeData = resumeData; - this.interruptType = interruptType; - } + protected ResumeRunReq( + String workflowID, String eventID, String resumeData, Integer interruptType) { + this.workflowID = workflowID; + this.eventID = eventID; + this.resumeData = resumeData; + this.interruptType = interruptType; + } } diff --git a/api/src/main/java/com/coze/openapi/client/workflows/run/RetrieveRunHistoryReq.java b/api/src/main/java/com/coze/openapi/client/workflows/run/RetrieveRunHistoryReq.java index e4e26165..96d04ccc 100644 --- a/api/src/main/java/com/coze/openapi/client/workflows/run/RetrieveRunHistoryReq.java +++ b/api/src/main/java/com/coze/openapi/client/workflows/run/RetrieveRunHistoryReq.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.workflows.run; import com.coze.openapi.client.common.BaseReq; @@ -17,21 +18,21 @@ @AllArgsConstructor public class RetrieveRunHistoryReq extends BaseReq { - /* - * The ID of the workflow. - * */ - @NonNull - @JsonProperty("execute_id") - private String executeID; + /* + * The ID of the workflow. + * */ + @NonNull + @JsonProperty("execute_id") + private String executeID; - /* - * The ID of the workflow async execute. - * */ - @NonNull - @JsonProperty("workflow_id") - private String workflowID; + /* + * The ID of the workflow async execute. + * */ + @NonNull + @JsonProperty("workflow_id") + private String workflowID; - public static RetrieveRunHistoryReq of(String workflowID, String executeID) { - return RetrieveRunHistoryReq.builder().executeID(executeID).workflowID(workflowID).build(); - } + public static RetrieveRunHistoryReq of(String workflowID, String executeID) { + return RetrieveRunHistoryReq.builder().executeID(executeID).workflowID(workflowID).build(); + } } diff --git a/api/src/main/java/com/coze/openapi/client/workflows/run/RetrieveRunHistoryResp.java b/api/src/main/java/com/coze/openapi/client/workflows/run/RetrieveRunHistoryResp.java index b8f58f23..736d6cd4 100644 --- a/api/src/main/java/com/coze/openapi/client/workflows/run/RetrieveRunHistoryResp.java +++ b/api/src/main/java/com/coze/openapi/client/workflows/run/RetrieveRunHistoryResp.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.workflows.run; import java.util.List; @@ -17,6 +18,5 @@ @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) public class RetrieveRunHistoryResp extends BaseResp { - private List histories; - + private List histories; } diff --git a/api/src/main/java/com/coze/openapi/client/workflows/run/RunWorkflowReq.java b/api/src/main/java/com/coze/openapi/client/workflows/run/RunWorkflowReq.java index ff8c688a..4a0c27e1 100644 --- a/api/src/main/java/com/coze/openapi/client/workflows/run/RunWorkflowReq.java +++ b/api/src/main/java/com/coze/openapi/client/workflows/run/RunWorkflowReq.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.workflows.run; import java.util.Map; @@ -18,35 +19,35 @@ @NoArgsConstructor @AllArgsConstructor public class RunWorkflowReq extends BaseReq { - /* - * The ID of the workflow, which should have been published. - * */ - @NonNull - @JsonProperty("workflow_id") - private String workflowID; - - /* - * Input parameters and their values for the starting node of the workflow. You can view the - * list of parameters on the arrangement page of the specified workflow. - * */ - private Map parameters; - - /* - * The associated Bot ID required for some workflow executions, - * such as workflows with database nodes, variable nodes, etc. - * */ - @JsonProperty("bot_id") - private String botID; - - /* - * Used to specify some additional fields in the format of Map[String][String] - * */ - @JsonProperty("ext") - private Map ext; - - /* - * Whether to run asynchronously. - * */ - @JsonProperty("is_async") - private Boolean isAsync; + /* + * The ID of the workflow, which should have been published. + * */ + @NonNull + @JsonProperty("workflow_id") + private String workflowID; + + /* + * Input parameters and their values for the starting node of the workflow. You can view the + * list of parameters on the arrangement page of the specified workflow. + * */ + private Map parameters; + + /* + * The associated Bot ID required for some workflow executions, + * such as workflows with database nodes, variable nodes, etc. + * */ + @JsonProperty("bot_id") + private String botID; + + /* + * Used to specify some additional fields in the format of Map[String][String] + * */ + @JsonProperty("ext") + private Map ext; + + /* + * Whether to run asynchronously. + * */ + @JsonProperty("is_async") + private Boolean isAsync; } diff --git a/api/src/main/java/com/coze/openapi/client/workflows/run/RunWorkflowResp.java b/api/src/main/java/com/coze/openapi/client/workflows/run/RunWorkflowResp.java index 718f767a..999815f9 100644 --- a/api/src/main/java/com/coze/openapi/client/workflows/run/RunWorkflowResp.java +++ b/api/src/main/java/com/coze/openapi/client/workflows/run/RunWorkflowResp.java @@ -1,7 +1,9 @@ +/* (C)2024 */ package com.coze.openapi.client.workflows.run; import com.coze.openapi.client.common.BaseResponse; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.*; import lombok.experimental.SuperBuilder; @@ -12,25 +14,27 @@ @AllArgsConstructor @ToString(callSuper = true) public class RunWorkflowResp extends BaseResponse { - /* - Execution ID of asynchronous execution. Only returned when the workflow is executed - asynchronously (is_async=true). You can use execute_id to call the Query Workflow - Asynchronous Execution Result API to obtain the final execution result of the workflow. - * */ - @JsonProperty("execute_id") - private String executeID; + /* + Execution ID of asynchronous execution. Only returned when the workflow is executed + asynchronously (is_async=true). You can use execute_id to call the Query Workflow + Asynchronous Execution Result API to obtain the final execution result of the workflow. + * */ + @JsonProperty("execute_id") + private String executeID; + + /* + Workflow execution result, usually a JSON serialized string. In some scenarios, a + string with a non-JSON structure may be returned. + * */ + @JsonProperty("data") + private String data; + + @JsonProperty("debug_url") + private String debugURL; - /* - Workflow execution result, usually a JSON serialized string. In some scenarios, a - string with a non-JSON structure may be returned. - * */ - @JsonProperty("data") - private String data; + @JsonProperty("token") + private Integer token; - @JsonProperty("debug_url") - private String debugURL; - @JsonProperty("token") - private Integer token; - @JsonProperty("cost") - private String cost; + @JsonProperty("cost") + private String cost; } diff --git a/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowEvent.java b/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowEvent.java index 7eff2ec8..57e3b9ec 100644 --- a/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowEvent.java +++ b/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowEvent.java @@ -1,9 +1,11 @@ +/* (C)2024 */ package com.coze.openapi.client.workflows.run.model; import java.util.Map; import com.coze.openapi.client.common.BaseResp; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; @@ -16,83 +18,75 @@ @EqualsAndHashCode(callSuper = true) @ToString(callSuper = true) public class WorkflowEvent extends BaseResp { - /** - * The event ID of this message in the interface response. It starts from 0. - */ - @JsonProperty("id") - private int id; + /** The event ID of this message in the interface response. It starts from 0. */ + @JsonProperty("id") + private int id; - /** - * The current streaming data packet event. - */ - @JsonProperty("event") - private WorkflowEventType event; + /** The current streaming data packet event. */ + @JsonProperty("event") + private WorkflowEventType event; - @JsonProperty("message") - private WorkflowEventMessage message; + @JsonProperty("message") + private WorkflowEventMessage message; - @JsonProperty("interrupt") - private WorkflowEventInterrupt interrupt; + @JsonProperty("interrupt") + private WorkflowEventInterrupt interrupt; - @JsonProperty("error") - private WorkflowEventError error; + @JsonProperty("error") + private WorkflowEventError error; - private static WorkflowEvent parseWorkflowEventMessage(Integer id, String data, String logID) { - WorkflowEventMessage message = WorkflowEventMessage.fromJson(data); - return WorkflowEvent.builder() - .id(id) - .event(WorkflowEventType.MESSAGE) - .message(message) - .logID(logID) - .build(); - } + private static WorkflowEvent parseWorkflowEventMessage(Integer id, String data, String logID) { + WorkflowEventMessage message = WorkflowEventMessage.fromJson(data); + return WorkflowEvent.builder() + .id(id) + .event(WorkflowEventType.MESSAGE) + .message(message) + .logID(logID) + .build(); + } - private static WorkflowEvent parseWorkflowEventInterrupt(Integer id, String data, String logID) { - WorkflowEventInterrupt interrupt = WorkflowEventInterrupt.fromJson(data); - return WorkflowEvent.builder() - .id(id) - .event(WorkflowEventType.INTERRUPT) - .interrupt(interrupt) - .logID(logID) - .build(); - } + private static WorkflowEvent parseWorkflowEventInterrupt(Integer id, String data, String logID) { + WorkflowEventInterrupt interrupt = WorkflowEventInterrupt.fromJson(data); + return WorkflowEvent.builder() + .id(id) + .event(WorkflowEventType.INTERRUPT) + .interrupt(interrupt) + .logID(logID) + .build(); + } - private static WorkflowEvent parseWorkflowEventError(Integer id, String data, String logID) { - WorkflowEventError error = WorkflowEventError.fromJson(data); - return WorkflowEvent.builder() - .id(id) - .event(WorkflowEventType.ERROR) - .error(error) - .logID(logID) - .build(); - } + private static WorkflowEvent parseWorkflowEventError(Integer id, String data, String logID) { + WorkflowEventError error = WorkflowEventError.fromJson(data); + return WorkflowEvent.builder() + .id(id) + .event(WorkflowEventType.ERROR) + .error(error) + .logID(logID) + .build(); + } - private static WorkflowEvent parseWorkflowEventDone(Integer id, String logID) { - return WorkflowEvent.builder() - .id(id) - .event(WorkflowEventType.DONE) - .logID(logID) - .build(); - } + private static WorkflowEvent parseWorkflowEventDone(Integer id, String logID) { + return WorkflowEvent.builder().id(id).event(WorkflowEventType.DONE).logID(logID).build(); + } - public static WorkflowEvent parseEvent(Map eventLine, String logID) { - Integer id = Integer.parseInt(eventLine.get("id")); - WorkflowEventType event = WorkflowEventType.fromString(eventLine.get("event")); - String data = eventLine.get("data"); + public static WorkflowEvent parseEvent(Map eventLine, String logID) { + Integer id = Integer.parseInt(eventLine.get("id")); + WorkflowEventType event = WorkflowEventType.fromString(eventLine.get("event")); + String data = eventLine.get("data"); - if (WorkflowEventType.MESSAGE.equals(event)) { - return parseWorkflowEventMessage(id, data, logID); - } else if (WorkflowEventType.INTERRUPT.equals(event)) { - return parseWorkflowEventInterrupt(id, data, logID); - } else if (WorkflowEventType.ERROR.equals(event)) { - return parseWorkflowEventError(id, data, logID); - } else if (WorkflowEventType.DONE.equals(event)) { - return parseWorkflowEventDone(id, logID); - } - return parseWorkflowEventMessage(id, data, logID); + if (WorkflowEventType.MESSAGE.equals(event)) { + return parseWorkflowEventMessage(id, data, logID); + } else if (WorkflowEventType.INTERRUPT.equals(event)) { + return parseWorkflowEventInterrupt(id, data, logID); + } else if (WorkflowEventType.ERROR.equals(event)) { + return parseWorkflowEventError(id, data, logID); + } else if (WorkflowEventType.DONE.equals(event)) { + return parseWorkflowEventDone(id, logID); } + return parseWorkflowEventMessage(id, data, logID); + } - public boolean isDone() { - return WorkflowEventType.DONE.equals(this.event); - } -} + public boolean isDone() { + return WorkflowEventType.DONE.equals(this.event); + } +} diff --git a/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowEventError.java b/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowEventError.java index 8edf5ce0..7c8ca7ec 100644 --- a/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowEventError.java +++ b/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowEventError.java @@ -1,7 +1,9 @@ +/* (C)2024 */ package com.coze.openapi.client.workflows.run.model; import com.coze.openapi.service.utils.Utils; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -12,20 +14,18 @@ @NoArgsConstructor @AllArgsConstructor public class WorkflowEventError { - /** - * Status code. 0 represents a successful API call. Other values indicate that the call has failed. You can - * determine the detailed reason for the error through the error_message field. - */ - @JsonProperty("error_code") - private int errorCode; + /** + * Status code. 0 represents a successful API call. Other values indicate that the call has + * failed. You can determine the detailed reason for the error through the error_message field. + */ + @JsonProperty("error_code") + private int errorCode; - /** - * Status message. You can get detailed error information when the API call fails. - */ - @JsonProperty("error_message") - private String errorMessage; + /** Status message. You can get detailed error information when the API call fails. */ + @JsonProperty("error_message") + private String errorMessage; - public static WorkflowEventError fromJson(String data) { - return Utils.fromJson(data, WorkflowEventError.class); - } -} \ No newline at end of file + public static WorkflowEventError fromJson(String data) { + return Utils.fromJson(data, WorkflowEventError.class); + } +} diff --git a/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowEventInterrupt.java b/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowEventInterrupt.java index 57b2072e..880d24c3 100644 --- a/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowEventInterrupt.java +++ b/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowEventInterrupt.java @@ -1,7 +1,9 @@ +/* (C)2024 */ package com.coze.openapi.client.workflows.run.model; import com.coze.openapi.service.utils.Utils; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -12,19 +14,15 @@ @NoArgsConstructor @AllArgsConstructor public class WorkflowEventInterrupt { - /** - * The content of interruption event. - */ - @JsonProperty("interrupt_data") - private WorkflowEventInterruptData interruptData; + /** The content of interruption event. */ + @JsonProperty("interrupt_data") + private WorkflowEventInterruptData interruptData; - /** - * The name of the node that outputs the message, such as "Question". - */ - @JsonProperty("node_title") - private String nodeTitle; + /** The name of the node that outputs the message, such as "Question". */ + @JsonProperty("node_title") + private String nodeTitle; - public static WorkflowEventInterrupt fromJson(String data) { - return Utils.fromJson(data, WorkflowEventInterrupt.class); - } -} \ No newline at end of file + public static WorkflowEventInterrupt fromJson(String data) { + return Utils.fromJson(data, WorkflowEventInterrupt.class); + } +} diff --git a/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowEventInterruptData.java b/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowEventInterruptData.java index d86c046d..fbc17c98 100644 --- a/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowEventInterruptData.java +++ b/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowEventInterruptData.java @@ -1,6 +1,8 @@ +/* (C)2024 */ package com.coze.openapi.client.workflows.run.model; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -11,15 +13,11 @@ @NoArgsConstructor @AllArgsConstructor public class WorkflowEventInterruptData { - /** - * The workflow interruption event ID, which should be passed back when resuming the workflow. - */ - @JsonProperty("event_id") - private String eventID; + /** The workflow interruption event ID, which should be passed back when resuming the workflow. */ + @JsonProperty("event_id") + private String eventID; - /** - * The type of workflow interruption, which should be passed back when resuming the workflow. - */ - @JsonProperty("type") - private int type; + /** The type of workflow interruption, which should be passed back when resuming the workflow. */ + @JsonProperty("type") + private int type; } diff --git a/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowEventMessage.java b/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowEventMessage.java index 37169058..46e31717 100644 --- a/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowEventMessage.java +++ b/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowEventMessage.java @@ -1,5 +1,8 @@ +/* (C)2024 */ package com.coze.openapi.client.workflows.run.model; +import java.util.Map; + import com.coze.openapi.service.utils.Utils; import com.fasterxml.jackson.annotation.JsonProperty; @@ -8,45 +11,35 @@ import lombok.Data; import lombok.NoArgsConstructor; -import java.util.Map; - @Data @Builder @NoArgsConstructor @AllArgsConstructor public class WorkflowEventMessage { - /** - * The content of the streamed output message. - */ - @JsonProperty("content") - private String content; - - /** - * The name of the node that outputs the message, such as the message node or end node. - */ - @JsonProperty("node_title") - private String nodeTitle; - - /** - * The message ID of this message within the node, starting at 0, for example, the 5th message of the message node. - */ - @JsonProperty("node_seq_id") - private String nodeSeqID; - - /** - * Whether the current message is the last data packet for this node. - */ - @JsonProperty("node_is_finish") - private boolean nodeIsFinish; - - /** - * Additional fields. - */ - @JsonProperty("ext") - private Map ext; - - - public static WorkflowEventMessage fromJson(String data) { - return Utils.fromJson(data, WorkflowEventMessage.class); - } -} \ No newline at end of file + /** The content of the streamed output message. */ + @JsonProperty("content") + private String content; + + /** The name of the node that outputs the message, such as the message node or end node. */ + @JsonProperty("node_title") + private String nodeTitle; + + /** + * The message ID of this message within the node, starting at 0, for example, the 5th message of + * the message node. + */ + @JsonProperty("node_seq_id") + private String nodeSeqID; + + /** Whether the current message is the last data packet for this node. */ + @JsonProperty("node_is_finish") + private boolean nodeIsFinish; + + /** Additional fields. */ + @JsonProperty("ext") + private Map ext; + + public static WorkflowEventMessage fromJson(String data) { + return Utils.fromJson(data, WorkflowEventMessage.class); + } +} diff --git a/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowEventType.java b/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowEventType.java index 7aab1017..a3fadb65 100644 --- a/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowEventType.java +++ b/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowEventType.java @@ -1,57 +1,55 @@ +/* (C)2024 */ package com.coze.openapi.client.workflows.run.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; + import lombok.AllArgsConstructor; import lombok.Getter; -/** - * Workflow event types. - */ +/** Workflow event types. */ @Getter @AllArgsConstructor public class WorkflowEventType { - /** - * The output message from the workflow node, such as the output message from - * the message node or end node. You can view the specific message content in data. - */ - public static final WorkflowEventType MESSAGE = new WorkflowEventType("Message"); - - /** - * An error has occurred. You can view the error_code and error_message in data to - * troubleshoot the issue. - */ - public static final WorkflowEventType ERROR = new WorkflowEventType("Error"); - - /** - * End. Indicates the end of the workflow execution, where data is empty. - */ - public static final WorkflowEventType DONE = new WorkflowEventType("Done"); - - /** - * Interruption. Indicates the workflow has been interrupted, where the data field - * contains specific interruption information. - */ - public static final WorkflowEventType INTERRUPT = new WorkflowEventType("Interrupt"); - - private final String value; - - @JsonValue - public String getValue() { - return value; + /** + * The output message from the workflow node, such as the output message from the message node or + * end node. You can view the specific message content in data. + */ + public static final WorkflowEventType MESSAGE = new WorkflowEventType("Message"); + + /** + * An error has occurred. You can view the error_code and error_message in data to troubleshoot + * the issue. + */ + public static final WorkflowEventType ERROR = new WorkflowEventType("Error"); + + /** End. Indicates the end of the workflow execution, where data is empty. */ + public static final WorkflowEventType DONE = new WorkflowEventType("Done"); + + /** + * Interruption. Indicates the workflow has been interrupted, where the data field contains + * specific interruption information. + */ + public static final WorkflowEventType INTERRUPT = new WorkflowEventType("Interrupt"); + + private final String value; + + @JsonValue + public String getValue() { + return value; + } + + @JsonCreator + public static WorkflowEventType fromString(String value) { + if (value == null) { + return new WorkflowEventType(""); } - @JsonCreator - public static WorkflowEventType fromString(String value) { - if (value == null) { - return new WorkflowEventType(""); - } - - if (value.equals(MESSAGE.getValue())) return MESSAGE; - if (value.equals(ERROR.getValue())) return ERROR; - if (value.equals(DONE.getValue())) return DONE; - if (value.equals(INTERRUPT.getValue())) return INTERRUPT; - - return new WorkflowEventType(value); - } -} \ No newline at end of file + if (value.equals(MESSAGE.getValue())) return MESSAGE; + if (value.equals(ERROR.getValue())) return ERROR; + if (value.equals(DONE.getValue())) return DONE; + if (value.equals(INTERRUPT.getValue())) return INTERRUPT; + + return new WorkflowEventType(value); + } +} diff --git a/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowExecuteStatus.java b/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowExecuteStatus.java index 191d611b..0ffddbff 100644 --- a/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowExecuteStatus.java +++ b/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowExecuteStatus.java @@ -1,48 +1,42 @@ +/* (C)2024 */ package com.coze.openapi.client.workflows.run.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; + import lombok.AllArgsConstructor; import lombok.Getter; -/** - * Execution status of the workflow. - */ +/** Execution status of the workflow. */ @Getter @AllArgsConstructor public class WorkflowExecuteStatus { - /** - * Execution succeeded. - */ - public static final WorkflowExecuteStatus SUCCESS = new WorkflowExecuteStatus("Success"); - - /** - * Execution in progress. - */ - public static final WorkflowExecuteStatus RUNNING = new WorkflowExecuteStatus("Running"); - - /** - * Execution failed. - */ - public static final WorkflowExecuteStatus FAIL = new WorkflowExecuteStatus("Fail"); - - private final String value; - - @JsonValue - public String getValue() { - return value; - } + /** Execution succeeded. */ + public static final WorkflowExecuteStatus SUCCESS = new WorkflowExecuteStatus("Success"); + + /** Execution in progress. */ + public static final WorkflowExecuteStatus RUNNING = new WorkflowExecuteStatus("Running"); + + /** Execution failed. */ + public static final WorkflowExecuteStatus FAIL = new WorkflowExecuteStatus("Fail"); - @JsonCreator - public static WorkflowExecuteStatus fromString(String value) { - if (value == null) { - return new WorkflowExecuteStatus(""); - } - - if (value.equals(SUCCESS.getValue())) return SUCCESS; - if (value.equals(RUNNING.getValue())) return RUNNING; - if (value.equals(FAIL.getValue())) return FAIL; - - return new WorkflowExecuteStatus(value); + private final String value; + + @JsonValue + public String getValue() { + return value; + } + + @JsonCreator + public static WorkflowExecuteStatus fromString(String value) { + if (value == null) { + return new WorkflowExecuteStatus(""); } -} \ No newline at end of file + + if (value.equals(SUCCESS.getValue())) return SUCCESS; + if (value.equals(RUNNING.getValue())) return RUNNING; + if (value.equals(FAIL.getValue())) return FAIL; + + return new WorkflowExecuteStatus(value); + } +} diff --git a/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowRunHistory.java b/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowRunHistory.java index 3964cea6..bbdce988 100644 --- a/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowRunHistory.java +++ b/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowRunHistory.java @@ -1,6 +1,8 @@ +/* (C)2024 */ package com.coze.openapi.client.workflows.run.model; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -11,93 +13,79 @@ @NoArgsConstructor @AllArgsConstructor public class WorkflowRunHistory { - /** - * The ID of execute. - */ - @JsonProperty("execute_id") - private String executeID; + /** The ID of execute. */ + @JsonProperty("execute_id") + private String executeID; - /** - * Execute status: - * success: Execution succeeded. - * running: Execution in progress. - * fail: Execution failed. - */ - @JsonProperty("execute_status") - private WorkflowExecuteStatus executeStatus; + /** + * Execute status: success: Execution succeeded. running: Execution in progress. fail: Execution + * failed. + */ + @JsonProperty("execute_status") + private WorkflowExecuteStatus executeStatus; - /** - * The Bot ID specified when executing the workflow. Returns 0 if no Bot ID was specified. - */ - @JsonProperty("bot_id") - private String botID; + /** The Bot ID specified when executing the workflow. Returns 0 if no Bot ID was specified. */ + @JsonProperty("bot_id") + private String botID; - /** - * The release connector ID of the agent. By default, only the Agent as API connector is - * displayed, and the connector ID is 1024. - */ - @JsonProperty("connector_id") - private String connectorID; + /** + * The release connector ID of the agent. By default, only the Agent as API connector is + * displayed, and the connector ID is 1024. + */ + @JsonProperty("connector_id") + private String connectorID; - /** - * User ID, the user_id specified by the ext field when executing the workflow. If not - * specified, the token applicant's button ID is returned. - */ - @JsonProperty("connector_uid") - private String connectorUid; + /** + * User ID, the user_id specified by the ext field when executing the workflow. If not specified, + * the token applicant's button ID is returned. + */ + @JsonProperty("connector_uid") + private String connectorUid; - /** - * How the workflow runs: - * 0: Synchronous operation. - * 1: Streaming operation. - * 2: Asynchronous operation. - */ - @JsonProperty("run_mode") - private WorkflowRunMode runMode; + /** + * How the workflow runs: 0: Synchronous operation. 1: Streaming operation. 2: Asynchronous + * operation. + */ + @JsonProperty("run_mode") + private WorkflowRunMode runMode; - /** - * The Log ID of the asynchronously running workflow. If the workflow is executed abnormally, - * you can contact the service team to troubleshoot the problem through the Log ID. - */ - @JsonProperty("logid") - private String logid; + /** + * The Log ID of the asynchronously running workflow. If the workflow is executed abnormally, you + * can contact the service team to troubleshoot the problem through the Log ID. + */ + @JsonProperty("logid") + private String logid; - /** - * The start time of the workflow, in Unix time timestamp format, in seconds. - */ - @JsonProperty("create_time") - private int createTime; + /** The start time of the workflow, in Unix time timestamp format, in seconds. */ + @JsonProperty("create_time") + private int createTime; - /** - * The workflow resume running time, in Unix time timestamp format, in seconds. - */ - @JsonProperty("update_time") - private int updateTime; + /** The workflow resume running time, in Unix time timestamp format, in seconds. */ + @JsonProperty("update_time") + private int updateTime; - /** - * The output of the workflow is usually a JSON serialized string, but it may also be a - * non-JSON structured string. - */ - @JsonProperty("output") - private String output; + /** + * The output of the workflow is usually a JSON serialized string, but it may also be a non-JSON + * structured string. + */ + @JsonProperty("output") + private String output; - /** - * Status code. 0 represents a successful API call. Other values indicate that the call has failed. You can - * determine the detailed reason for the error through the error_message field. - */ - @JsonProperty("error_code") - private int errorCode; + /** + * Status code. 0 represents a successful API call. Other values indicate that the call has + * failed. You can determine the detailed reason for the error through the error_message field. + */ + @JsonProperty("error_code") + private int errorCode; - /** - * Status message. You can get detailed error information when the API call fails. - */ - @JsonProperty("error_message") - private String errorMessage; + /** Status message. You can get detailed error information when the API call fails. */ + @JsonProperty("error_message") + private String errorMessage; - /** - * Workflow trial run debugging page. Visit this page to view the running results, input - * and output information of each workflow node. - */ - @JsonProperty("debug_url") - private String debugUrl; -} \ No newline at end of file + /** + * Workflow trial run debugging page. Visit this page to view the running results, input and + * output information of each workflow node. + */ + @JsonProperty("debug_url") + private String debugUrl; +} diff --git a/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowRunMode.java b/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowRunMode.java index 4f308e99..1ccb8b1a 100644 --- a/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowRunMode.java +++ b/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowRunMode.java @@ -1,45 +1,38 @@ +/* (C)2024 */ package com.coze.openapi.client.workflows.run.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -/** - * Run mode of the workflow. - */ +/** Run mode of the workflow. */ public enum WorkflowRunMode { - /** - * Synchronous operation. - */ - SYNCHRONOUS(0), + /** Synchronous operation. */ + SYNCHRONOUS(0), - /** - * Streaming operation. - */ - STREAMING(1), + /** Streaming operation. */ + STREAMING(1), - /** - * Asynchronous operation. - */ - ASYNCHRONOUS(2); + /** Asynchronous operation. */ + ASYNCHRONOUS(2); - private final int value; + private final int value; - WorkflowRunMode(int value) { - this.value = value; - } + WorkflowRunMode(int value) { + this.value = value; + } - @JsonValue - public int getValue() { - return value; - } + @JsonValue + public int getValue() { + return value; + } - @JsonCreator - public static WorkflowRunMode fromValue(int value) { - for (WorkflowRunMode mode : WorkflowRunMode.values()) { - if (mode.value == value) { - return mode; - } - } - throw new IllegalArgumentException("Unknown WorkflowRunMode: " + value); + @JsonCreator + public static WorkflowRunMode fromValue(int value) { + for (WorkflowRunMode mode : WorkflowRunMode.values()) { + if (mode.value == value) { + return mode; + } } -} \ No newline at end of file + throw new IllegalArgumentException("Unknown WorkflowRunMode: " + value); + } +} diff --git a/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowRunResult.java b/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowRunResult.java index 3cf6ec67..ae4f4f85 100644 --- a/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowRunResult.java +++ b/api/src/main/java/com/coze/openapi/client/workflows/run/model/WorkflowRunResult.java @@ -1,6 +1,8 @@ +/* (C)2024 */ package com.coze.openapi.client.workflows.run.model; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; @@ -11,21 +13,21 @@ @NoArgsConstructor @AllArgsConstructor public class WorkflowRunResult { - @JsonProperty("debug_url") - private String debugUrl; + @JsonProperty("debug_url") + private String debugUrl; - /** - * Workflow execution result, usually a JSON serialized string. In some scenarios, a - * string with a non-JSON structure may be returned. - */ - @JsonProperty("data") - private String data; + /** + * Workflow execution result, usually a JSON serialized string. In some scenarios, a string with a + * non-JSON structure may be returned. + */ + @JsonProperty("data") + private String data; - /** - * Execution ID of asynchronous execution. Only returned when the workflow is executed - * asynchronously (is_async=true). You can use execute_id to call the Query Workflow - * Asynchronous Execution Result API to obtain the final execution result of the workflow. - */ - @JsonProperty("execute_id") - private String executeID; -} \ No newline at end of file + /** + * Execution ID of asynchronous execution. Only returned when the workflow is executed + * asynchronously (is_async=true). You can use execute_id to call the Query Workflow Asynchronous + * Execution Result API to obtain the final execution result of the workflow. + */ + @JsonProperty("execute_id") + private String executeID; +} diff --git a/api/src/main/java/com/coze/openapi/client/workspace/ListWorkspaceReq.java b/api/src/main/java/com/coze/openapi/client/workspace/ListWorkspaceReq.java index 9d1d5fc8..c27b19da 100644 --- a/api/src/main/java/com/coze/openapi/client/workspace/ListWorkspaceReq.java +++ b/api/src/main/java/com/coze/openapi/client/workspace/ListWorkspaceReq.java @@ -1,5 +1,9 @@ +/* (C)2024 */ package com.coze.openapi.client.workspace; +import com.coze.openapi.client.common.BaseReq; + +import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; @@ -7,24 +11,16 @@ import lombok.NonNull; import lombok.experimental.SuperBuilder; -import com.coze.openapi.client.common.BaseReq; - -import lombok.AllArgsConstructor; - @Data @EqualsAndHashCode(callSuper = true) @SuperBuilder @NoArgsConstructor @AllArgsConstructor public class ListWorkspaceReq extends BaseReq { - @NonNull - @Builder.Default - private Integer pageNum = 1; - @NonNull - @Builder.Default - private Integer pageSize = 20; + @NonNull @Builder.Default private Integer pageNum = 1; + @NonNull @Builder.Default private Integer pageSize = 20; - public static ListWorkspaceReq of(Integer pageNum, Integer pageSize) { - return ListWorkspaceReq.builder().pageNum(pageNum).pageSize(pageSize).build(); - } + public static ListWorkspaceReq of(Integer pageNum, Integer pageSize) { + return ListWorkspaceReq.builder().pageNum(pageNum).pageSize(pageSize).build(); + } } diff --git a/api/src/main/java/com/coze/openapi/client/workspace/ListWorkspaceResp.java b/api/src/main/java/com/coze/openapi/client/workspace/ListWorkspaceResp.java index 253d35df..ada803c7 100644 --- a/api/src/main/java/com/coze/openapi/client/workspace/ListWorkspaceResp.java +++ b/api/src/main/java/com/coze/openapi/client/workspace/ListWorkspaceResp.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.client.workspace; import java.util.List; @@ -17,10 +18,9 @@ @AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) public class ListWorkspaceResp { - @JsonProperty("total_count") - private Integer totalCount; + @JsonProperty("total_count") + private Integer totalCount; - @JsonProperty("workspaces") - private List workspaces; - -} \ No newline at end of file + @JsonProperty("workspaces") + private List workspaces; +} diff --git a/api/src/main/java/com/coze/openapi/client/workspace/model/Workspace.java b/api/src/main/java/com/coze/openapi/client/workspace/model/Workspace.java index 34a6aefc..f4c5bb44 100644 --- a/api/src/main/java/com/coze/openapi/client/workspace/model/Workspace.java +++ b/api/src/main/java/com/coze/openapi/client/workspace/model/Workspace.java @@ -1,24 +1,26 @@ +/* (C)2024 */ package com.coze.openapi.client.workspace.model; import com.fasterxml.jackson.annotation.JsonProperty; + import lombok.Builder; import lombok.Data; @Data @Builder public class Workspace { - @JsonProperty("id") - private String id; - - @JsonProperty("name") - private String name; - - @JsonProperty("icon_url") - private String iconUrl; - - @JsonProperty("role_type") - private WorkspaceRoleType roleType; - - @JsonProperty("workspace_type") - private WorkspaceType workspaceType; -} \ No newline at end of file + @JsonProperty("id") + private String id; + + @JsonProperty("name") + private String name; + + @JsonProperty("icon_url") + private String iconUrl; + + @JsonProperty("role_type") + private WorkspaceRoleType roleType; + + @JsonProperty("workspace_type") + private WorkspaceType workspaceType; +} diff --git a/api/src/main/java/com/coze/openapi/client/workspace/model/WorkspaceRoleType.java b/api/src/main/java/com/coze/openapi/client/workspace/model/WorkspaceRoleType.java index fbc7c20e..a7e825c4 100644 --- a/api/src/main/java/com/coze/openapi/client/workspace/model/WorkspaceRoleType.java +++ b/api/src/main/java/com/coze/openapi/client/workspace/model/WorkspaceRoleType.java @@ -1,31 +1,32 @@ +/* (C)2024 */ package com.coze.openapi.client.workspace.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; + import lombok.Getter; @Getter public class WorkspaceRoleType { - public static final WorkspaceRoleType OWNER = new WorkspaceRoleType("owner"); - public static final WorkspaceRoleType ADMIN = new WorkspaceRoleType("admin"); - public static final WorkspaceRoleType MEMBER = new WorkspaceRoleType("member"); + public static final WorkspaceRoleType OWNER = new WorkspaceRoleType("owner"); + public static final WorkspaceRoleType ADMIN = new WorkspaceRoleType("admin"); + public static final WorkspaceRoleType MEMBER = new WorkspaceRoleType("member"); - @JsonValue - private final String value; + @JsonValue private final String value; - private WorkspaceRoleType(String value) { - this.value = value; - } + private WorkspaceRoleType(String value) { + this.value = value; + } - @JsonCreator - public static WorkspaceRoleType fromString(String value) { - if ("owner".equals(value)) { - return OWNER; - } else if ("admin".equals(value)) { - return ADMIN; - } else if ("member".equals(value)) { - return MEMBER; - } - return new WorkspaceRoleType(value); + @JsonCreator + public static WorkspaceRoleType fromString(String value) { + if ("owner".equals(value)) { + return OWNER; + } else if ("admin".equals(value)) { + return ADMIN; + } else if ("member".equals(value)) { + return MEMBER; } -} \ No newline at end of file + return new WorkspaceRoleType(value); + } +} diff --git a/api/src/main/java/com/coze/openapi/client/workspace/model/WorkspaceType.java b/api/src/main/java/com/coze/openapi/client/workspace/model/WorkspaceType.java index 48db28a1..569591bc 100644 --- a/api/src/main/java/com/coze/openapi/client/workspace/model/WorkspaceType.java +++ b/api/src/main/java/com/coze/openapi/client/workspace/model/WorkspaceType.java @@ -1,28 +1,29 @@ +/* (C)2024 */ package com.coze.openapi.client.workspace.model; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; + import lombok.Getter; @Getter public class WorkspaceType { - public static final WorkspaceType PERSONAL = new WorkspaceType("personal"); - public static final WorkspaceType TEAM = new WorkspaceType("team"); + public static final WorkspaceType PERSONAL = new WorkspaceType("personal"); + public static final WorkspaceType TEAM = new WorkspaceType("team"); - @JsonValue - private final String value; + @JsonValue private final String value; - private WorkspaceType(String value) { - this.value = value; - } + private WorkspaceType(String value) { + this.value = value; + } - @JsonCreator - public static WorkspaceType fromString(String value) { - if ("personal".equals(value)) { - return PERSONAL; - } else if ("team".equals(value)) { - return TEAM; - } - return new WorkspaceType(value); + @JsonCreator + public static WorkspaceType fromString(String value) { + if ("personal".equals(value)) { + return PERSONAL; + } else if ("team".equals(value)) { + return TEAM; } -} \ No newline at end of file + return new WorkspaceType(value); + } +} diff --git a/api/src/main/java/com/coze/openapi/service/auth/Auth.java b/api/src/main/java/com/coze/openapi/service/auth/Auth.java index 36c175b4..dc7333db 100644 --- a/api/src/main/java/com/coze/openapi/service/auth/Auth.java +++ b/api/src/main/java/com/coze/openapi/service/auth/Auth.java @@ -1,42 +1,43 @@ +/* (C)2024 */ package com.coze.openapi.service.auth; import com.coze.openapi.client.auth.OAuthToken; -public abstract class Auth { - - protected String accessToken; - protected String refreshToken; - protected long expiresIn; - protected OAuthClient client; - - - protected boolean needRefresh(){ - // accessToken 为空代表第一次请求,需要刷新token - return accessToken == null || System.currentTimeMillis() / 1000 > expiresIn; - } - - /** - * 获取token类型 - * @return token类型,默认返回 Bearer - */ - public String tokenType() { - return "Bearer"; - } - - /** - * 获取token - * @return token - */ - public String token(){ - if (!this.needRefresh()) { - return accessToken; - } - - OAuthToken resp = this.client.refreshToken(this.refreshToken); - this.accessToken = resp.getAccessToken(); - this.refreshToken = resp.getRefreshToken(); - this.expiresIn = resp.getExpiresIn(); - return this.accessToken; +public abstract class Auth { + + protected String accessToken; + protected String refreshToken; + protected long expiresIn; + protected OAuthClient client; + + protected boolean needRefresh() { + // accessToken 为空代表第一次请求,需要刷新token + return accessToken == null || System.currentTimeMillis() / 1000 > expiresIn; + } + + /** + * 获取token类型 + * + * @return token类型,默认返回 Bearer + */ + public String tokenType() { + return "Bearer"; + } + + /** + * 获取token + * + * @return token + */ + public String token() { + if (!this.needRefresh()) { + return accessToken; } + OAuthToken resp = this.client.refreshToken(this.refreshToken); + this.accessToken = resp.getAccessToken(); + this.refreshToken = resp.getRefreshToken(); + this.expiresIn = resp.getExpiresIn(); + return this.accessToken; + } } diff --git a/api/src/main/java/com/coze/openapi/service/auth/AuthLogFactory.java b/api/src/main/java/com/coze/openapi/service/auth/AuthLogFactory.java index 42af59ad..1ef11ec4 100644 --- a/api/src/main/java/com/coze/openapi/service/auth/AuthLogFactory.java +++ b/api/src/main/java/com/coze/openapi/service/auth/AuthLogFactory.java @@ -1,18 +1,19 @@ +/* (C)2024 */ package com.coze.openapi.service.auth; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AuthLogFactory { - private static volatile Logger logger = LoggerFactory.getLogger("com.coze.openapi.auth"); - - public static Logger getLogger() { - return logger; - } - - public static void setLogger(Logger customLogger) { - if (customLogger != null) { - logger = customLogger; - } + private static volatile Logger logger = LoggerFactory.getLogger("com.coze.openapi.auth"); + + public static Logger getLogger() { + return logger; + } + + public static void setLogger(Logger customLogger) { + if (customLogger != null) { + logger = customLogger; } -} \ No newline at end of file + } +} diff --git a/api/src/main/java/com/coze/openapi/service/auth/DeviceOAuthClient.java b/api/src/main/java/com/coze/openapi/service/auth/DeviceOAuthClient.java index df3414f0..ccb68127 100644 --- a/api/src/main/java/com/coze/openapi/service/auth/DeviceOAuthClient.java +++ b/api/src/main/java/com/coze/openapi/service/auth/DeviceOAuthClient.java @@ -1,91 +1,92 @@ +/* (C)2024 */ package com.coze.openapi.service.auth; +import java.util.concurrent.TimeUnit; + +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; + import com.coze.openapi.client.auth.*; import com.coze.openapi.client.exception.AuthErrorCode; import com.coze.openapi.client.exception.CozeAuthException; +public class DeviceOAuthClient extends OAuthClient { -import org.jetbrains.annotations.NotNull; -import org.slf4j.Logger; - -import java.util.concurrent.TimeUnit; + protected DeviceOAuthClient(DeviceOAuthBuilder builder) { + super(builder); + } -public class DeviceOAuthClient extends OAuthClient{ + private static final Logger logger = AuthLogFactory.getLogger(); - protected DeviceOAuthClient(DeviceOAuthBuilder builder) { - super(builder); - } + public DeviceAuthResp getDeviceCode() { + DeviceAuthReq req = DeviceAuthReq.builder().clientID(this.clientID).build(); + DeviceAuthResp resp = execute(this.api.device(req)); + resp.setVerificationURL(resp.getVerificationURI() + "?user_code=" + resp.getUserCode()); + return resp; + } - private static final Logger logger = AuthLogFactory.getLogger(); - public DeviceAuthResp getDeviceCode(){ - DeviceAuthReq req = DeviceAuthReq.builder().clientID(this.clientID).build(); - DeviceAuthResp resp = execute(this.api.device(req)); - resp.setVerificationURL(resp.getVerificationURI() + "?user_code=" + resp.getUserCode()); - return resp; - } + public DeviceAuthResp getDeviceCode(@NotNull String workspaceID) { + DeviceAuthReq req = DeviceAuthReq.builder().clientID(this.clientID).build(); + DeviceAuthResp resp = execute(this.api.device(workspaceID, req)); + resp.setVerificationURL(resp.getVerificationURI() + "?user_code=" + resp.getUserCode()); + return resp; + } - public DeviceAuthResp getDeviceCode(@NotNull String workspaceID){ - DeviceAuthReq req = DeviceAuthReq.builder().clientID(this.clientID).build(); - DeviceAuthResp resp = execute(this.api.device(workspaceID, req)); - resp.setVerificationURL(resp.getVerificationURI() + "?user_code=" + resp.getUserCode()); - return resp; - } + public OAuthToken getAccessToken(String deviceCode) throws Exception { + return getAccessToken(deviceCode, false); + } - public OAuthToken getAccessToken(String deviceCode) throws Exception { - return getAccessToken(deviceCode, false); + public OAuthToken getAccessToken(String deviceCode, boolean poll) throws Exception { + GetAccessTokenReq.GetAccessTokenReqBuilder builder = GetAccessTokenReq.builder(); + builder + .clientID(this.clientID) + .grantType(GrantType.DeviceCode.getValue()) + .deviceCode(deviceCode); + if (!poll) { + return super.getAccessToken(null, builder.build()); // secret 放进去 } - - public OAuthToken getAccessToken(String deviceCode, boolean poll) throws Exception{ - GetAccessTokenReq.GetAccessTokenReqBuilder builder = GetAccessTokenReq.builder(); - builder.clientID(this.clientID). - grantType(GrantType.DeviceCode.getValue()).deviceCode(deviceCode); - if (!poll){ - return super.getAccessToken(null, builder.build()); // secret 放进去 + int interval = 5; + while (true) { + try { + return super.getAccessToken(null, builder.build()); + } catch (CozeAuthException e) { + if (AuthErrorCode.AUTHORIZATION_PENDING.equals(e.getCode())) { + logger.info("Authorization pending, sleep " + interval + " seconds"); + } else if (AuthErrorCode.SLOW_DOWN.equals(e.getCode())) { + if (interval < 30) { + interval += 5; + } + logger.info("Slow down, sleep " + interval + " seconds"); + } else { + throw e; } - int interval = 5; - while (true){ - try{ - return super.getAccessToken(null, builder.build()); - }catch (CozeAuthException e){ - if (AuthErrorCode.AUTHORIZATION_PENDING.equals(e.getCode())){ - logger.info("Authorization pending, sleep " + interval + " seconds"); - } else if (AuthErrorCode.SLOW_DOWN.equals(e.getCode())){ - if (interval < 30){ - interval+=5; - } - logger.info("Slow down, sleep " + interval + " seconds"); - } else { - throw e; - } - try { - TimeUnit.SECONDS.sleep(interval); - } catch (InterruptedException ie) { - logger.warn("Interrupted while sleeping", ie); - Thread.currentThread().interrupt(); // 恢复中断状态 - throw ie; - } - }catch (Exception e){ - throw e; - } + try { + TimeUnit.SECONDS.sleep(interval); + } catch (InterruptedException ie) { + logger.warn("Interrupted while sleeping", ie); + Thread.currentThread().interrupt(); // 恢复中断状态 + throw ie; } + } catch (Exception e) { + throw e; + } } + } + @Override + public OAuthToken refreshToken(String refreshToken) { + return super.refreshAccessToken(refreshToken, this.clientSecret); + } - + public static class DeviceOAuthBuilder extends OAuthBuilder { @Override - public OAuthToken refreshToken(String refreshToken) { - return super.refreshAccessToken(refreshToken, this.clientSecret); + protected DeviceOAuthBuilder self() { + return this; } - public static class DeviceOAuthBuilder extends OAuthBuilder { - @Override - protected DeviceOAuthBuilder self() { - return this; - } - - @Override - public DeviceOAuthClient build() { - return new DeviceOAuthClient(this); - } + @Override + public DeviceOAuthClient build() { + return new DeviceOAuthClient(this); } + } } diff --git a/api/src/main/java/com/coze/openapi/service/auth/JWTOAuth.java b/api/src/main/java/com/coze/openapi/service/auth/JWTOAuth.java index dce01d2f..eaeb2a2a 100644 --- a/api/src/main/java/com/coze/openapi/service/auth/JWTOAuth.java +++ b/api/src/main/java/com/coze/openapi/service/auth/JWTOAuth.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.service.auth; import java.util.Objects; @@ -9,33 +10,29 @@ import lombok.Builder; import lombok.NonNull; - @Builder @AllArgsConstructor public class JWTOAuth extends Auth { - private Integer ttl; - private String sessionName; - private Scope scope; - @NonNull - private JWTOAuthClient jwtClient; - - public JWTOAuth(JWTOAuthClient client) { - Objects.requireNonNull(client, "client must not be null"); - this.jwtClient = client; - this.ttl = client.getTtl(); + private Integer ttl; + private String sessionName; + private Scope scope; + @NonNull private JWTOAuthClient jwtClient; + + public JWTOAuth(JWTOAuthClient client) { + Objects.requireNonNull(client, "client must not be null"); + this.jwtClient = client; + this.ttl = client.getTtl(); + } + + @Override + public String token() { + if (!this.needRefresh()) { + return accessToken; } - - @Override - public String token(){ - if (!this.needRefresh()) { - return accessToken; - } - OAuthToken resp = this.jwtClient.getAccessToken(this.ttl, this.scope, this.sessionName); - this.accessToken = resp.getAccessToken(); - this.expiresIn = resp.getExpiresIn(); - return this.accessToken; - } - - + OAuthToken resp = this.jwtClient.getAccessToken(this.ttl, this.scope, this.sessionName); + this.accessToken = resp.getAccessToken(); + this.expiresIn = resp.getExpiresIn(); + return this.accessToken; + } } diff --git a/api/src/main/java/com/coze/openapi/service/auth/JWTOAuthClient.java b/api/src/main/java/com/coze/openapi/service/auth/JWTOAuthClient.java index 17ddf933..0b977e2f 100644 --- a/api/src/main/java/com/coze/openapi/service/auth/JWTOAuthClient.java +++ b/api/src/main/java/com/coze/openapi/service/auth/JWTOAuthClient.java @@ -1,158 +1,154 @@ +/* (C)2024 */ package com.coze.openapi.service.auth; -import com.coze.openapi.client.auth.GetAccessTokenReq; -import com.coze.openapi.client.auth.OAuthToken; -import com.coze.openapi.client.auth.GrantType; -import com.coze.openapi.client.auth.scope.Scope; - +import java.security.KeyFactory; +import java.security.PrivateKey; +import java.security.spec.PKCS8EncodedKeySpec; +import java.util.Base64; import java.util.Date; +import java.util.HashMap; import java.util.Map; +import com.coze.openapi.client.auth.GetAccessTokenReq; +import com.coze.openapi.client.auth.GrantType; +import com.coze.openapi.client.auth.OAuthToken; +import com.coze.openapi.client.auth.scope.Scope; import com.coze.openapi.service.utils.Utils; + import io.jsonwebtoken.JwtBuilder; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import lombok.Getter; -import okhttp3.OkHttpClient; -import java.security.KeyFactory; -import java.security.PrivateKey; -import java.util.Base64; -import java.util.HashMap; -import java.security.spec.PKCS8EncodedKeySpec; - -public class JWTOAuthClient extends OAuthClient{ - @Getter - private final Integer ttl; - private final PrivateKey privateKey; - private final String publicKey; - - protected JWTOAuthClient(JWTOAuthBuilder builder) throws Exception{ - super(builder); - this.privateKey = parsePrivateKey(builder.privateKey); - this.publicKey = builder.publicKey; - this.ttl = builder.ttl; +public class JWTOAuthClient extends OAuthClient { + @Getter private final Integer ttl; + private final PrivateKey privateKey; + private final String publicKey; + + protected JWTOAuthClient(JWTOAuthBuilder builder) throws Exception { + super(builder); + this.privateKey = parsePrivateKey(builder.privateKey); + this.publicKey = builder.publicKey; + this.ttl = builder.ttl; + } + + @Override + public OAuthToken refreshToken(String refreshToken) { + return null; + } + + public OAuthToken getAccessToken() { + return doGetAccessToken(this.ttl, null, null); + } + + public OAuthToken getAccessToken(Integer ttl) { + return doGetAccessToken(ttl, null, null); + } + + public OAuthToken getAccessToken(Scope scope) { + return doGetAccessToken(this.ttl, scope, null); + } + + public OAuthToken getAccessToken(Integer ttl, Scope scope) { + return doGetAccessToken(ttl, scope, null); + } + + public OAuthToken getAccessToken(String sessionName) { + return doGetAccessToken(this.ttl, null, sessionName); + } + + public OAuthToken getAccessToken(Integer ttl, String sessionName) { + return doGetAccessToken(ttl, null, sessionName); + } + + public OAuthToken getAccessToken(Scope scope, String sessionName) { + return doGetAccessToken(this.ttl, scope, sessionName); + } + + public OAuthToken getAccessToken(Integer ttl, Scope scope, String sessionName) { + return doGetAccessToken(ttl, scope, sessionName); + } + + private OAuthToken doGetAccessToken(Integer ttl, Scope scope, String sessionName) { + GetAccessTokenReq.GetAccessTokenReqBuilder builder = GetAccessTokenReq.builder(); + builder.grantType(GrantType.JWTCode.getValue()).durationSeconds(ttl).scope(scope); + + return getAccessToken(this.generateJWT(ttl, sessionName), builder.build()); + } + + private String generateJWT(int ttl, String sessionName) { + try { + long now = System.currentTimeMillis() / 1000; + + // 构建 JWT header + Map header = new HashMap<>(); + header.put("alg", "RS256"); + header.put("typ", "JWT"); + header.put("kid", this.publicKey); + + JwtBuilder jwtBuilder = + Jwts.builder() + .setHeader(header) + .setIssuer(this.clientID) + .setAudience("api.coze.cn") + .setIssuedAt(new Date(now * 1000)) + .setExpiration(new Date((now + ttl) * 1000)) + .setId(Utils.genRandomSign(16)) + .signWith(privateKey, SignatureAlgorithm.RS256); + if (sessionName != null) { + jwtBuilder.claim("session_name", sessionName); + } + return jwtBuilder.compact(); + + } catch (Exception e) { + throw new RuntimeException("Failed to generate JWT", e); } - - @Override - public OAuthToken refreshToken(String refreshToken) { - return null; + } + + private PrivateKey parsePrivateKey(String privateKeyPEM) throws Exception { + String privateKeyContent = + privateKeyPEM + .replace("-----BEGIN PRIVATE KEY-----", "") + .replace("-----END PRIVATE KEY-----", "") + .replaceAll("\\s", ""); + + byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyContent); + PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes); + KeyFactory keyFactory = KeyFactory.getInstance("RSA"); + return keyFactory.generatePrivate(keySpec); + } + + public static class JWTOAuthBuilder extends OAuthBuilder { + private Integer ttl; + private String publicKey; + private String privateKey; + + public JWTOAuthBuilder publicKey(String publicKey) { + this.publicKey = publicKey; + return this; } - - public OAuthToken getAccessToken() { - return doGetAccessToken(this.ttl, null, null); - } - - public OAuthToken getAccessToken(Integer ttl) { - return doGetAccessToken(ttl, null, null); - } - - public OAuthToken getAccessToken(Scope scope) { - return doGetAccessToken(this.ttl, scope, null); - } - - public OAuthToken getAccessToken(Integer ttl, Scope scope) { - return doGetAccessToken(ttl, scope, null); - } - - public OAuthToken getAccessToken(String sessionName) { - return doGetAccessToken(this.ttl, null, sessionName); - } - - public OAuthToken getAccessToken(Integer ttl, String sessionName) { - return doGetAccessToken(ttl, null, sessionName); + public JWTOAuthBuilder ttl(Integer ttl) { + this.ttl = ttl; + return this; } - public OAuthToken getAccessToken(Scope scope, String sessionName) { - return doGetAccessToken(this.ttl, scope, sessionName); + public JWTOAuthBuilder privateKey(String privateKey) { + this.privateKey = privateKey; + return this; } - public OAuthToken getAccessToken(Integer ttl, Scope scope, String sessionName) { - return doGetAccessToken(ttl, scope, sessionName); - } - - private OAuthToken doGetAccessToken(Integer ttl, Scope scope, String sessionName) { - GetAccessTokenReq.GetAccessTokenReqBuilder builder = GetAccessTokenReq.builder(); - builder.grantType(GrantType.JWTCode.getValue()).durationSeconds(ttl).scope(scope); - - return getAccessToken(this.generateJWT(ttl, sessionName), builder.build()); - } - - private String generateJWT(int ttl, String sessionName) { - try { - long now = System.currentTimeMillis() / 1000; - - // 构建 JWT header - Map header = new HashMap<>(); - header.put("alg", "RS256"); - header.put("typ", "JWT"); - header.put("kid", this.publicKey); - - - JwtBuilder jwtBuilder = Jwts.builder() - .setHeader(header) - .setIssuer(this.clientID) - .setAudience("api.coze.cn") - .setIssuedAt(new Date(now * 1000)) - .setExpiration(new Date((now + ttl) * 1000)) - .setId(Utils.genRandomSign(16)) - .signWith(privateKey, SignatureAlgorithm.RS256); - if (sessionName != null) { - jwtBuilder.claim("session_name", sessionName); - } - return jwtBuilder.compact(); - - } catch (Exception e) { - throw new RuntimeException("Failed to generate JWT", e); - } - } - - - private PrivateKey parsePrivateKey(String privateKeyPEM) throws Exception { - String privateKeyContent = privateKeyPEM - .replace("-----BEGIN PRIVATE KEY-----", "") - .replace("-----END PRIVATE KEY-----", "") - .replaceAll("\\s", ""); - - byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyContent); - PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes); - KeyFactory keyFactory = KeyFactory.getInstance("RSA"); - return keyFactory.generatePrivate(keySpec); + @Override + protected JWTOAuthBuilder self() { + return this; } - public static class JWTOAuthBuilder extends OAuthBuilder { - private Integer ttl; - private String publicKey; - private String privateKey; - - public JWTOAuthBuilder publicKey(String publicKey) { - this.publicKey = publicKey; - return this; - } - - public JWTOAuthBuilder ttl(Integer ttl) { - this.ttl = ttl; - return this; - } - - public JWTOAuthBuilder privateKey(String privateKey) { - this.privateKey = privateKey; - return this; - } - - @Override - protected JWTOAuthBuilder self() { - return this; - } - - @Override - public JWTOAuthClient build() throws Exception { - if (this.ttl == null || this.ttl.equals(0)){ - this.ttl = 900; - } - return new JWTOAuthClient(this); - } + @Override + public JWTOAuthClient build() throws Exception { + if (this.ttl == null || this.ttl.equals(0)) { + this.ttl = 900; + } + return new JWTOAuthClient(this); } - + } } diff --git a/api/src/main/java/com/coze/openapi/service/auth/OAuthClient.java b/api/src/main/java/com/coze/openapi/service/auth/OAuthClient.java index c34ed439..faf5f3b5 100644 --- a/api/src/main/java/com/coze/openapi/service/auth/OAuthClient.java +++ b/api/src/main/java/com/coze/openapi/service/auth/OAuthClient.java @@ -1,314 +1,330 @@ +/* (C)2024 */ package com.coze.openapi.service.auth; +import static com.coze.openapi.service.config.Consts.*; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; + import com.coze.openapi.api.CozeAuthAPI; import com.coze.openapi.client.auth.GetAccessTokenReq; +import com.coze.openapi.client.auth.GrantType; import com.coze.openapi.client.auth.OAuthToken; import com.coze.openapi.client.common.BaseResp; -import com.coze.openapi.client.auth.GrantType; -import com.coze.openapi.client.exception.CozeError; import com.coze.openapi.client.exception.CozeAuthException; -import com.coze.openapi.service.service.AuthenticationInterceptor; -import com.coze.openapi.service.service.TimeoutInterceptor; +import com.coze.openapi.client.exception.CozeError; import com.coze.openapi.service.utils.UserAgentInterceptor; import com.coze.openapi.service.utils.Utils; import com.fasterxml.jackson.databind.ObjectMapper; + import io.reactivex.Single; import okhttp3.ConnectionPool; import okhttp3.OkHttpClient; import okhttp3.ResponseBody; -import org.jetbrains.annotations.NotNull; -import org.slf4j.Logger; - import retrofit2.HttpException; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.jackson.JacksonConverterFactory; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import static com.coze.openapi.service.config.Consts.*; - public abstract class OAuthClient { - private static final String AuthorizeHeader ="Authorization"; - private static final ObjectMapper mapper = Utils.defaultObjectMapper(); - - protected final String clientSecret; - protected final String clientID; - protected final String baseURL; - protected final CozeAuthAPI api; - protected final ExecutorService executorService; - - protected OAuthClient(OAuthBuilder builder) { - builder.init(); - this.clientSecret = builder.clientSecret; - this.clientID = builder.clientID; - this.baseURL = builder.baseURL; - - Retrofit retrofit = defaultRetrofit(builder.client, mapper, getBaseURL()); - - this.api = retrofit.create(CozeAuthAPI.class); - this.executorService = builder.client.dispatcher().executorService(); + private static final String AuthorizeHeader = "Authorization"; + private static final ObjectMapper mapper = Utils.defaultObjectMapper(); + + protected final String clientSecret; + protected final String clientID; + protected final String baseURL; + protected final CozeAuthAPI api; + protected final ExecutorService executorService; + + protected OAuthClient(OAuthBuilder builder) { + builder.init(); + this.clientSecret = builder.clientSecret; + this.clientID = builder.clientID; + this.baseURL = builder.baseURL; + + Retrofit retrofit = defaultRetrofit(builder.client, mapper, getBaseURL()); + + this.api = retrofit.create(CozeAuthAPI.class); + this.executorService = builder.client.dispatcher().executorService(); + } + + protected String getOAuthURL(@NotNull String redirectURI, String state) { + return this._getOAuthURL(redirectURI, state, null, null, null); + } + + protected String getOAuthURL( + @NotNull String redirectURI, String state, @NotNull String codeChallenge) { + return this._getOAuthURL(redirectURI, state, codeChallenge, null, null); + } + + protected String getOAuthURL( + @NotNull String redirectURI, + String state, + @NotNull String codeChallenge, + @NotNull String codeChallengeMethod) { + return this._getOAuthURL(redirectURI, state, codeChallenge, codeChallengeMethod, null); + } + + protected String getOAuthURL( + @NotNull String redirectURI, + String state, + @NotNull String codeChallenge, + @NotNull String codeChallengeMethod, + @NotNull String workspaceID) { + return this._getOAuthURL(redirectURI, state, codeChallenge, codeChallengeMethod, workspaceID); + } + + private String _getOAuthURL( + String redirectUri, + String state, + String codeChallenge, + String codeChallengeMethod, + String workspaceID) { + + Map params = new HashMap<>(); + params.put("response_type", "code"); + if (this.clientID != null) { + params.put("client_id", this.clientID); } - - - protected String getOAuthURL(@NotNull String redirectURI, String state) { - return this._getOAuthURL(redirectURI, state, null, null, null); + if (redirectUri != null) { + params.put("redirect_uri", redirectUri); } - - protected String getOAuthURL(@NotNull String redirectURI, String state, @NotNull String codeChallenge) { - return this._getOAuthURL(redirectURI, state, codeChallenge, null, null); + if (state != null) { + params.put("state", state); } - - protected String getOAuthURL(@NotNull String redirectURI, String state, @NotNull String codeChallenge, @NotNull String codeChallengeMethod) { - return this._getOAuthURL(redirectURI, state, codeChallenge, codeChallengeMethod, null); + if (codeChallenge != null) { + params.put("code_challenge", codeChallenge); + } + if (codeChallengeMethod != null) { + params.put("code_challenge_method", codeChallengeMethod); } - protected String getOAuthURL(@NotNull String redirectURI, String state, @NotNull String codeChallenge, @NotNull String codeChallengeMethod, @NotNull String workspaceID) { - return this._getOAuthURL(redirectURI, state, codeChallenge, codeChallengeMethod, workspaceID); + String uri = baseURL + "/api/permission/oauth2/authorize"; + if (workspaceID != null) { + uri = + baseURL + String.format("/api/permission/oauth2/workspace_id/%s/authorize", workspaceID); } - private String _getOAuthURL( - String redirectUri, - String state, - String codeChallenge, - String codeChallengeMethod, - String workspaceID){ - - Map params = new HashMap<>(); - params.put("response_type", "code"); - if (this.clientID!= null){ - params.put("client_id", this.clientID); - } - if (redirectUri != null) { - params.put("redirect_uri", redirectUri); - } - if (state != null){ - params.put("state", state); - } - if (codeChallenge != null) { - params.put("code_challenge", codeChallenge); - } - if (codeChallengeMethod != null) { - params.put("code_challenge_method", codeChallengeMethod); + String queryString = + params.entrySet().stream() + .map( + entry -> { + try { + return URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8.toString()) + + "=" + + URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.toString()); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + }) + .collect(Collectors.joining("&")); + + return uri + "?" + queryString; + } + + protected Retrofit defaultRetrofit(OkHttpClient client, ObjectMapper mapper, String baseURL) { + return new Retrofit.Builder() + .baseUrl(baseURL) + .client(client) + .addConverterFactory(JacksonConverterFactory.create(mapper)) + .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) + .build(); + } + + private String getBaseURL() { + return this.baseURL; + } + + protected OAuthToken getAccessToken( + GrantType type, String code, String clientSecret, String redirectURI) { + return request(code, clientSecret, type, null, redirectURI); + } + + protected OAuthToken getAccessToken(GrantType type, String clientSecret, String redirectURI) { + return request(null, clientSecret, type, null, redirectURI); + } + + protected OAuthToken getAccessToken(String secret, GetAccessTokenReq req) { + Map headers = new HashMap<>(); + if (secret != null) { + headers.put(AuthorizeHeader, String.format("Bearer %s", secret)); + } + return execute(this.api.retrieve(headers, req)); + } + + protected OAuthToken refreshAccessToken(String refreshToken, String clientSecret) { + return request(null, clientSecret, GrantType.RefreshToken, refreshToken, null); + } + + protected OAuthToken refreshAccessToken(String refreshToken) { + return request(null, null, GrantType.RefreshToken, refreshToken, null); + } + + public void shutdownExecutor() { + Objects.requireNonNull( + this.executorService, "executorService must be set in order to shut down"); + this.executorService.shutdown(); + } + + private OAuthToken request( + String code, String secret, GrantType grantType, String refreshToken, String redirectURI) { + GetAccessTokenReq.GetAccessTokenReqBuilder builder = GetAccessTokenReq.builder(); + builder + .clientID(this.clientID) + .grantType(grantType.getValue()) + .code(code) + .refreshToken(refreshToken) + .redirectUri(redirectURI); + GetAccessTokenReq req = builder.build(); + + Map headers = new HashMap<>(); + if (secret != null) { + headers.put(AuthorizeHeader, String.format("Bearer %s", secret)); + } + return execute(this.api.retrieve(headers, req)); + } + + protected static T execute(Single> apiCall) { + try { + Response response = apiCall.blockingGet(); + if (!response.isSuccessful()) { + try (ResponseBody errorBody = response.errorBody()) { + if (errorBody == null) { + throw new HttpException(response); + } + String logID = Utils.getLogID(response); + String errStr = errorBody.string(); + CozeError error = mapper.readValue(errStr, CozeError.class); + throw new CozeAuthException(error, new HttpException(response), response.code(), logID); + } catch (IOException ex) { + throw new HttpException(response); } - - String uri = baseURL + "/api/permission/oauth2/authorize"; - if (workspaceID != null) { - uri = baseURL + String.format("/api/permission/oauth2/workspace_id/%s/authorize", workspaceID); + } + T body = response.body(); + if (body instanceof BaseResp) { + ((BaseResp) body).setLogID(Utils.getLogID(response)); + } + return body; + } catch (HttpException e) { + try (ResponseBody errorBody = e.response().errorBody()) { + if (errorBody == null) { + throw e; } + String logID = Utils.getLogID(e.response()); - String queryString = params.entrySet().stream() - .map(entry -> { - try { - return URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8.toString()) + "=" + - URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.toString()); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - }) - .collect(Collectors.joining("&")); + String errStr = e.response().errorBody().string(); - return uri + "?" + queryString; + CozeError error = mapper.readValue(errStr, CozeError.class); + throw new CozeAuthException(error, e, e.code(), logID); + } catch (IOException ex) { + // couldn't parse OpenAI error + throw e; + } } - - protected Retrofit defaultRetrofit(OkHttpClient client, ObjectMapper mapper, String baseURL) { - return new Retrofit.Builder() - .baseUrl(baseURL) - .client(client) - .addConverterFactory(JacksonConverterFactory.create(mapper)) - .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) - .build(); + } + + public abstract OAuthToken refreshToken(String refreshToken); + + public abstract static class OAuthBuilder> { + protected String clientID; + protected String clientSecret; + protected String baseURL; + protected int readTimeout; + protected int connectTimeout; + protected OkHttpClient client; + protected Logger logger; + + @SuppressWarnings("unchecked") + protected T self() { + return (T) this; } - private String getBaseURL(){ - return this.baseURL; + public T clientID(String clientID) { + this.clientID = clientID; + return self(); } - protected OAuthToken getAccessToken(GrantType type, String code, String clientSecret, String redirectURI) { - return request(code, clientSecret, type, null, redirectURI); + public T clientSecret(String clientSecret) { + this.clientSecret = clientSecret; + return self(); } - protected OAuthToken getAccessToken(GrantType type, String clientSecret, String redirectURI) { - return request(null, clientSecret, type, null, redirectURI); + public T baseURL(String baseURL) { + this.baseURL = baseURL; + return self(); } - protected OAuthToken getAccessToken(String secret, GetAccessTokenReq req) { - Map headers = new HashMap<>(); - if (secret != null){ - headers.put(AuthorizeHeader, String.format("Bearer %s", secret)); - } - return execute(this.api.retrieve(headers, req)); + public T readTimeout(int readTimeout) { + this.readTimeout = readTimeout; + return self(); } - protected OAuthToken refreshAccessToken(String refreshToken, String clientSecret) { - return request(null, clientSecret, GrantType.RefreshToken, refreshToken, null); + public T connectTimeout(int connectTimeout) { + this.connectTimeout = connectTimeout; + return self(); } - protected OAuthToken refreshAccessToken(String refreshToken) { - return request(null, null, GrantType.RefreshToken, refreshToken, null); + public T client(OkHttpClient client) { + this.client = client; + return self(); } - public void shutdownExecutor() { - Objects.requireNonNull(this.executorService, "executorService must be set in order to shut down"); - this.executorService.shutdown(); + public T logger(Logger logger) { + this.logger = logger; + return self(); } - - private OAuthToken request(String code, String secret, GrantType grantType, String refreshToken, String redirectURI){ - GetAccessTokenReq.GetAccessTokenReqBuilder builder = GetAccessTokenReq.builder(); - builder.clientID(this.clientID). - grantType(grantType.getValue()). - code(code). - refreshToken(refreshToken). - redirectUri(redirectURI); - GetAccessTokenReq req = builder.build(); - - Map headers = new HashMap<>(); - if (secret != null){ - headers.put(AuthorizeHeader, String.format("Bearer %s", secret)); - } - return execute(this.api.retrieve(headers, req)); + public abstract OAuthClient build() throws Exception; + + protected T init() { + if (this.logger != null) { + AuthLogFactory.setLogger(this.logger); + } + if (this.baseURL == null || this.baseURL.isEmpty()) { + this.baseURL = COZE_COM_BASE_URL; + } + + if (this.readTimeout == 0) { + this.readTimeout = 5000; + } + + if (this.connectTimeout == 0) { + this.connectTimeout = 5000; + } + + if (this.client == null) { + this.client = + defaultClient( + Duration.ofMillis(this.readTimeout), Duration.ofMillis(this.connectTimeout)); + } else { + OkHttpClient.Builder builder = new OkHttpClient.Builder(client); + builder.addInterceptor(new UserAgentInterceptor()); + + this.client = builder.build(); + } + return this.self(); } - protected static T execute(Single> apiCall) { - try { - Response response = apiCall.blockingGet(); - if (!response.isSuccessful()) { - try (ResponseBody errorBody = response.errorBody()) { - if (errorBody == null) { - throw new HttpException(response); - } - String logID = Utils.getLogID(response); - String errStr = errorBody.string(); - CozeError error = mapper.readValue(errStr, CozeError.class); - throw new CozeAuthException(error, new HttpException(response), response.code(), logID); - } catch (IOException ex) { - throw new HttpException(response); - } - } - T body = response.body(); - if (body instanceof BaseResp) { - ((BaseResp) body).setLogID(Utils.getLogID(response)); - } - return body; - } catch (HttpException e) { - try (ResponseBody errorBody = e.response().errorBody()){ - if (errorBody == null) { - throw e; - } - String logID = Utils.getLogID(e.response()); - - String errStr = e.response().errorBody().string(); - - CozeError error = mapper.readValue(errStr, CozeError.class); - throw new CozeAuthException(error, e, e.code(), logID); - } catch (IOException ex) { - // couldn't parse OpenAI error - throw e; - } - } + protected OkHttpClient defaultClient(Duration readTimeout, Duration connectTimeout) { + return new OkHttpClient.Builder() + .connectionPool(new ConnectionPool(5, 1, TimeUnit.SECONDS)) + .readTimeout(readTimeout.toMillis(), TimeUnit.MILLISECONDS) + .connectTimeout(connectTimeout.toMillis(), TimeUnit.MILLISECONDS) + .addInterceptor(new UserAgentInterceptor()) + .build(); } - - public abstract OAuthToken refreshToken(String refreshToken); - - public static abstract class OAuthBuilder> { - protected String clientID; - protected String clientSecret; - protected String baseURL; - protected int readTimeout; - protected int connectTimeout; - protected OkHttpClient client; - protected Logger logger; - - @SuppressWarnings("unchecked") - protected T self() { - return (T) this; - } - - public T clientID(String clientID) { - this.clientID = clientID; - return self(); - } - - public T clientSecret(String clientSecret) { - this.clientSecret = clientSecret; - return self(); - } - - public T baseURL(String baseURL) { - this.baseURL = baseURL; - return self(); - } - - public T readTimeout(int readTimeout) { - this.readTimeout = readTimeout; - return self(); - } - - public T connectTimeout(int connectTimeout) { - this.connectTimeout = connectTimeout; - return self(); - } - - public T client(OkHttpClient client) { - this.client = client; - return self(); - } - - public T logger(Logger logger) { - this.logger = logger; - return self(); - } - - public abstract OAuthClient build() throws Exception; - - protected T init() { - if (this.logger != null){ - AuthLogFactory.setLogger(this.logger); - } - if (this.baseURL == null || this.baseURL.isEmpty()){ - this.baseURL = COZE_COM_BASE_URL; - } - - if (this.readTimeout == 0){ - this.readTimeout = 5000; - } - - if (this.connectTimeout == 0){ - this.connectTimeout = 5000; - } - - if (this.client == null){ - this.client = defaultClient(Duration.ofMillis(this.readTimeout), Duration.ofMillis(this.connectTimeout)); - }else { - OkHttpClient.Builder builder = new OkHttpClient.Builder(client); - builder.addInterceptor(new UserAgentInterceptor()); - - this.client = builder.build(); - } - return this.self(); - } - - protected OkHttpClient defaultClient(Duration readTimeout, Duration connectTimeout) { - return new OkHttpClient.Builder() - .connectionPool(new ConnectionPool(5, 1, TimeUnit.SECONDS)) - .readTimeout(readTimeout.toMillis(), TimeUnit.MILLISECONDS) - .connectTimeout(connectTimeout.toMillis(), TimeUnit.MILLISECONDS) - .addInterceptor(new UserAgentInterceptor()) - .build(); - } - } - - - + } } diff --git a/api/src/main/java/com/coze/openapi/service/auth/PKCEOAuthClient.java b/api/src/main/java/com/coze/openapi/service/auth/PKCEOAuthClient.java index 860a87da..ef0e101b 100644 --- a/api/src/main/java/com/coze/openapi/service/auth/PKCEOAuthClient.java +++ b/api/src/main/java/com/coze/openapi/service/auth/PKCEOAuthClient.java @@ -1,105 +1,128 @@ +/* (C)2024 */ package com.coze.openapi.service.auth; -import com.coze.openapi.client.auth.GetAccessTokenReq; -import com.coze.openapi.client.auth.OAuthToken; -import com.coze.openapi.client.auth.GrantType; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; -import com.coze.openapi.client.auth.GetPKCEAuthURLResp; -import com.coze.openapi.service.utils.Utils; -import lombok.Getter; - -import lombok.val; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -public class PKCEOAuthClient extends OAuthClient{ - - @Getter - public enum CodeChallengeMethod { - Plain("plain"), - S256("S256"); - - private final String value; - CodeChallengeMethod(String value) { - this.value = value; - } - } - - private static final int codeVerifierLen = 16; - - protected PKCEOAuthClient(PKCEOAuthBuilder builder) { - super(builder); - } +import com.coze.openapi.client.auth.GetAccessTokenReq; +import com.coze.openapi.client.auth.GetPKCEAuthURLResp; +import com.coze.openapi.client.auth.GrantType; +import com.coze.openapi.client.auth.OAuthToken; +import com.coze.openapi.service.utils.Utils; +import lombok.Getter; - public GetPKCEAuthURLResp genOAuthURL(@NotNull String redirectURI, String state) { - return genOAuthURL(redirectURI, state, CodeChallengeMethod.Plain); - } +public class PKCEOAuthClient extends OAuthClient { - public GetPKCEAuthURLResp genOAuthURL(@NotNull String redirectURI, String state, @NotNull String workspaceID) { - return genOAuthURL(redirectURI, state, CodeChallengeMethod.Plain, workspaceID); - } + @Getter + public enum CodeChallengeMethod { + Plain("plain"), + S256("S256"); - public GetPKCEAuthURLResp genOAuthURL(@NotNull String redirectURI, String state, @NotNull CodeChallengeMethod codeChallengeMethod) { - String codeVerifier = Utils.genRandomSign(codeVerifierLen); - String url = super.getOAuthURL(redirectURI, state, getCode(codeVerifier,codeChallengeMethod), codeChallengeMethod.getValue()); - return new GetPKCEAuthURLResp(codeVerifier, url); - } + private final String value; - public GetPKCEAuthURLResp genOAuthURL(@NotNull String redirectURI, String state, @NotNull CodeChallengeMethod codeChallengeMethod, @NotNull String workspaceID) { - String codeVerifier = Utils.genRandomSign(codeVerifierLen); - String url = super.getOAuthURL(redirectURI, state, getCode(codeVerifier,codeChallengeMethod), codeChallengeMethod.getValue(), workspaceID); - return new GetPKCEAuthURLResp(codeVerifier, url); + CodeChallengeMethod(String value) { + this.value = value; } - - private String getCode(@NotNull String codeVerifier, @NotNull CodeChallengeMethod codeChallengeMethod){ - String code = ""; - try{ - code = "plain".equals(codeChallengeMethod.getValue()) ?codeVerifier:genS256CodeChallenge(codeVerifier); - } catch (NoSuchAlgorithmException e) { - code = codeVerifier; - } - return code; + } + + private static final int codeVerifierLen = 16; + + protected PKCEOAuthClient(PKCEOAuthBuilder builder) { + super(builder); + } + + public GetPKCEAuthURLResp genOAuthURL(@NotNull String redirectURI, String state) { + return genOAuthURL(redirectURI, state, CodeChallengeMethod.Plain); + } + + public GetPKCEAuthURLResp genOAuthURL( + @NotNull String redirectURI, String state, @NotNull String workspaceID) { + return genOAuthURL(redirectURI, state, CodeChallengeMethod.Plain, workspaceID); + } + + public GetPKCEAuthURLResp genOAuthURL( + @NotNull String redirectURI, String state, @NotNull CodeChallengeMethod codeChallengeMethod) { + String codeVerifier = Utils.genRandomSign(codeVerifierLen); + String url = + super.getOAuthURL( + redirectURI, + state, + getCode(codeVerifier, codeChallengeMethod), + codeChallengeMethod.getValue()); + return new GetPKCEAuthURLResp(codeVerifier, url); + } + + public GetPKCEAuthURLResp genOAuthURL( + @NotNull String redirectURI, + String state, + @NotNull CodeChallengeMethod codeChallengeMethod, + @NotNull String workspaceID) { + String codeVerifier = Utils.genRandomSign(codeVerifierLen); + String url = + super.getOAuthURL( + redirectURI, + state, + getCode(codeVerifier, codeChallengeMethod), + codeChallengeMethod.getValue(), + workspaceID); + return new GetPKCEAuthURLResp(codeVerifier, url); + } + + private String getCode( + @NotNull String codeVerifier, @NotNull CodeChallengeMethod codeChallengeMethod) { + String code = ""; + try { + code = + "plain".equals(codeChallengeMethod.getValue()) + ? codeVerifier + : genS256CodeChallenge(codeVerifier); + } catch (NoSuchAlgorithmException e) { + code = codeVerifier; } - - public OAuthToken getAccessToken(@NotNull String code, @NotNull String redirectURI, @Nullable String codeVerifier) { - GetAccessTokenReq req = GetAccessTokenReq.builder() - .clientID(this.clientID) - .grantType(GrantType.AuthorizationCode.getValue()) - .code(code) - .redirectUri(redirectURI) - .codeVerifier(codeVerifier).build(); - return super.getAccessToken(null, req); - } - - + return code; + } + + public OAuthToken getAccessToken( + @NotNull String code, @NotNull String redirectURI, @Nullable String codeVerifier) { + GetAccessTokenReq req = + GetAccessTokenReq.builder() + .clientID(this.clientID) + .grantType(GrantType.AuthorizationCode.getValue()) + .code(code) + .redirectUri(redirectURI) + .codeVerifier(codeVerifier) + .build(); + return super.getAccessToken(null, req); + } + + @Override + public OAuthToken refreshToken(String refreshToken) { + return super.refreshAccessToken(refreshToken); + } + + public static String genS256CodeChallenge(String codeVerifier) throws NoSuchAlgorithmException { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + byte[] sha256Hash = digest.digest(codeVerifier.getBytes(StandardCharsets.US_ASCII)); + String codeChallenge = Base64.getUrlEncoder().withoutPadding().encodeToString(sha256Hash); + codeChallenge = codeChallenge.replace("=", ""); + return codeChallenge; + } + + public static class PKCEOAuthBuilder extends OAuthBuilder { @Override - public OAuthToken refreshToken(String refreshToken) { - return super.refreshAccessToken(refreshToken); + protected PKCEOAuthBuilder self() { + return this; } - public static String genS256CodeChallenge(String codeVerifier) throws NoSuchAlgorithmException { - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - byte[] sha256Hash = digest.digest(codeVerifier.getBytes(StandardCharsets.US_ASCII)); - String codeChallenge = Base64.getUrlEncoder().withoutPadding().encodeToString(sha256Hash); - codeChallenge = codeChallenge.replace("=", ""); - return codeChallenge; - } - - public static class PKCEOAuthBuilder extends OAuthBuilder { - @Override - protected PKCEOAuthBuilder self() { - return this; - } - - @Override - public PKCEOAuthClient build() { - return new PKCEOAuthClient(this); - } + @Override + public PKCEOAuthClient build() { + return new PKCEOAuthClient(this); } - + } } diff --git a/api/src/main/java/com/coze/openapi/service/auth/TokenAuth.java b/api/src/main/java/com/coze/openapi/service/auth/TokenAuth.java index 5a36419c..75e2eb50 100644 --- a/api/src/main/java/com/coze/openapi/service/auth/TokenAuth.java +++ b/api/src/main/java/com/coze/openapi/service/auth/TokenAuth.java @@ -1,15 +1,15 @@ +/* (C)2024 */ package com.coze.openapi.service.auth; public class TokenAuth extends Auth { - private final String accessToken; + private final String accessToken; - public TokenAuth(String accessToken) { - this.accessToken = accessToken; - } + public TokenAuth(String accessToken) { + this.accessToken = accessToken; + } - - @Override - public String token() { - return accessToken; - } + @Override + public String token() { + return accessToken; + } } diff --git a/api/src/main/java/com/coze/openapi/service/auth/WebOAuthClient.java b/api/src/main/java/com/coze/openapi/service/auth/WebOAuthClient.java index 823ac207..64c48215 100644 --- a/api/src/main/java/com/coze/openapi/service/auth/WebOAuthClient.java +++ b/api/src/main/java/com/coze/openapi/service/auth/WebOAuthClient.java @@ -1,47 +1,46 @@ +/* (C)2024 */ package com.coze.openapi.service.auth; - -import com.coze.openapi.client.auth.OAuthToken; +import org.jetbrains.annotations.NotNull; import com.coze.openapi.client.auth.GrantType; -import org.jetbrains.annotations.NotNull; +import com.coze.openapi.client.auth.OAuthToken; public class WebOAuthClient extends OAuthClient { - protected WebOAuthClient(OAuthBuilder builder) { - super(builder); - } - + protected WebOAuthClient(OAuthBuilder builder) { + super(builder); + } - @Override - public String getOAuthURL(@NotNull String redirectURI, String state) { - return super.getOAuthURL(redirectURI, state); - } + @Override + public String getOAuthURL(@NotNull String redirectURI, String state) { + return super.getOAuthURL(redirectURI, state); + } - @Override - public String getOAuthURL(@NotNull String redirectURI, String state, @NotNull String workspaceID) { - return super.getOAuthURL(redirectURI, state, workspaceID); - } + @Override + public String getOAuthURL( + @NotNull String redirectURI, String state, @NotNull String workspaceID) { + return super.getOAuthURL(redirectURI, state, workspaceID); + } - public OAuthToken getAccessToken(String code, String redirectURI) { - return super.getAccessToken(GrantType.AuthorizationCode, code, this.clientSecret, redirectURI); - } + public OAuthToken getAccessToken(String code, String redirectURI) { + return super.getAccessToken(GrantType.AuthorizationCode, code, this.clientSecret, redirectURI); + } + @Override + public OAuthToken refreshToken(String refreshToken) { + return super.refreshAccessToken(refreshToken, this.clientSecret); + } + public static class WebOAuthBuilder extends OAuthBuilder { @Override - public OAuthToken refreshToken(String refreshToken) { - return super.refreshAccessToken(refreshToken, this.clientSecret); + protected WebOAuthBuilder self() { + return this; } - public static class WebOAuthBuilder extends OAuthBuilder { - @Override - protected WebOAuthBuilder self() { - return this; - } - - @Override - public WebOAuthClient build() { - return new WebOAuthClient(this); - } + @Override + public WebOAuthClient build() { + return new WebOAuthClient(this); } + } } diff --git a/api/src/main/java/com/coze/openapi/service/config/Consts.java b/api/src/main/java/com/coze/openapi/service/config/Consts.java index 6d759ce6..d47a35fc 100644 --- a/api/src/main/java/com/coze/openapi/service/config/Consts.java +++ b/api/src/main/java/com/coze/openapi/service/config/Consts.java @@ -1,7 +1,7 @@ +/* (C)2024 */ package com.coze.openapi.service.config; public class Consts { - public static final String COZE_COM_BASE_URL = "https://api.coze.com"; - public static final String COZE_CN_BASE_URL = "https://api.coze.cn"; - + public static final String COZE_COM_BASE_URL = "https://api.coze.com"; + public static final String COZE_CN_BASE_URL = "https://api.coze.cn"; } diff --git a/api/src/main/java/com/coze/openapi/service/service/APIResponseCallAdapter.java b/api/src/main/java/com/coze/openapi/service/service/APIResponseCallAdapter.java index e6edcf56..8195e568 100644 --- a/api/src/main/java/com/coze/openapi/service/service/APIResponseCallAdapter.java +++ b/api/src/main/java/com/coze/openapi/service/service/APIResponseCallAdapter.java @@ -1,112 +1,118 @@ +/* (C)2024 */ package com.coze.openapi.service.service; +import java.io.IOException; +import java.lang.reflect.Type; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import com.coze.openapi.client.common.BaseResponse; import com.coze.openapi.client.exception.CozeApiExcetion; import com.coze.openapi.service.utils.Utils; + import okhttp3.Request; import okhttp3.ResponseBody; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import retrofit2.*; -import java.io.IOException; -import java.lang.reflect.Type; - public class APIResponseCallAdapter implements CallAdapter> { - private static final Logger logger = LoggerFactory.getLogger(APIResponseCallAdapter.class); - private final Type responseType; - - public APIResponseCallAdapter(Type responseType) { - this.responseType = responseType; - } - - @Override - public Type responseType() { - return responseType; - } - - @Override - public Call adapt(Call call) { - return new Call() { - @Override - public Response execute() throws IOException { - Response response = call.execute(); - if (!response.isSuccessful()) { - logger.warn("HTTP error: " + response.code() + " " + response.message()); - String errStr = "http exception"; - try { - ResponseBody errorBody = response.errorBody(); - if (errorBody != null) { - errStr = errorBody.string(); - BaseResponse baseResponse = Utils.fromJson(errStr, BaseResponse.class); - throw new CozeApiExcetion(baseResponse.getCode(), baseResponse.getMsg(), Utils.getLogID(response)); - } - throw new CozeApiExcetion(response.code(), "http exception", Utils.getLogID(response)); - } catch (Exception e) { - // 解析json 失败会走到这,直接返回全量信息 - throw new CozeApiExcetion(response.code(), errStr, Utils.getLogID(response)); - } - } + private static final Logger logger = LoggerFactory.getLogger(APIResponseCallAdapter.class); + private final Type responseType; - R body = response.body(); - if (body instanceof BaseResponse) { - BaseResponse baseResponse = (BaseResponse) body; - if (baseResponse.getCode() != 0) { - logger.warn("API error: " + baseResponse.getCode() + " " + baseResponse.getMsg()); - throw new CozeApiExcetion(baseResponse.getCode(), baseResponse.getMsg(), Utils.getLogID(response)); - } - } - return response; - } + public APIResponseCallAdapter(Type responseType) { + this.responseType = responseType; + } - @Override - public void enqueue(Callback callback) { - call.enqueue(new Callback() { - @Override - public void onResponse(Call call, Response response) { - try { - callback.onResponse(call, execute()); - } catch (Exception e) { - onFailure(call, e); - } - } - - @Override - public void onFailure(Call call, Throwable t) { - callback.onFailure(call, t); - } - }); - } + @Override + public Type responseType() { + return responseType; + } - @Override - public boolean isExecuted() { - return call.isExecuted(); + @Override + public Call adapt(Call call) { + return new Call() { + @Override + public Response execute() throws IOException { + Response response = call.execute(); + if (!response.isSuccessful()) { + logger.warn("HTTP error: " + response.code() + " " + response.message()); + String errStr = "http exception"; + try { + ResponseBody errorBody = response.errorBody(); + if (errorBody != null) { + errStr = errorBody.string(); + BaseResponse baseResponse = Utils.fromJson(errStr, BaseResponse.class); + throw new CozeApiExcetion( + baseResponse.getCode(), baseResponse.getMsg(), Utils.getLogID(response)); } + throw new CozeApiExcetion(response.code(), "http exception", Utils.getLogID(response)); + } catch (Exception e) { + // 解析json 失败会走到这,直接返回全量信息 + throw new CozeApiExcetion(response.code(), errStr, Utils.getLogID(response)); + } + } - @Override - public void cancel() { - call.cancel(); - } + R body = response.body(); + if (body instanceof BaseResponse) { + BaseResponse baseResponse = (BaseResponse) body; + if (baseResponse.getCode() != 0) { + logger.warn("API error: " + baseResponse.getCode() + " " + baseResponse.getMsg()); + throw new CozeApiExcetion( + baseResponse.getCode(), baseResponse.getMsg(), Utils.getLogID(response)); + } + } + return response; + } - @Override - public boolean isCanceled() { - return call.isCanceled(); - } + @Override + public void enqueue(Callback callback) { + call.enqueue( + new Callback() { + @Override + public void onResponse(Call call, Response response) { + try { + callback.onResponse(call, execute()); + } catch (Exception e) { + onFailure(call, e); + } + } - @Override - public Call clone() { - return adapt(call.clone()); - } + @Override + public void onFailure(Call call, Throwable t) { + callback.onFailure(call, t); + } + }); + } - @Override - public Request request() { - return call.request(); - } + @Override + public boolean isExecuted() { + return call.isExecuted(); + } - @Override - public okio.Timeout timeout() { - return call.timeout(); - } - }; - } -} \ No newline at end of file + @Override + public void cancel() { + call.cancel(); + } + + @Override + public boolean isCanceled() { + return call.isCanceled(); + } + + @Override + public Call clone() { + return adapt(call.clone()); + } + + @Override + public Request request() { + return call.request(); + } + + @Override + public okio.Timeout timeout() { + return call.timeout(); + } + }; + } +} diff --git a/api/src/main/java/com/coze/openapi/service/service/APIResponseCallAdapterFactory.java b/api/src/main/java/com/coze/openapi/service/service/APIResponseCallAdapterFactory.java index 3d0bae7f..fba8e1c2 100644 --- a/api/src/main/java/com/coze/openapi/service/service/APIResponseCallAdapterFactory.java +++ b/api/src/main/java/com/coze/openapi/service/service/APIResponseCallAdapterFactory.java @@ -1,31 +1,32 @@ +/* (C)2024 */ package com.coze.openapi.service.service; +import java.lang.annotation.Annotation; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; + import retrofit2.Call; import retrofit2.CallAdapter; import retrofit2.Retrofit; import retrofit2.http.Streaming; -import java.lang.annotation.Annotation; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; - public class APIResponseCallAdapterFactory extends CallAdapter.Factory { - @Override - public CallAdapter get(Type returnType, Annotation[] annotations, Retrofit retrofit) { - if (getRawType(returnType) != Call.class) { - return null; - } - for (Annotation annotation : annotations) { - // 流式接口不用这个 adapter 处理 - if (annotation instanceof Streaming ) { - return null; - } - } - Type responseType = getParameterUpperBound(0, (ParameterizedType) returnType); - return new APIResponseCallAdapter<>(responseType); + @Override + public CallAdapter get(Type returnType, Annotation[] annotations, Retrofit retrofit) { + if (getRawType(returnType) != Call.class) { + return null; } - - public static APIResponseCallAdapterFactory create() { - return new APIResponseCallAdapterFactory(); + for (Annotation annotation : annotations) { + // 流式接口不用这个 adapter 处理 + if (annotation instanceof Streaming) { + return null; + } } + Type responseType = getParameterUpperBound(0, (ParameterizedType) returnType); + return new APIResponseCallAdapter<>(responseType); + } + + public static APIResponseCallAdapterFactory create() { + return new APIResponseCallAdapterFactory(); + } } diff --git a/api/src/main/java/com/coze/openapi/service/service/AuthenticationInterceptor.java b/api/src/main/java/com/coze/openapi/service/service/AuthenticationInterceptor.java index e1409296..26a4f2b3 100644 --- a/api/src/main/java/com/coze/openapi/service/service/AuthenticationInterceptor.java +++ b/api/src/main/java/com/coze/openapi/service/service/AuthenticationInterceptor.java @@ -1,28 +1,31 @@ +/* (C)2024 */ package com.coze.openapi.service.service; -import okhttp3.Interceptor; -import okhttp3.Request; -import okhttp3.Response; - import java.io.IOException; import java.util.Objects; import com.coze.openapi.service.auth.Auth; -public class AuthenticationInterceptor implements Interceptor{ - private final Auth auth; +import okhttp3.Interceptor; +import okhttp3.Request; +import okhttp3.Response; + +public class AuthenticationInterceptor implements Interceptor { + private final Auth auth; - AuthenticationInterceptor(Auth auth) { - Objects.requireNonNull(auth, "Auth required"); - this.auth = auth; - } + AuthenticationInterceptor(Auth auth) { + Objects.requireNonNull(auth, "Auth required"); + this.auth = auth; + } - @Override - public Response intercept(Chain chain) throws IOException { - Request request = chain.request() - .newBuilder() - .header("Authorization", auth.tokenType() + " " + auth.token()) - .build(); - return chain.proceed(request); - } + @Override + public Response intercept(Chain chain) throws IOException { + Request request = + chain + .request() + .newBuilder() + .header("Authorization", auth.tokenType() + " " + auth.token()) + .build(); + return chain.proceed(request); + } } diff --git a/api/src/main/java/com/coze/openapi/service/service/CozeAPI.java b/api/src/main/java/com/coze/openapi/service/service/CozeAPI.java index 2e05ea3b..e29fcaa8 100644 --- a/api/src/main/java/com/coze/openapi/service/service/CozeAPI.java +++ b/api/src/main/java/com/coze/openapi/service/service/CozeAPI.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.service.service; import java.time.Duration; @@ -5,10 +6,12 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; -import com.coze.openapi.service.utils.UserAgentInterceptor; import org.slf4j.Logger; import com.coze.openapi.api.*; +import com.coze.openapi.service.auth.Auth; +import com.coze.openapi.service.config.Consts; +import com.coze.openapi.service.service.audio.AudioService; import com.coze.openapi.service.service.bots.BotService; import com.coze.openapi.service.service.chat.ChatService; import com.coze.openapi.service.service.common.CozeLoggerFactory; @@ -17,10 +20,8 @@ import com.coze.openapi.service.service.file.FileService; import com.coze.openapi.service.service.workflow.WorkflowService; import com.coze.openapi.service.service.workspace.WorkspaceService; +import com.coze.openapi.service.utils.UserAgentInterceptor; import com.coze.openapi.service.utils.Utils; -import com.coze.openapi.service.service.audio.AudioService; -import com.coze.openapi.service.auth.Auth; -import com.coze.openapi.service.config.Consts; import com.fasterxml.jackson.databind.ObjectMapper; import okhttp3.ConnectionPool; @@ -30,186 +31,219 @@ import retrofit2.converter.jackson.JacksonConverterFactory; public class CozeAPI { - private static final Logger logger = CozeLoggerFactory.getLogger(); - private final String baseURL; - private final ExecutorService executorService; - private final Auth auth; - private final WorkspaceService workspaceAPI; - private final BotService botAPI; - private final ConversationService conversationAPI; - private final FileService fileAPI; - private final DatasetService datasetAPI; - private final WorkflowService workflowAPI; - private final ChatService chatAPI; - private final AudioService audioAPI; - - private CozeAPI(String baseURL, ExecutorService executorService, Auth auth, WorkspaceService workspaceAPI, BotService botAPI, ConversationService conversationAPI, FileService fileAPI, DatasetService knowledgeAPI, WorkflowService workflowAPI, ChatService chatAPI, AudioService audioAPI) { - this.baseURL = baseURL; - this.executorService = executorService; - this.auth = auth; - this.workspaceAPI = workspaceAPI; - this.botAPI = botAPI; - this.conversationAPI = conversationAPI; - this.fileAPI = fileAPI; - this.datasetAPI = knowledgeAPI; - this.workflowAPI = workflowAPI; - this.chatAPI = chatAPI; - this.audioAPI = audioAPI; + private static final Logger logger = CozeLoggerFactory.getLogger(); + private final String baseURL; + private final ExecutorService executorService; + private final Auth auth; + private final WorkspaceService workspaceAPI; + private final BotService botAPI; + private final ConversationService conversationAPI; + private final FileService fileAPI; + private final DatasetService datasetAPI; + private final WorkflowService workflowAPI; + private final ChatService chatAPI; + private final AudioService audioAPI; + + private CozeAPI( + String baseURL, + ExecutorService executorService, + Auth auth, + WorkspaceService workspaceAPI, + BotService botAPI, + ConversationService conversationAPI, + FileService fileAPI, + DatasetService knowledgeAPI, + WorkflowService workflowAPI, + ChatService chatAPI, + AudioService audioAPI) { + this.baseURL = baseURL; + this.executorService = executorService; + this.auth = auth; + this.workspaceAPI = workspaceAPI; + this.botAPI = botAPI; + this.conversationAPI = conversationAPI; + this.fileAPI = fileAPI; + this.datasetAPI = knowledgeAPI; + this.workflowAPI = workflowAPI; + this.chatAPI = chatAPI; + this.audioAPI = audioAPI; + } + + public WorkspaceService workspaces() { + return this.workspaceAPI; + } + + public BotService bots() { + return this.botAPI; + } + + public ConversationService conversations() { + return this.conversationAPI; + } + + public FileService files() { + return this.fileAPI; + } + + public DatasetService datasets() { + return this.datasetAPI; + } + + public WorkflowService workflows() { + return this.workflowAPI; + } + + public ChatService chat() { + return this.chatAPI; + } + + public AudioService audio() { + return this.audioAPI; + } + + public void shutdownExecutor() { + Objects.requireNonNull( + this.executorService, "executorService must be set in order to shut down"); + this.executorService.shutdown(); + } + + public static class Builder { + private String baseURL = Consts.COZE_COM_BASE_URL; + private Auth auth; + private OkHttpClient client; + private int readTimeout = 5000; + private int connectTimeout = 5000; + + public Builder logger(Logger logger) { + CozeLoggerFactory.setLogger(logger); + return this; } - public WorkspaceService workspaces() { - return this.workspaceAPI; + public Builder baseURL(String url) { + this.baseURL = url; + return this; } - public BotService bots() { - return this.botAPI; - } - - public ConversationService conversations() { - return this.conversationAPI; - } - - public FileService files() { - return this.fileAPI; - } - - public DatasetService datasets() { - return this.datasetAPI; + public Builder auth(Auth auth) { + this.auth = auth; + return this; } - public WorkflowService workflows() { - return this.workflowAPI; + public Builder client(OkHttpClient client) { + this.client = client; + return this; } - public ChatService chat() { - return this.chatAPI; + public Builder readTimeout(int readTimeout) { + this.readTimeout = readTimeout; + return this; } - public AudioService audio() { - return this.audioAPI; + public Builder connectTimeout(int connectTimeout) { + this.connectTimeout = connectTimeout; + return this; } - public void shutdownExecutor() { - Objects.requireNonNull(this.executorService, "executorService must be set in order to shut down"); - this.executorService.shutdown(); + public CozeAPI build() { + if (this.auth == null) { + throw new IllegalArgumentException("auth must be set"); + } + if (this.client == null) { + this.client = + defaultClient( + Duration.ofMillis(this.readTimeout), Duration.ofMillis(this.connectTimeout)); + } else { + this.client = parseClient(this.client); + } + if (this.baseURL == null || this.baseURL.isEmpty()) { + this.baseURL = Consts.COZE_COM_BASE_URL; + } + + ObjectMapper mapper = Utils.defaultObjectMapper(); + Retrofit retrofit = defaultRetrofit(client, mapper, this.baseURL); + ExecutorService executorService = client.dispatcher().executorService(); + WorkspaceService workspaceAPI = new WorkspaceService(retrofit.create(WorkspaceAPI.class)); + BotService botAPI = new BotService(retrofit.create(BotAPI.class)); + ConversationService conversationAPI = + new ConversationService( + retrofit.create(ConversationAPI.class), + retrofit.create(ConversationMessageAPI.class)); + FileService fileAPI = new FileService(retrofit.create(FileAPI.class)); + DatasetService knowledgeAPI = new DatasetService(retrofit.create(DocumentAPI.class)); + WorkflowService workflowAPI = + new WorkflowService( + retrofit.create(WorkflowRunAPI.class), retrofit.create(WorkflowRunHistoryAPI.class)); + ChatService chatAPI = + new ChatService(retrofit.create(ChatAPI.class), retrofit.create(ChatMessageAPI.class)); + AudioService audioAPI = + new AudioService( + retrofit.create(AudioVoiceAPI.class), + retrofit.create(AudioRoomAPI.class), + retrofit.create(AudioSpeechAPI.class)); + + return new CozeAPI( + this.baseURL, + executorService, + this.auth, + workspaceAPI, + botAPI, + conversationAPI, + fileAPI, + knowledgeAPI, + workflowAPI, + chatAPI, + audioAPI); } - - - public static class Builder { - private String baseURL = Consts.COZE_COM_BASE_URL; - private Auth auth; - private OkHttpClient client; - private int readTimeout = 5000; - private int connectTimeout = 5000; - - public Builder logger(Logger logger) { - CozeLoggerFactory.setLogger(logger); - return this; + // 确保加上了 Auth 拦截器 + private OkHttpClient parseClient(OkHttpClient client) { + boolean hasAuthInterceptor = false; + boolean hasTimeoutInterceptor = false; + boolean hasUserAgentInterceptor = false; + for (Interceptor interceptor : client.interceptors()) { + if (interceptor instanceof AuthenticationInterceptor) { + hasAuthInterceptor = true; } - - public Builder baseURL(String url){ - this.baseURL = url; - return this; + if (interceptor instanceof TimeoutInterceptor) { + hasTimeoutInterceptor = true; } - - public Builder auth(Auth auth){ - this.auth = auth; - return this; - } - - public Builder client(OkHttpClient client){ - this.client = client; - return this; - } - - public Builder readTimeout(int readTimeout){ - this.readTimeout = readTimeout; - return this; - } - - public Builder connectTimeout(int connectTimeout){ - this.connectTimeout = connectTimeout; - return this; + if (interceptor instanceof UserAgentInterceptor) { + hasUserAgentInterceptor = true; } + } + if (hasAuthInterceptor && hasTimeoutInterceptor && hasUserAgentInterceptor) { + return client; + } + OkHttpClient.Builder builder = new OkHttpClient.Builder(client); + if (!hasAuthInterceptor) { + builder.addInterceptor(new AuthenticationInterceptor(this.auth)); + } + if (!hasTimeoutInterceptor) { + builder.addInterceptor(new TimeoutInterceptor()); + } + if (!hasUserAgentInterceptor) { + builder.addInterceptor(new UserAgentInterceptor()); + } + return builder.build(); + } - public CozeAPI build(){ - if (this.auth == null){ - throw new IllegalArgumentException("auth must be set"); - } - if (this.client == null){ - this.client = defaultClient(Duration.ofMillis(this.readTimeout), Duration.ofMillis(this.connectTimeout)); - }else { - this.client = parseClient(this.client); - } - if (this.baseURL == null || this.baseURL.isEmpty()){ - this.baseURL = Consts.COZE_COM_BASE_URL; - } - - ObjectMapper mapper = Utils.defaultObjectMapper(); - Retrofit retrofit = defaultRetrofit(client, mapper, this.baseURL); - ExecutorService executorService = client.dispatcher().executorService(); - WorkspaceService workspaceAPI = new WorkspaceService(retrofit.create(WorkspaceAPI.class)); - BotService botAPI = new BotService(retrofit.create(BotAPI.class)); - ConversationService conversationAPI = new ConversationService(retrofit.create(ConversationAPI.class), retrofit.create(ConversationMessageAPI.class)); - FileService fileAPI = new FileService(retrofit.create(FileAPI.class)); - DatasetService knowledgeAPI = new DatasetService(retrofit.create(DocumentAPI.class)); - WorkflowService workflowAPI = new WorkflowService(retrofit.create(WorkflowRunAPI.class), retrofit.create(WorkflowRunHistoryAPI.class)); - ChatService chatAPI = new ChatService(retrofit.create(ChatAPI.class), retrofit.create(ChatMessageAPI.class)); - AudioService audioAPI = new AudioService(retrofit.create(AudioVoiceAPI.class), retrofit.create(AudioRoomAPI.class), retrofit.create(AudioSpeechAPI.class)); - - return new CozeAPI(this.baseURL, executorService, this.auth, workspaceAPI, botAPI, conversationAPI, fileAPI, knowledgeAPI, workflowAPI, chatAPI, audioAPI); - } - // 确保加上了 Auth 拦截器 - private OkHttpClient parseClient(OkHttpClient client){ - boolean hasAuthInterceptor = false; - boolean hasTimeoutInterceptor = false; - boolean hasUserAgentInterceptor = false; - for(Interceptor interceptor :client.interceptors()){ - if (interceptor instanceof AuthenticationInterceptor){ - hasAuthInterceptor = true; - } - if (interceptor instanceof TimeoutInterceptor){ - hasTimeoutInterceptor = true; - } - if (interceptor instanceof UserAgentInterceptor){ - hasUserAgentInterceptor = true; - } - } - if (hasAuthInterceptor && hasTimeoutInterceptor && hasUserAgentInterceptor){ - return client; - } - OkHttpClient.Builder builder = new OkHttpClient.Builder(client); - if (!hasAuthInterceptor){ - builder.addInterceptor(new AuthenticationInterceptor(this.auth)); - } - if (!hasTimeoutInterceptor){ - builder.addInterceptor(new TimeoutInterceptor()); - } - if (!hasUserAgentInterceptor){ - builder.addInterceptor(new UserAgentInterceptor()); - } - return builder.build(); - } - - - private OkHttpClient defaultClient(Duration readTimeout, Duration connectTimeout) { - return new OkHttpClient.Builder() - .connectionPool(new ConnectionPool(5, 1, TimeUnit.SECONDS)) - .readTimeout(readTimeout.toMillis(), TimeUnit.MILLISECONDS) - .connectTimeout(connectTimeout.toMillis(), TimeUnit.MILLISECONDS) - .addInterceptor(new AuthenticationInterceptor(this.auth)) // 添加拦截器,在请求头中增加 token - .addInterceptor(new TimeoutInterceptor()) // 添加拦截器,设置超时时间 - .addInterceptor(new UserAgentInterceptor()) // 添加拦截器,设置 user-agent - .build(); - } + private OkHttpClient defaultClient(Duration readTimeout, Duration connectTimeout) { + return new OkHttpClient.Builder() + .connectionPool(new ConnectionPool(5, 1, TimeUnit.SECONDS)) + .readTimeout(readTimeout.toMillis(), TimeUnit.MILLISECONDS) + .connectTimeout(connectTimeout.toMillis(), TimeUnit.MILLISECONDS) + .addInterceptor(new AuthenticationInterceptor(this.auth)) // 添加拦截器,在请求头中增加 token + .addInterceptor(new TimeoutInterceptor()) // 添加拦截器,设置超时时间 + .addInterceptor(new UserAgentInterceptor()) // 添加拦截器,设置 user-agent + .build(); + } - private Retrofit defaultRetrofit(OkHttpClient client, ObjectMapper mapper, String baseURL) { - return new Retrofit.Builder() - .baseUrl(baseURL) - .client(client) - .addConverterFactory(JacksonConverterFactory.create(mapper)) - .addCallAdapterFactory(APIResponseCallAdapterFactory.create()) - .build(); - } + private Retrofit defaultRetrofit(OkHttpClient client, ObjectMapper mapper, String baseURL) { + return new Retrofit.Builder() + .baseUrl(baseURL) + .client(client) + .addConverterFactory(JacksonConverterFactory.create(mapper)) + .addCallAdapterFactory(APIResponseCallAdapterFactory.create()) + .build(); } + } } diff --git a/api/src/main/java/com/coze/openapi/service/service/TimeoutInterceptor.java b/api/src/main/java/com/coze/openapi/service/service/TimeoutInterceptor.java index 87375802..e262a44e 100644 --- a/api/src/main/java/com/coze/openapi/service/service/TimeoutInterceptor.java +++ b/api/src/main/java/com/coze/openapi/service/service/TimeoutInterceptor.java @@ -1,40 +1,41 @@ +/* (C)2024 */ package com.coze.openapi.service.service; -import okhttp3.Interceptor; -import okhttp3.Request; -import okhttp3.Response; - import java.io.IOException; import java.util.concurrent.TimeUnit; import com.coze.openapi.client.common.BaseReq; +import okhttp3.Interceptor; +import okhttp3.Request; +import okhttp3.Response; + public class TimeoutInterceptor implements Interceptor { - - @Override - public Response intercept(Chain chain) throws IOException { - Request request = chain.request(); - - // 从请求中获取 BaseReq 对象 - Object tag = request.tag(BaseReq.class); - if (!(tag instanceof BaseReq)) { - return chain.proceed(request); - } - - BaseReq baseReq = (BaseReq) tag; - Chain newChain = chain; - - // 只有当设置了超时时间时才修改 - if (baseReq.getConnectTimeout() != null) { - newChain = newChain.withConnectTimeout(baseReq.getConnectTimeout(), TimeUnit.MILLISECONDS); - } - if (baseReq.getReadTimeout() != null) { - newChain = newChain.withReadTimeout(baseReq.getReadTimeout(), TimeUnit.MILLISECONDS); - } - if (baseReq.getWriteTimeout() != null) { - newChain = newChain.withWriteTimeout(baseReq.getWriteTimeout(), TimeUnit.MILLISECONDS); - } - - return newChain.proceed(request); + + @Override + public Response intercept(Chain chain) throws IOException { + Request request = chain.request(); + + // 从请求中获取 BaseReq 对象 + Object tag = request.tag(BaseReq.class); + if (!(tag instanceof BaseReq)) { + return chain.proceed(request); + } + + BaseReq baseReq = (BaseReq) tag; + Chain newChain = chain; + + // 只有当设置了超时时间时才修改 + if (baseReq.getConnectTimeout() != null) { + newChain = newChain.withConnectTimeout(baseReq.getConnectTimeout(), TimeUnit.MILLISECONDS); + } + if (baseReq.getReadTimeout() != null) { + newChain = newChain.withReadTimeout(baseReq.getReadTimeout(), TimeUnit.MILLISECONDS); } + if (baseReq.getWriteTimeout() != null) { + newChain = newChain.withWriteTimeout(baseReq.getWriteTimeout(), TimeUnit.MILLISECONDS); + } + + return newChain.proceed(request); + } } diff --git a/api/src/main/java/com/coze/openapi/service/service/audio/AudioService.java b/api/src/main/java/com/coze/openapi/service/service/audio/AudioService.java index 9bc26256..65c7702e 100644 --- a/api/src/main/java/com/coze/openapi/service/service/audio/AudioService.java +++ b/api/src/main/java/com/coze/openapi/service/service/audio/AudioService.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.service.service.audio; import com.coze.openapi.api.AudioRoomAPI; @@ -5,26 +6,25 @@ import com.coze.openapi.api.AudioVoiceAPI; public class AudioService { - private final VoiceService voiceAPI; - private final RoomService roomAPI; - private final SpeechService speechAPI; + private final VoiceService voiceAPI; + private final RoomService roomAPI; + private final SpeechService speechAPI; - public AudioService(AudioVoiceAPI voiceAPI, AudioRoomAPI roomAPI, AudioSpeechAPI speechAPI) { - this.voiceAPI = new VoiceService(voiceAPI); - this.roomAPI = new RoomService(roomAPI); - this.speechAPI = new SpeechService(speechAPI); - } + public AudioService(AudioVoiceAPI voiceAPI, AudioRoomAPI roomAPI, AudioSpeechAPI speechAPI) { + this.voiceAPI = new VoiceService(voiceAPI); + this.roomAPI = new RoomService(roomAPI); + this.speechAPI = new SpeechService(speechAPI); + } - public VoiceService voices() { - return this.voiceAPI; - } + public VoiceService voices() { + return this.voiceAPI; + } - public RoomService rooms() { - return this.roomAPI; - } - - public SpeechService speech() { - return this.speechAPI; - } + public RoomService rooms() { + return this.roomAPI; + } + public SpeechService speech() { + return this.speechAPI; + } } diff --git a/api/src/main/java/com/coze/openapi/service/service/audio/RoomService.java b/api/src/main/java/com/coze/openapi/service/service/audio/RoomService.java index ab68c6a5..738976e9 100644 --- a/api/src/main/java/com/coze/openapi/service/service/audio/RoomService.java +++ b/api/src/main/java/com/coze/openapi/service/service/audio/RoomService.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.service.service.audio; import com.coze.openapi.api.AudioRoomAPI; @@ -7,16 +8,16 @@ import com.coze.openapi.service.utils.Utils; public class RoomService { - private final AudioRoomAPI roomApi; + private final AudioRoomAPI roomApi; - public RoomService(AudioRoomAPI roomApi) { - this.roomApi = roomApi; - } + public RoomService(AudioRoomAPI roomApi) { + this.roomApi = roomApi; + } - public CreateRoomResp create(CreateRoomReq req) { - BaseResponse resp = Utils.execute(roomApi.create(req, req)); - CreateRoomResp data = resp.getData(); - data.setLogID(resp.getLogID()); - return data; - } + public CreateRoomResp create(CreateRoomReq req) { + BaseResponse resp = Utils.execute(roomApi.create(req, req)); + CreateRoomResp data = resp.getData(); + data.setLogID(resp.getLogID()); + return data; + } } diff --git a/api/src/main/java/com/coze/openapi/service/service/audio/SpeechService.java b/api/src/main/java/com/coze/openapi/service/service/audio/SpeechService.java index 18f1ee39..df521497 100644 --- a/api/src/main/java/com/coze/openapi/service/service/audio/SpeechService.java +++ b/api/src/main/java/com/coze/openapi/service/service/audio/SpeechService.java @@ -1,36 +1,34 @@ +/* (C)2024 */ package com.coze.openapi.service.service.audio; import com.coze.openapi.api.AudioSpeechAPI; import com.coze.openapi.client.audio.speech.CreateSpeechReq; import com.coze.openapi.client.audio.speech.CreateSpeechResp; -import com.coze.openapi.client.common.BaseResp; -import com.coze.openapi.client.common.BaseResponse; import com.coze.openapi.service.utils.Utils; -import io.reactivex.Single; import okhttp3.ResponseBody; import retrofit2.HttpException; import retrofit2.Response; public class SpeechService { - private final AudioSpeechAPI api; + private final AudioSpeechAPI api; - public SpeechService(AudioSpeechAPI api) { - this.api = api; - } + public SpeechService(AudioSpeechAPI api) { + this.api = api; + } - public CreateSpeechResp create(CreateSpeechReq req) { - try{ - Response response = api.create(req, req).execute(); - if (!response.isSuccessful()) { - throw new HttpException(response); - } - CreateSpeechResp resp = new CreateSpeechResp(response.body()); - resp.setLogID(Utils.getLogID(response)); - return resp; + public CreateSpeechResp create(CreateSpeechReq req) { + try { + Response response = api.create(req, req).execute(); + if (!response.isSuccessful()) { + throw new HttpException(response); + } + CreateSpeechResp resp = new CreateSpeechResp(response.body()); + resp.setLogID(Utils.getLogID(response)); + return resp; - }catch (Exception e){ - throw new RuntimeException(e); - } + } catch (Exception e) { + throw new RuntimeException(e); } + } } diff --git a/api/src/main/java/com/coze/openapi/service/service/audio/VoiceService.java b/api/src/main/java/com/coze/openapi/service/service/audio/VoiceService.java index 713a2379..947e9200 100644 --- a/api/src/main/java/com/coze/openapi/service/service/audio/VoiceService.java +++ b/api/src/main/java/com/coze/openapi/service/service/audio/VoiceService.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.service.service.audio; import java.io.File; @@ -13,8 +14,8 @@ import com.coze.openapi.client.common.pagination.PageFetcher; import com.coze.openapi.client.common.pagination.PageNumBasedPaginator; import com.coze.openapi.client.common.pagination.PageRequest; -import com.coze.openapi.client.common.pagination.PageResponse; import com.coze.openapi.client.common.pagination.PageResp; +import com.coze.openapi.client.common.pagination.PageResponse; import com.coze.openapi.service.utils.Utils; import okhttp3.MediaType; @@ -22,77 +23,82 @@ import okhttp3.RequestBody; public class VoiceService { - private final AudioVoiceAPI api; + private final AudioVoiceAPI api; + + public VoiceService(AudioVoiceAPI api) { + this.api = api; + } + + public CloneVoiceResp clone(CloneVoiceReq req) { + RequestBody voiceName = RequestBody.create(req.getVoiceName(), MediaType.parse("text/plain")); + RequestBody audioFormat = + RequestBody.create(req.getAudioFormat().getValue(), MediaType.parse("text/plain")); - public VoiceService(AudioVoiceAPI api) { - this.api = api; + RequestBody language = null; + if (req.getLanguage() != null) { + language = RequestBody.create(req.getLanguage().getValue(), MediaType.parse("text/plain")); + } + RequestBody voiceID = null; + if (req.getVoiceID() != null) { + voiceID = RequestBody.create(req.getVoiceID(), MediaType.parse("text/plain")); + } + RequestBody previewText = null; + if (req.getPreviewText() != null) { + previewText = RequestBody.create(req.getPreviewText(), MediaType.parse("text/plain")); + } + RequestBody text = null; + if (req.getText() != null) { + text = RequestBody.create(req.getText(), MediaType.parse("text/plain")); } + File file = new File(req.getFilePath()); + RequestBody fileBody = RequestBody.create(file, MediaType.parse("multipart/form-data")); + MultipartBody.Part filePart = + MultipartBody.Part.createFormData("file", file.getName(), fileBody); - public CloneVoiceResp clone(CloneVoiceReq req) { - RequestBody voiceName = RequestBody.create(req.getVoiceName(), MediaType.parse("text/plain")); - RequestBody audioFormat = RequestBody.create(req.getAudioFormat().getValue(), MediaType.parse("text/plain")); - - RequestBody language = null; - if (req.getLanguage() != null) { - language = RequestBody.create(req.getLanguage().getValue(), MediaType.parse("text/plain")); - } - RequestBody voiceID = null; - if (req.getVoiceID() != null) { - voiceID = RequestBody.create(req.getVoiceID(), MediaType.parse("text/plain")); - } - RequestBody previewText = null; - if (req.getPreviewText() != null) { - previewText = RequestBody.create(req.getPreviewText(), MediaType.parse("text/plain")); - } - RequestBody text = null; - if (req.getText() != null) { - text = RequestBody.create(req.getText(), MediaType.parse("text/plain")); - } - File file = new File(req.getFilePath()); - RequestBody fileBody = RequestBody.create(file, MediaType.parse("multipart/form-data")); - MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), fileBody); - - return Utils.execute(api.clone(filePart, voiceName, audioFormat, language, voiceID, previewText, text, req)).getData(); + return Utils.execute( + api.clone(filePart, voiceName, audioFormat, language, voiceID, previewText, text, req)) + .getData(); + } + + public PageResp list(@NotNull ListVoiceReq req) { + if (req == null) { + throw new IllegalArgumentException("req is required"); } - public PageResp list(@NotNull ListVoiceReq req) { - if (req == null) { - throw new IllegalArgumentException("req is required"); - } - - Integer pageNum = req.getPageNum(); - Integer pageSize = req.getPageSize(); - Boolean filterSystemVoice = req.getFilterSystemVoice(); - - // 创建分页获取器 - PageFetcher pageFetcher = request -> { - ListVoiceResp resp = Utils.execute(api.list(filterSystemVoice, request.getPageNum(), request.getPageSize(), req)).getData(); - - return PageResponse.builder() - .hasMore(resp.getVoiceList().size() == request.getPageSize()) - .data(resp.getVoiceList()) - .pageNum(request.getPageNum()) - .pageSize(request.getPageSize()) - .logID(resp.getLogID()) - .build(); + Integer pageNum = req.getPageNum(); + Integer pageSize = req.getPageSize(); + Boolean filterSystemVoice = req.getFilterSystemVoice(); + + // 创建分页获取器 + PageFetcher pageFetcher = + request -> { + ListVoiceResp resp = + Utils.execute( + api.list(filterSystemVoice, request.getPageNum(), request.getPageSize(), req)) + .getData(); + + return PageResponse.builder() + .hasMore(resp.getVoiceList().size() == request.getPageSize()) + .data(resp.getVoiceList()) + .pageNum(request.getPageNum()) + .pageSize(request.getPageSize()) + .logID(resp.getLogID()) + .build(); }; - // 创建分页器 - PageNumBasedPaginator paginator = new PageNumBasedPaginator<>(pageFetcher, pageSize); - - // 获取当前页数据 - PageRequest initialRequest = PageRequest.builder() - .pageNum(pageNum) - .pageSize(pageSize) - .build(); - - PageResponse currentPage = pageFetcher.fetch(initialRequest); - - return PageResp.builder() - .items(currentPage.getData()) - .iterator(paginator) - .hasMore(currentPage.isHasMore()) - .logID(currentPage.getLogID()) - .build(); - } -} \ No newline at end of file + // 创建分页器 + PageNumBasedPaginator paginator = new PageNumBasedPaginator<>(pageFetcher, pageSize); + + // 获取当前页数据 + PageRequest initialRequest = PageRequest.builder().pageNum(pageNum).pageSize(pageSize).build(); + + PageResponse currentPage = pageFetcher.fetch(initialRequest); + + return PageResp.builder() + .items(currentPage.getData()) + .iterator(paginator) + .hasMore(currentPage.isHasMore()) + .logID(currentPage.getLogID()) + .build(); + } +} diff --git a/api/src/main/java/com/coze/openapi/service/service/bots/BotService.java b/api/src/main/java/com/coze/openapi/service/service/bots/BotService.java index e0aeceb6..68ba1106 100644 --- a/api/src/main/java/com/coze/openapi/service/service/bots/BotService.java +++ b/api/src/main/java/com/coze/openapi/service/service/bots/BotService.java @@ -1,97 +1,90 @@ +/* (C)2024 */ package com.coze.openapi.service.service.bots; - -import com.coze.openapi.client.bots.*; import org.jetbrains.annotations.NotNull; import com.coze.openapi.api.BotAPI; +import com.coze.openapi.client.bots.*; import com.coze.openapi.client.bots.model.Bot; import com.coze.openapi.client.bots.model.SimpleBot; import com.coze.openapi.client.common.BaseResponse; -import com.coze.openapi.client.common.pagination.PageResponse; -import com.coze.openapi.client.common.pagination.PageResp; import com.coze.openapi.client.common.pagination.PageFetcher; import com.coze.openapi.client.common.pagination.PageNumBasedPaginator; import com.coze.openapi.client.common.pagination.PageRequest; +import com.coze.openapi.client.common.pagination.PageResp; +import com.coze.openapi.client.common.pagination.PageResponse; import com.coze.openapi.service.utils.Utils; public class BotService { - private final BotAPI api; + private final BotAPI api; - public BotService(BotAPI api) { - this.api = api; - } + public BotService(BotAPI api) { + this.api = api; + } - public PageResp list(@NotNull ListBotReq req) { - if (req == null) { - throw new IllegalArgumentException("req is required"); - } - - Integer pageNum = req.getPageNum() == null ? 1 : req.getPageNum(); - Integer pageSize = req.getPageSize() == null ? 20 : req.getPageSize(); - PageFetcher pageFetcher = getSimpleBotPageFetcher(req); - - // 创建分页器 - PageNumBasedPaginator paginator = new PageNumBasedPaginator<>(pageFetcher, pageSize); - - // 获取当前页数据 - PageRequest initialRequest = PageRequest.builder() - .pageNum(pageNum) - .pageSize(pageSize) - .build(); - - PageResponse firstPage = pageFetcher.fetch(initialRequest); - - return PageResp.builder() - .total(firstPage.getTotal()) - .items(firstPage.getData()) - .iterator(paginator) - .logID(firstPage.getLogID()) - .hasMore(firstPage.isHasMore()) - .build(); + public PageResp list(@NotNull ListBotReq req) { + if (req == null) { + throw new IllegalArgumentException("req is required"); } - @NotNull - private PageFetcher getSimpleBotPageFetcher(@NotNull ListBotReq req) { - String spaceID = req.getSpaceID(); - - // 创建分页获取器 - PageFetcher pageFetcher = request -> { - BaseResponse resp = Utils.execute(api.list(spaceID, request.getPageNum(), request.getPageSize(), req)); - return PageResponse.builder() - .hasMore(resp.getData().getBots().size() == request.getPageSize()) - .data(resp.getData().getBots()) - .pageNum(request.getPageNum()) - .pageSize(request.getPageSize()) - .total(resp.getData().getTotal()) - .logID(resp.getLogID()) - .build(); + Integer pageNum = req.getPageNum() == null ? 1 : req.getPageNum(); + Integer pageSize = req.getPageSize() == null ? 20 : req.getPageSize(); + PageFetcher pageFetcher = getSimpleBotPageFetcher(req); + + // 创建分页器 + PageNumBasedPaginator paginator = new PageNumBasedPaginator<>(pageFetcher, pageSize); + + // 获取当前页数据 + PageRequest initialRequest = PageRequest.builder().pageNum(pageNum).pageSize(pageSize).build(); + + PageResponse firstPage = pageFetcher.fetch(initialRequest); + + return PageResp.builder() + .total(firstPage.getTotal()) + .items(firstPage.getData()) + .iterator(paginator) + .logID(firstPage.getLogID()) + .hasMore(firstPage.isHasMore()) + .build(); + } + + @NotNull + private PageFetcher getSimpleBotPageFetcher(@NotNull ListBotReq req) { + String spaceID = req.getSpaceID(); + + // 创建分页获取器 + PageFetcher pageFetcher = + request -> { + BaseResponse resp = + Utils.execute(api.list(spaceID, request.getPageNum(), request.getPageSize(), req)); + return PageResponse.builder() + .hasMore(resp.getData().getBots().size() == request.getPageSize()) + .data(resp.getData().getBots()) + .pageNum(request.getPageNum()) + .pageSize(request.getPageSize()) + .total(resp.getData().getTotal()) + .logID(resp.getLogID()) + .build(); }; - return pageFetcher; - } - - - public RetrieveBotResp retrieve(@NotNull RetrieveBotReq req) { - BaseResponse resp = Utils.execute(api.retrieve(req.getBotID(), req)); - return RetrieveBotResp.builder() - .bot(resp.getData()) - .logID(resp.getLogID()) - .build(); - } - - public CreateBotResp create(@NotNull CreateBotReq req ) { - return Utils.execute(api.create(req, req)).getData(); - } - - public UpdateBotResp update(@NotNull UpdateBotReq req) { - String logID = Utils.execute(api.update(req, req)).getLogID(); - return UpdateBotResp.builder() - .logID(logID) - .build(); - } - - public PublishBotResp publish(@NotNull PublishBotReq req) { - return Utils.execute(api.publish(req, req)).getData(); - } + return pageFetcher; + } + + public RetrieveBotResp retrieve(@NotNull RetrieveBotReq req) { + BaseResponse resp = Utils.execute(api.retrieve(req.getBotID(), req)); + return RetrieveBotResp.builder().bot(resp.getData()).logID(resp.getLogID()).build(); + } + + public CreateBotResp create(@NotNull CreateBotReq req) { + return Utils.execute(api.create(req, req)).getData(); + } + + public UpdateBotResp update(@NotNull UpdateBotReq req) { + String logID = Utils.execute(api.update(req, req)).getLogID(); + return UpdateBotResp.builder().logID(logID).build(); + } + + public PublishBotResp publish(@NotNull PublishBotReq req) { + return Utils.execute(api.publish(req, req)).getData(); + } } diff --git a/api/src/main/java/com/coze/openapi/service/service/chat/ChatMessageService.java b/api/src/main/java/com/coze/openapi/service/service/chat/ChatMessageService.java index 01af107b..6e8723e9 100644 --- a/api/src/main/java/com/coze/openapi/service/service/chat/ChatMessageService.java +++ b/api/src/main/java/com/coze/openapi/service/service/chat/ChatMessageService.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.service.service.chat; import java.util.List; @@ -11,18 +12,15 @@ public class ChatMessageService { + private final ChatMessageAPI chatMessageApi; - private final ChatMessageAPI chatMessageApi; + public ChatMessageService(ChatMessageAPI chatMessageApi) { + this.chatMessageApi = chatMessageApi; + } - public ChatMessageService(ChatMessageAPI chatMessageApi) { - this.chatMessageApi = chatMessageApi; - } - - public ListMessageResp list(ListMessageReq req) { - BaseResponse> resp = Utils.execute(chatMessageApi.list(req.getConversationID(), req.getChatID(), req)); - return ListMessageResp.builder() - .logID(resp.getLogID()) - .messages(resp.getData()) - .build(); - } + public ListMessageResp list(ListMessageReq req) { + BaseResponse> resp = + Utils.execute(chatMessageApi.list(req.getConversationID(), req.getChatID(), req)); + return ListMessageResp.builder().logID(resp.getLogID()).messages(resp.getData()).build(); + } } diff --git a/api/src/main/java/com/coze/openapi/service/service/chat/ChatService.java b/api/src/main/java/com/coze/openapi/service/service/chat/ChatService.java index e0089644..e7051cf6 100644 --- a/api/src/main/java/com/coze/openapi/service/service/chat/ChatService.java +++ b/api/src/main/java/com/coze/openapi/service/service/chat/ChatService.java @@ -1,5 +1,11 @@ +/* (C)2024 */ package com.coze.openapi.service.service.chat; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import org.slf4j.Logger; + import com.coze.openapi.api.ChatAPI; import com.coze.openapi.api.ChatMessageAPI; import com.coze.openapi.client.chat.CancelChatReq; @@ -25,165 +31,151 @@ import okhttp3.ResponseBody; import retrofit2.Call; -import java.util.Objects; -import java.util.concurrent.TimeUnit; - -import org.slf4j.Logger; - public class ChatService { - private final ChatAPI chatAPI; - private final ChatMessageService chatMessageAPI; - private static final Logger logger = CozeLoggerFactory.getLogger(); - - public ChatService(ChatAPI chatAPI, ChatMessageAPI chatMessageAPI) { - this.chatAPI = chatAPI; - this.chatMessageAPI = new ChatMessageService(chatMessageAPI); - } - - public ChatMessageService message() { - return this.chatMessageAPI; - } - - /* - * Call the Chat API with non-streaming to send messages to a published Coze bot. - * docs en: https://www.coze.com/docs/developer_guides/chat_v3 - * docs zh: https://www.coze.cn/docs/developer_guides/chat_v3 - * */ - public CreateChatResp create(CreateChatReq req) { - req.disableStream(); - String conversationID = req.getConversationID(); - req.clearBeforeReq(); - BaseResponse resp = Utils.execute(chatAPI.chat(conversationID, req, req)); - return CreateChatResp.builder() - .chat(resp.getData()) - .logID(resp.getLogID()) - .build(); - } - /* - * Call the Chat API with non-streaming to send messages to a published Coze bot and - * fetch chat status & message. - * docs en: https://www.coze.com/docs/developer_guides/chat_v3 - * docs zh: https://www.coze.cn/docs/developer_guides/chat_v3 - * */ - public ChatPoll createAndPoll(CreateChatReq req) throws Exception{ - return _createAndPoll(req, null); - } - - /* - * Call the Chat API with non-streaming to send messages to a published Coze bot and - * fetch chat status & message. - * docs en: https://www.coze.com/docs/developer_guides/chat_v3 - * docs zh: https://www.coze.cn/docs/developer_guides/chat_v3 - * - * timeout: The maximum time to wait for the chat to complete. The chat will be cancelled after the progress of it - * exceed timeout. The unit is second. - * */ - public ChatPoll createAndPoll(CreateChatReq req, Long timeout) throws Exception{ - Objects.requireNonNull(timeout, "timeout is required"); - return _createAndPoll(req, timeout); - } - - private ChatPoll _createAndPoll(CreateChatReq req, Long timeout) throws Exception{ - req.disableStream(); - String conversationID = req.getConversationID(); - req.clearBeforeReq(); - Chat chat = Utils.execute(chatAPI.chat(conversationID, req, req)).getData(); - // 处理一开始没有传入 ConversationID 的情况 - conversationID = chat.getConversationID(); - String chatID = chat.getID(); - long start = System.currentTimeMillis() / 1000; - while (ChatStatus.IN_PROGRESS.equals(chat.getStatus())) { - TimeUnit.SECONDS.sleep(1); - if (timeout != null && timeout > 0) { - if ((System.currentTimeMillis() / 1000) - start > timeout) { - logger.warn("Chat timeout: " + timeout + " seconds, cancel Chat"); - // The chat can be cancelled before its completed. - cancel(CancelChatReq.of(conversationID, chatID)); - break; - } - } - - chat = retrieve(RetrieveChatReq.of(conversationID, chatID)).getChat(); - if (ChatStatus.COMPLETED.equals(chat.getStatus())) { - logger.info("Chat completed, spend " + (System.currentTimeMillis() / 1000 - start) + " seconds"); - break; - } + private final ChatAPI chatAPI; + private final ChatMessageService chatMessageAPI; + private static final Logger logger = CozeLoggerFactory.getLogger(); + + public ChatService(ChatAPI chatAPI, ChatMessageAPI chatMessageAPI) { + this.chatAPI = chatAPI; + this.chatMessageAPI = new ChatMessageService(chatMessageAPI); + } + + public ChatMessageService message() { + return this.chatMessageAPI; + } + + /* + * Call the Chat API with non-streaming to send messages to a published Coze bot. + * docs en: https://www.coze.com/docs/developer_guides/chat_v3 + * docs zh: https://www.coze.cn/docs/developer_guides/chat_v3 + * */ + public CreateChatResp create(CreateChatReq req) { + req.disableStream(); + String conversationID = req.getConversationID(); + req.clearBeforeReq(); + BaseResponse resp = Utils.execute(chatAPI.chat(conversationID, req, req)); + return CreateChatResp.builder().chat(resp.getData()).logID(resp.getLogID()).build(); + } + /* + * Call the Chat API with non-streaming to send messages to a published Coze bot and + * fetch chat status & message. + * docs en: https://www.coze.com/docs/developer_guides/chat_v3 + * docs zh: https://www.coze.cn/docs/developer_guides/chat_v3 + * */ + public ChatPoll createAndPoll(CreateChatReq req) throws Exception { + return _createAndPoll(req, null); + } + + /* + * Call the Chat API with non-streaming to send messages to a published Coze bot and + * fetch chat status & message. + * docs en: https://www.coze.com/docs/developer_guides/chat_v3 + * docs zh: https://www.coze.cn/docs/developer_guides/chat_v3 + * + * timeout: The maximum time to wait for the chat to complete. The chat will be cancelled after the progress of it + * exceed timeout. The unit is second. + * */ + public ChatPoll createAndPoll(CreateChatReq req, Long timeout) throws Exception { + Objects.requireNonNull(timeout, "timeout is required"); + return _createAndPoll(req, timeout); + } + + private ChatPoll _createAndPoll(CreateChatReq req, Long timeout) throws Exception { + req.disableStream(); + String conversationID = req.getConversationID(); + req.clearBeforeReq(); + Chat chat = Utils.execute(chatAPI.chat(conversationID, req, req)).getData(); + // 处理一开始没有传入 ConversationID 的情况 + conversationID = chat.getConversationID(); + String chatID = chat.getID(); + long start = System.currentTimeMillis() / 1000; + while (ChatStatus.IN_PROGRESS.equals(chat.getStatus())) { + TimeUnit.SECONDS.sleep(1); + if (timeout != null && timeout > 0) { + if ((System.currentTimeMillis() / 1000) - start > timeout) { + logger.warn("Chat timeout: " + timeout + " seconds, cancel Chat"); + // The chat can be cancelled before its completed. + cancel(CancelChatReq.of(conversationID, chatID)); + break; } - ListMessageResp resp = message().list(ListMessageReq.of(conversationID, chatID)); - return new ChatPoll(chat, resp.getMessages()); - } - - /* - * Get the detailed information of the chat. - * docs en: https://www.coze.com/docs/developer_guides/retrieve_chat - * docs zh: https://www.coze.cn/docs/developer_guides/retrieve_chat - * */ - public RetrieveChatResp retrieve(RetrieveChatReq req) { - BaseResponse resp = Utils.execute(chatAPI.retrieve(req.getConversationID(), req.getChatID(), req)); - return RetrieveChatResp.builder() - .chat(resp.getData()) - .logID(resp.getLogID()) - .build(); - } - - /* - * Call this API to cancel an ongoing chat. - * docs en: https://www.coze.com/docs/developer_guides/chat_cancel - * docs zh: https://www.coze.cn/docs/developer_guides/chat_cancel - * */ - public CancelChatResp cancel(CancelChatReq req) { - BaseResponse resp = Utils.execute(chatAPI.cancel(req, req)); - return CancelChatResp.builder() - .chat(resp.getData()) - .logID(resp.getLogID()) - .build(); - } - - /* - * Call this API to submit the results of tool execution. - * docs en: https://www.coze.com/docs/developer_guides/chat_submit_tool_outputs - * docs zh: https://www.coze.cn/docs/developer_guides/chat_submit_tool_outputs - */ - public SubmitToolOutputsResp submitToolOutputs(SubmitToolOutputsReq req) { - req.disableStream(); - String conversationID = req.getConversationID(); - String chatID = req.getChatID(); - req.clearBeforeReq(); - BaseResponse resp = Utils.execute(chatAPI.submitToolOutputs(conversationID, chatID, req, req)); - return SubmitToolOutputsResp.builder() - .chat(resp.getData()) - .logID(resp.getLogID()) - .build(); - } - - /* - * Call this API to submit the results of tool execution. This API will return streaming response - * docs en: https://www.coze.com/docs/developer_guides/chat_submit_tool_outputs - * docs zh: https://www.coze.cn/docs/developer_guides/chat_submit_tool_outputs - */ - public Flowable streamSubmitToolOutputs(SubmitToolOutputsReq req) { - req.enableStream(); - String conversationID = req.getConversationID(); - String chatID = req.getChatID(); - req.clearBeforeReq(); - return stream(chatAPI.streamSubmitToolOutputs(conversationID, chatID, req, req)); - } - - /* - * Call the Chat API with streaming to send messages to a published Coze bot. - * docs en: https://www.coze.com/docs/developer_guides/chat_v3 - * docs zh: https://www.coze.cn/docs/developer_guides/chat_v3 - * */ - public Flowable stream(CreateChatReq req) { - req.enableStream(); - String conversationID = req.getConversationID(); - req.clearBeforeReq(); - return stream(chatAPI.stream(conversationID, req, req)); - } - - - public static Flowable stream(Call apiCall) { - return Flowable.create(emitter -> apiCall.enqueue(new EventCallback(emitter)), BackpressureStrategy.BUFFER); + } + + chat = retrieve(RetrieveChatReq.of(conversationID, chatID)).getChat(); + if (ChatStatus.COMPLETED.equals(chat.getStatus())) { + logger.info( + "Chat completed, spend " + (System.currentTimeMillis() / 1000 - start) + " seconds"); + break; + } } + ListMessageResp resp = message().list(ListMessageReq.of(conversationID, chatID)); + return new ChatPoll(chat, resp.getMessages()); + } + + /* + * Get the detailed information of the chat. + * docs en: https://www.coze.com/docs/developer_guides/retrieve_chat + * docs zh: https://www.coze.cn/docs/developer_guides/retrieve_chat + * */ + public RetrieveChatResp retrieve(RetrieveChatReq req) { + BaseResponse resp = + Utils.execute(chatAPI.retrieve(req.getConversationID(), req.getChatID(), req)); + return RetrieveChatResp.builder().chat(resp.getData()).logID(resp.getLogID()).build(); + } + + /* + * Call this API to cancel an ongoing chat. + * docs en: https://www.coze.com/docs/developer_guides/chat_cancel + * docs zh: https://www.coze.cn/docs/developer_guides/chat_cancel + * */ + public CancelChatResp cancel(CancelChatReq req) { + BaseResponse resp = Utils.execute(chatAPI.cancel(req, req)); + return CancelChatResp.builder().chat(resp.getData()).logID(resp.getLogID()).build(); + } + + /* + * Call this API to submit the results of tool execution. + * docs en: https://www.coze.com/docs/developer_guides/chat_submit_tool_outputs + * docs zh: https://www.coze.cn/docs/developer_guides/chat_submit_tool_outputs + */ + public SubmitToolOutputsResp submitToolOutputs(SubmitToolOutputsReq req) { + req.disableStream(); + String conversationID = req.getConversationID(); + String chatID = req.getChatID(); + req.clearBeforeReq(); + BaseResponse resp = + Utils.execute(chatAPI.submitToolOutputs(conversationID, chatID, req, req)); + return SubmitToolOutputsResp.builder().chat(resp.getData()).logID(resp.getLogID()).build(); + } + + /* + * Call this API to submit the results of tool execution. This API will return streaming response + * docs en: https://www.coze.com/docs/developer_guides/chat_submit_tool_outputs + * docs zh: https://www.coze.cn/docs/developer_guides/chat_submit_tool_outputs + */ + public Flowable streamSubmitToolOutputs(SubmitToolOutputsReq req) { + req.enableStream(); + String conversationID = req.getConversationID(); + String chatID = req.getChatID(); + req.clearBeforeReq(); + return stream(chatAPI.streamSubmitToolOutputs(conversationID, chatID, req, req)); + } + + /* + * Call the Chat API with streaming to send messages to a published Coze bot. + * docs en: https://www.coze.com/docs/developer_guides/chat_v3 + * docs zh: https://www.coze.cn/docs/developer_guides/chat_v3 + * */ + public Flowable stream(CreateChatReq req) { + req.enableStream(); + String conversationID = req.getConversationID(); + req.clearBeforeReq(); + return stream(chatAPI.stream(conversationID, req, req)); + } + + public static Flowable stream(Call apiCall) { + return Flowable.create( + emitter -> apiCall.enqueue(new EventCallback(emitter)), BackpressureStrategy.BUFFER); + } } diff --git a/api/src/main/java/com/coze/openapi/service/service/chat/EventCallback.java b/api/src/main/java/com/coze/openapi/service/service/chat/EventCallback.java index 4e712236..431e6d5a 100644 --- a/api/src/main/java/com/coze/openapi/service/service/chat/EventCallback.java +++ b/api/src/main/java/com/coze/openapi/service/service/chat/EventCallback.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.service.service.chat; import java.io.BufferedReader; @@ -12,25 +13,26 @@ public class EventCallback extends AbstractEventCallback { - public EventCallback(FlowableEmitter emitter) { - super(emitter); - } + public EventCallback(FlowableEmitter emitter) { + super(emitter); + } - @Override - protected boolean processLine(String line, BufferedReader reader, String logID) throws IOException { - if (line.startsWith("event:")) { - String event = line.substring(6).trim(); - String data = reader.readLine().substring(5).trim(); + @Override + protected boolean processLine(String line, BufferedReader reader, String logID) + throws IOException { + if (line.startsWith("event:")) { + String event = line.substring(6).trim(); + String data = reader.readLine().substring(5).trim(); - Map eventLine = new HashMap<>(); - eventLine.put("event", event); - eventLine.put("data", data); + Map eventLine = new HashMap<>(); + eventLine.put("event", event); + eventLine.put("data", data); - ChatEvent eventData = ChatEvent.parseEvent(eventLine, logID); + ChatEvent eventData = ChatEvent.parseEvent(eventLine, logID); - emitter.onNext(eventData); - return eventData.isDone(); - } - return false; + emitter.onNext(eventData); + return eventData.isDone(); } + return false; + } } diff --git a/api/src/main/java/com/coze/openapi/service/service/common/AbstractEventCallback.java b/api/src/main/java/com/coze/openapi/service/service/common/AbstractEventCallback.java index 34c703eb..a3875bc3 100644 --- a/api/src/main/java/com/coze/openapi/service/service/common/AbstractEventCallback.java +++ b/api/src/main/java/com/coze/openapi/service/service/common/AbstractEventCallback.java @@ -1,6 +1,6 @@ +/* (C)2024 */ package com.coze.openapi.service.service.common; - import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; @@ -21,74 +21,74 @@ import retrofit2.Callback; import retrofit2.Response; - public abstract class AbstractEventCallback implements Callback { - private static final ObjectMapper mapper = Utils.defaultObjectMapper(); - private static final Logger logger = CozeLoggerFactory.getLogger(); + private static final ObjectMapper mapper = Utils.defaultObjectMapper(); + private static final Logger logger = CozeLoggerFactory.getLogger(); + + protected FlowableEmitter emitter; + + public AbstractEventCallback(FlowableEmitter emitter) { + this.emitter = emitter; + } + + @Override + public void onResponse(Call call, Response response) { + BufferedReader reader = null; + + try { + String logID = Utils.getLogID(response); + if (!response.isSuccessful()) { + logger.warn("HTTP error: " + response.code() + " " + response.message()); + String errStr = response.errorBody().string(); + CozeError error = mapper.readValue(errStr, CozeError.class); + throw new CozeApiExcetion(Integer.valueOf(response.code()), error.getErrorMessage(), logID); + } + + // 检查 response body 是否为 BaseResponse 格式 + String contentType = response.headers().get("Content-Type"); + if (contentType != null && contentType.contains("application/json")) { + String respStr = response.body().string(); + BaseResponse baseResp = mapper.readValue(respStr, BaseResponse.class); + if (baseResp.getCode() != 0) { + logger.warn("API error: {} {}", baseResp.getCode(), baseResp.getMsg()); + throw new CozeApiExcetion(baseResp.getCode(), baseResp.getMsg(), logID); + } + return; + } - protected FlowableEmitter emitter; + InputStream in = response.body().byteStream(); + reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)); + String line; - public AbstractEventCallback(FlowableEmitter emitter) { - this.emitter = emitter; - } + while (!emitter.isCancelled() && (line = reader.readLine()) != null) { + if (processLine(line, reader, logID)) { + break; + } + } - @Override - public void onResponse(Call call, Response response) { - BufferedReader reader = null; + emitter.onComplete(); + } catch (Throwable t) { + onFailure(call, t); + } finally { + if (reader != null) { try { - String logID = Utils.getLogID(response); - if (!response.isSuccessful()) { - logger.warn("HTTP error: " + response.code() + " " + response.message()); - String errStr = response.errorBody().string(); - CozeError error = mapper.readValue(errStr, CozeError.class); - throw new CozeApiExcetion(Integer.valueOf(response.code()), error.getErrorMessage(), logID); - } - - // 检查 response body 是否为 BaseResponse 格式 - String contentType = response.headers().get("Content-Type"); - if (contentType != null && contentType.contains("application/json")) { - String respStr = response.body().string(); - BaseResponse baseResp = mapper.readValue(respStr, BaseResponse.class); - if (baseResp.getCode() != 0) { - logger.warn("API error: {} {}", baseResp.getCode(), baseResp.getMsg()); - throw new CozeApiExcetion(baseResp.getCode(), baseResp.getMsg(), logID); - } - return; - } - - InputStream in = response.body().byteStream(); - reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)); - String line; - - while (!emitter.isCancelled() && (line = reader.readLine()) != null) { - if (processLine(line, reader, logID)) { - break; - } - } - - emitter.onComplete(); - - } catch (Throwable t) { - onFailure(call, t); - } finally { - if (reader != null) { - try { - reader.close(); - } catch (IOException e) { - // do nothing - } - if (response.body() != null) { - response.body().close(); - } - } + reader.close(); + } catch (IOException e) { + // do nothing + } + if (response.body() != null) { + response.body().close(); } + } } + } - protected abstract boolean processLine(String line, BufferedReader reader, String logID) throws IOException; + protected abstract boolean processLine(String line, BufferedReader reader, String logID) + throws IOException; - @Override - public void onFailure(Call call, Throwable t) { - emitter.onError(t); - } -} \ No newline at end of file + @Override + public void onFailure(Call call, Throwable t) { + emitter.onError(t); + } +} diff --git a/api/src/main/java/com/coze/openapi/service/service/common/CozeLoggerFactory.java b/api/src/main/java/com/coze/openapi/service/service/common/CozeLoggerFactory.java index d7b67a46..e0189501 100644 --- a/api/src/main/java/com/coze/openapi/service/service/common/CozeLoggerFactory.java +++ b/api/src/main/java/com/coze/openapi/service/service/common/CozeLoggerFactory.java @@ -1,18 +1,19 @@ +/* (C)2024 */ package com.coze.openapi.service.service.common; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CozeLoggerFactory { - private static volatile Logger logger = LoggerFactory.getLogger("com.coze.openapi"); - - public static Logger getLogger() { - return logger; - } - - public static void setLogger(Logger customLogger) { - if (customLogger != null) { - logger = customLogger; - } + private static volatile Logger logger = LoggerFactory.getLogger("com.coze.openapi"); + + public static Logger getLogger() { + return logger; + } + + public static void setLogger(Logger customLogger) { + if (customLogger != null) { + logger = customLogger; } + } } diff --git a/api/src/main/java/com/coze/openapi/service/service/conversation/ConversationService.java b/api/src/main/java/com/coze/openapi/service/service/conversation/ConversationService.java index 5c0feab3..9a79d93f 100644 --- a/api/src/main/java/com/coze/openapi/service/service/conversation/ConversationService.java +++ b/api/src/main/java/com/coze/openapi/service/service/conversation/ConversationService.java @@ -1,111 +1,112 @@ +/* (C)2024 */ package com.coze.openapi.service.service.conversation; import org.jetbrains.annotations.NotNull; import com.coze.openapi.api.ConversationAPI; import com.coze.openapi.api.ConversationMessageAPI; -import com.coze.openapi.client.connversations.ListConversationReq; -import com.coze.openapi.client.connversations.ListConversationResp; -import com.coze.openapi.client.connversations.model.Conversation; -import com.coze.openapi.client.common.pagination.PageResponse; +import com.coze.openapi.client.common.BaseResponse; +import com.coze.openapi.client.common.pagination.PageFetcher; +import com.coze.openapi.client.common.pagination.PageNumBasedPaginator; +import com.coze.openapi.client.common.pagination.PageRequest; import com.coze.openapi.client.common.pagination.PageResp; +import com.coze.openapi.client.common.pagination.PageResponse; import com.coze.openapi.client.connversations.ClearConversationReq; import com.coze.openapi.client.connversations.ClearConversationResp; import com.coze.openapi.client.connversations.CreateConversationReq; import com.coze.openapi.client.connversations.CreateConversationResp; +import com.coze.openapi.client.connversations.ListConversationReq; +import com.coze.openapi.client.connversations.ListConversationResp; import com.coze.openapi.client.connversations.RetrieveConversationReq; import com.coze.openapi.client.connversations.RetrieveConversationResp; +import com.coze.openapi.client.connversations.model.Conversation; import com.coze.openapi.service.utils.Utils; -import com.coze.openapi.client.common.BaseResponse; -import com.coze.openapi.client.common.pagination.PageFetcher; -import com.coze.openapi.client.common.pagination.PageNumBasedPaginator; -import com.coze.openapi.client.common.pagination.PageRequest; public class ConversationService { - private final ConversationAPI api; - private final MessageService messageApi; - - public ConversationService(ConversationAPI api, ConversationMessageAPI messageApi) { - this.api = api; - this.messageApi = new MessageService(messageApi); - } - - /* - Get the information of specific conversation. - - docs en: https://www.coze.com/docs/developer_guides/retrieve_conversation - docs cn: https://www.coze.cn/docs/developer_guides/retrieve_conversation - * */ - public RetrieveConversationResp retrieve(RetrieveConversationReq req) { - BaseResponse resp = Utils.execute(api.retrieve(req.getConversationID(), req)); - return RetrieveConversationResp.builder() - .conversation(resp.getData()) - .logID(resp.getLogID()) - .build(); + private final ConversationAPI api; + private final MessageService messageApi; + + public ConversationService(ConversationAPI api, ConversationMessageAPI messageApi) { + this.api = api; + this.messageApi = new MessageService(messageApi); + } + + /* + Get the information of specific conversation. + + docs en: https://www.coze.com/docs/developer_guides/retrieve_conversation + docs cn: https://www.coze.cn/docs/developer_guides/retrieve_conversation + * */ + public RetrieveConversationResp retrieve(RetrieveConversationReq req) { + BaseResponse resp = Utils.execute(api.retrieve(req.getConversationID(), req)); + return RetrieveConversationResp.builder() + .conversation(resp.getData()) + .logID(resp.getLogID()) + .build(); + } + + /* + Create a conversation. + Conversation is an interaction between a bot and a user, including one or more messages. + + docs en: https://www.coze.com/docs/developer_guides/create_conversation + docs zh: https://www.coze.cn/docs/developer_guides/create_conversation + * */ + public CreateConversationResp create(CreateConversationReq req) { + BaseResponse resp = Utils.execute(api.create(req, req)); + return CreateConversationResp.builder() + .conversation(resp.getData()) + .logID(resp.getLogID()) + .build(); + } + + public ClearConversationResp clear(ClearConversationReq req) { + return Utils.execute(api.clear(req.getConversationID(), req)).getData(); + } + + public PageResp list(@NotNull ListConversationReq req) { + if (req == null || req.getBotID() == null) { + throw new IllegalArgumentException("botID is required"); } - /* - Create a conversation. - Conversation is an interaction between a bot and a user, including one or more messages. - - docs en: https://www.coze.com/docs/developer_guides/create_conversation - docs zh: https://www.coze.cn/docs/developer_guides/create_conversation - * */ - public CreateConversationResp create(CreateConversationReq req) { - BaseResponse resp = Utils.execute(api.create(req, req)); - return CreateConversationResp.builder() - .conversation(resp.getData()) - .logID(resp.getLogID()) - .build(); - } + Integer pageNum = req.getPageNum(); + Integer pageSize = req.getPageSize(); + String botID = req.getBotID(); + + // 创建分页获取器 + PageFetcher pageFetcher = + request -> { + ListConversationResp resp = + Utils.execute(api.list(botID, request.getPageNum(), request.getPageSize(), req)) + .getData(); + + return PageResponse.builder() + .hasMore(resp.isHasMore()) + .data(resp.getConversations()) + .pageNum(request.getPageNum()) + .pageSize(request.getPageSize()) + .logID(resp.getLogID()) + .build(); + }; + // 创建分页器 + PageNumBasedPaginator paginator = + new PageNumBasedPaginator<>(pageFetcher, pageSize); - public ClearConversationResp clear(ClearConversationReq req) { - return Utils.execute(api.clear(req.getConversationID(), req)).getData(); - } + // 获取当前页数据 + PageRequest initialRequest = PageRequest.builder().pageNum(pageNum).pageSize(pageSize).build(); - public PageResp list(@NotNull ListConversationReq req) { - if (req == null || req.getBotID() == null) { - throw new IllegalArgumentException("botID is required"); - } - - Integer pageNum = req.getPageNum(); - Integer pageSize = req.getPageSize(); - String botID = req.getBotID(); - - // 创建分页获取器 - PageFetcher pageFetcher = request -> { - ListConversationResp resp = Utils.execute(api.list(botID, request.getPageNum(), request.getPageSize(), req)).getData(); - - return PageResponse.builder() - .hasMore(resp.isHasMore()) - .data(resp.getConversations()) - .pageNum(request.getPageNum()) - .pageSize(request.getPageSize()) - .logID(resp.getLogID()) - .build(); - }; + PageResponse firstPage = pageFetcher.fetch(initialRequest); - // 创建分页器 - PageNumBasedPaginator paginator = new PageNumBasedPaginator<>(pageFetcher, pageSize); - - // 获取当前页数据 - PageRequest initialRequest = PageRequest.builder() - .pageNum(pageNum) - .pageSize(pageSize) - .build(); - - PageResponse firstPage = pageFetcher.fetch(initialRequest); - - return PageResp.builder() - .items(firstPage.getData()) - .iterator(paginator) - .logID(firstPage.getLogID()) - .hasMore(firstPage.isHasMore()) - .build(); - } + return PageResp.builder() + .items(firstPage.getData()) + .iterator(paginator) + .logID(firstPage.getLogID()) + .hasMore(firstPage.isHasMore()) + .build(); + } - public MessageService messages() { - return messageApi; - } + public MessageService messages() { + return messageApi; + } } diff --git a/api/src/main/java/com/coze/openapi/service/service/conversation/MessageService.java b/api/src/main/java/com/coze/openapi/service/service/conversation/MessageService.java index c64baefd..985cb3fa 100644 --- a/api/src/main/java/com/coze/openapi/service/service/conversation/MessageService.java +++ b/api/src/main/java/com/coze/openapi/service/service/conversation/MessageService.java @@ -1,13 +1,14 @@ +/* (C)2024 */ package com.coze.openapi.service.service.conversation; import org.jetbrains.annotations.NotNull; import com.coze.openapi.api.ConversationMessageAPI; -import com.coze.openapi.client.common.pagination.PageResponse; -import com.coze.openapi.client.common.pagination.PageResp; import com.coze.openapi.client.common.BaseResponse; import com.coze.openapi.client.common.pagination.PageFetcher; import com.coze.openapi.client.common.pagination.PageRequest; +import com.coze.openapi.client.common.pagination.PageResp; +import com.coze.openapi.client.common.pagination.PageResponse; import com.coze.openapi.client.common.pagination.TokenBasedPaginator; import com.coze.openapi.client.connversations.message.CreateMessageReq; import com.coze.openapi.client.connversations.message.CreateMessageResp; @@ -15,137 +16,126 @@ import com.coze.openapi.client.connversations.message.DeleteMessageResp; import com.coze.openapi.client.connversations.message.ListMessageReq; import com.coze.openapi.client.connversations.message.ListMessageResp; -import com.coze.openapi.client.connversations.message.UpdateMessageReq; -import com.coze.openapi.client.connversations.message.UpdateMessageResp; import com.coze.openapi.client.connversations.message.RetrieveMessageReq; import com.coze.openapi.client.connversations.message.RetrieveMessageResp; +import com.coze.openapi.client.connversations.message.UpdateMessageReq; +import com.coze.openapi.client.connversations.message.UpdateMessageResp; import com.coze.openapi.client.connversations.message.model.Message; import com.coze.openapi.service.utils.Utils; public class MessageService { - private final ConversationMessageAPI api; + private final ConversationMessageAPI api; - public MessageService(ConversationMessageAPI api) { - this.api = api; - } + public MessageService(ConversationMessageAPI api) { + this.api = api; + } + + /* + Create a message and add it to the specified conversation. - /* - Create a message and add it to the specified conversation. - - docs en: https://www.coze.com/docs/developer_guides/create_message - docs cn: https://www.coze.cn/docs/developer_guides/create_message - * */ - public CreateMessageResp create(String conversationID, CreateMessageReq req) { - if (conversationID == null) { - throw new IllegalArgumentException("conversationID is required"); - } - BaseResponse resp = Utils.execute(api.create(conversationID, req, req)); - return CreateMessageResp.builder() - .message(resp.getData()) - .logID(resp.getLogID()) - .build(); + docs en: https://www.coze.com/docs/developer_guides/create_message + docs cn: https://www.coze.cn/docs/developer_guides/create_message + * */ + public CreateMessageResp create(String conversationID, CreateMessageReq req) { + if (conversationID == null) { + throw new IllegalArgumentException("conversationID is required"); } + BaseResponse resp = Utils.execute(api.create(conversationID, req, req)); + return CreateMessageResp.builder().message(resp.getData()).logID(resp.getLogID()).build(); + } + + /* + Create a message and add it to the specified conversation. + + docs en: https://www.coze.com/docs/developer_guides/create_message + docs cn: https://www.coze.cn/docs/developer_guides/create_message + * */ + public CreateMessageResp create(CreateMessageReq req) { + if (req == null || req.getConversationID() == null) { + throw new IllegalArgumentException("conversationID is required"); + } + + return create(req.getConversationID(), req); + } + + /* + * Get the message list of a specified conversation. - /* - Create a message and add it to the specified conversation. - - docs en: https://www.coze.com/docs/developer_guides/create_message - docs cn: https://www.coze.cn/docs/developer_guides/create_message - * */ - public CreateMessageResp create(CreateMessageReq req) { - if (req == null || req.getConversationID() == null) { - throw new IllegalArgumentException("conversationID is required"); - } - - return create(req.getConversationID(), req); + docs en: https://www.coze.com/docs/developer_guides/list_message + docs zh: https://www.coze.cn/docs/developer_guides/list_message + * */ + public PageResp list(@NotNull ListMessageReq req) { + if (req == null || req.getConversationID() == null) { + throw new IllegalArgumentException("conversationID is required"); } - /* - * Get the message list of a specified conversation. - - docs en: https://www.coze.com/docs/developer_guides/list_message - docs zh: https://www.coze.cn/docs/developer_guides/list_message - * */ - public PageResp list(@NotNull ListMessageReq req) { - if (req == null || req.getConversationID() == null) { - throw new IllegalArgumentException("conversationID is required"); - } - - String conversationID = req.getConversationID(); - Integer pageSize = req.getLimit(); - - // 创建分页获取器 - PageFetcher pageFetcher = request -> { - req.setAfterID(request.getPageToken()); // 设置 lastID - ListMessageResp resp = Utils.execute(api.list(conversationID, req, req)); - - return PageResponse.builder() - .hasMore(resp.getData().size() >= pageSize) - .data(resp.getData()) - .lastID(resp.getLastID()) // 使用 firstID 作为上一页的 token - .nextID(resp.getFirstID()) // 使用 lastID 作为下一页的 token - .build(); + String conversationID = req.getConversationID(); + Integer pageSize = req.getLimit(); + + // 创建分页获取器 + PageFetcher pageFetcher = + request -> { + req.setAfterID(request.getPageToken()); // 设置 lastID + ListMessageResp resp = Utils.execute(api.list(conversationID, req, req)); + + return PageResponse.builder() + .hasMore(resp.getData().size() >= pageSize) + .data(resp.getData()) + .lastID(resp.getLastID()) // 使用 firstID 作为上一页的 token + .nextID(resp.getFirstID()) // 使用 lastID 作为下一页的 token + .build(); }; - // 创建基于 token 的分页器 - TokenBasedPaginator paginator = new TokenBasedPaginator<>(pageFetcher, req.getLimit()); - - // 获取当前页数据 - PageRequest initialRequest = PageRequest.builder() - .pageSize(pageSize) - .pageToken(req.getBeforeID()) - .build(); - - PageResponse currentPage = pageFetcher.fetch(initialRequest); - - return PageResp.builder() - .items(currentPage.getData()) - .iterator(paginator) - .lastID(currentPage.getNextID()) - .build(); - } + // 创建基于 token 的分页器 + TokenBasedPaginator paginator = new TokenBasedPaginator<>(pageFetcher, req.getLimit()); + // 获取当前页数据 + PageRequest initialRequest = + PageRequest.builder().pageSize(pageSize).pageToken(req.getBeforeID()).build(); - /* - * Get the detailed information of specified message. - - docs en: https://www.coze.com/docs/developer_guides/retrieve_message - docs zh: https://www.coze.cn/docs/developer_guides/retrieve_message - * */ - public RetrieveMessageResp retrieve(RetrieveMessageReq req) { - if (req == null || req.getConversationID() == null || req.getMessageID() == null) { - throw new IllegalArgumentException("conversationID and messageID are required"); - } - BaseResponse resp = Utils.execute(api.retrieve(req.getConversationID(), req.getMessageID(), req)); - return RetrieveMessageResp.builder() - .message(resp.getData()) - .logID(resp.getLogID()) - .build(); - } + PageResponse currentPage = pageFetcher.fetch(initialRequest); - /* - * Modify a message, supporting the modification of message content, additional content, and message type. - - docs en: https://www.coze.com/docs/developer_guides/modify_message - docs cn: https://www.coze.cn/docs/developer_guides/modify_message - * */ - public UpdateMessageResp update(UpdateMessageReq req) { - if (req == null || req.getConversationID() == null || req.getMessageID() == null) { - throw new IllegalArgumentException("conversationID and messageID are required"); - } - return Utils.execute(api.update(req.getConversationID(), req.getMessageID(), req, req)); - } + return PageResp.builder() + .items(currentPage.getData()) + .iterator(paginator) + .lastID(currentPage.getNextID()) + .build(); + } - public DeleteMessageResp delete(DeleteMessageReq req) { - if (req == null || req.getConversationID() == null || req.getMessageID() == null) { - throw new IllegalArgumentException("conversationID and messageID are required"); - } - BaseResponse resp = Utils.execute(api.delete(req.getConversationID(), req.getMessageID(), req)); - return DeleteMessageResp.builder() - .message(resp.getData()) - .logID(resp.getLogID()) - .build(); - } + /* + * Get the detailed information of specified message. + docs en: https://www.coze.com/docs/developer_guides/retrieve_message + docs zh: https://www.coze.cn/docs/developer_guides/retrieve_message + * */ + public RetrieveMessageResp retrieve(RetrieveMessageReq req) { + if (req == null || req.getConversationID() == null || req.getMessageID() == null) { + throw new IllegalArgumentException("conversationID and messageID are required"); + } + BaseResponse resp = + Utils.execute(api.retrieve(req.getConversationID(), req.getMessageID(), req)); + return RetrieveMessageResp.builder().message(resp.getData()).logID(resp.getLogID()).build(); + } + + /* + * Modify a message, supporting the modification of message content, additional content, and message type. + + docs en: https://www.coze.com/docs/developer_guides/modify_message + docs cn: https://www.coze.cn/docs/developer_guides/modify_message + * */ + public UpdateMessageResp update(UpdateMessageReq req) { + if (req == null || req.getConversationID() == null || req.getMessageID() == null) { + throw new IllegalArgumentException("conversationID and messageID are required"); + } + return Utils.execute(api.update(req.getConversationID(), req.getMessageID(), req, req)); + } + public DeleteMessageResp delete(DeleteMessageReq req) { + if (req == null || req.getConversationID() == null || req.getMessageID() == null) { + throw new IllegalArgumentException("conversationID and messageID are required"); + } + BaseResponse resp = + Utils.execute(api.delete(req.getConversationID(), req.getMessageID(), req)); + return DeleteMessageResp.builder().message(resp.getData()).logID(resp.getLogID()).build(); + } } diff --git a/api/src/main/java/com/coze/openapi/service/service/dataset/DatasetService.java b/api/src/main/java/com/coze/openapi/service/service/dataset/DatasetService.java index 6cdc1581..78e72a40 100644 --- a/api/src/main/java/com/coze/openapi/service/service/dataset/DatasetService.java +++ b/api/src/main/java/com/coze/openapi/service/service/dataset/DatasetService.java @@ -1,16 +1,16 @@ +/* (C)2024 */ package com.coze.openapi.service.service.dataset; import com.coze.openapi.api.DocumentAPI; public class DatasetService { - private final DocumentService documentAPI; + private final DocumentService documentAPI; - public DatasetService(DocumentAPI api) { - this.documentAPI = new DocumentService(api); - } - - public DocumentService documents() { - return this.documentAPI; - } + public DatasetService(DocumentAPI api) { + this.documentAPI = new DocumentService(api); + } + public DocumentService documents() { + return this.documentAPI; + } } diff --git a/api/src/main/java/com/coze/openapi/service/service/dataset/DocumentService.java b/api/src/main/java/com/coze/openapi/service/service/dataset/DocumentService.java index 71cd4bfa..37a96f80 100644 --- a/api/src/main/java/com/coze/openapi/service/service/dataset/DocumentService.java +++ b/api/src/main/java/com/coze/openapi/service/service/dataset/DocumentService.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.service.service.dataset; import org.jetbrains.annotations.NotNull; @@ -6,6 +7,7 @@ import com.coze.openapi.client.common.pagination.PageFetcher; import com.coze.openapi.client.common.pagination.PageNumBasedPaginator; import com.coze.openapi.client.common.pagination.PageRequest; +import com.coze.openapi.client.common.pagination.PageResp; import com.coze.openapi.client.common.pagination.PageResponse; import com.coze.openapi.client.dataset.document.CreateDocumentReq; import com.coze.openapi.client.dataset.document.CreateDocumentResp; @@ -16,87 +18,88 @@ import com.coze.openapi.client.dataset.document.UpdateDocumentReq; import com.coze.openapi.client.dataset.document.UpdateDocumentResp; import com.coze.openapi.client.dataset.document.model.Document; -import com.coze.openapi.client.common.pagination.PageResp; import com.coze.openapi.service.utils.Utils; public class DocumentService { - private final DocumentAPI api; - - public DocumentService(DocumentAPI api) { - this.api = api; - } - - public CreateDocumentResp create(CreateDocumentReq req) { - return Utils.execute(api.create(req, req)); - } - - /* - * Modify the knowledge base file name and update strategy. - - docs en: https://www.coze.com/docs/developer_guides/modify_knowledge_files - docs zh: https://www.coze.cn/docs/developer_guides/modify_knowledge_files - * */ - public UpdateDocumentResp update(UpdateDocumentReq req) { - String logID = Utils.execute(api.update(req, req)).getLogID(); - return UpdateDocumentResp.builder().logID(logID).build(); + private final DocumentAPI api; + + public DocumentService(DocumentAPI api) { + this.api = api; + } + + public CreateDocumentResp create(CreateDocumentReq req) { + return Utils.execute(api.create(req, req)); + } + + /* + * Modify the knowledge base file name and update strategy. + + docs en: https://www.coze.com/docs/developer_guides/modify_knowledge_files + docs zh: https://www.coze.cn/docs/developer_guides/modify_knowledge_files + * */ + public UpdateDocumentResp update(UpdateDocumentReq req) { + String logID = Utils.execute(api.update(req, req)).getLogID(); + return UpdateDocumentResp.builder().logID(logID).build(); + } + + /* + * Delete text, images, sheets, and other files in the knowledge base, supporting batch deletion. + + docs en: https://www.coze.com/docs/developer_guides/delete_knowledge_files + docs zh: https://www.coze.cn/docs/developer_guides/delete_knowledge_files + * */ + public DeleteDocumentResp delete(DeleteDocumentReq req) { + String logID = Utils.execute(api.delete(req, req)).getLogID(); + return DeleteDocumentResp.builder().logID(logID).build(); + } + + /* + * View the file list of a specified knowledge base, which includes lists of documents, spreadsheets, or images. + + docs en: https://www.coze.com/docs/developer_guides/list_knowledge_files + docs zh: https://www.coze.cn/docs/developer_guides/list_knowledge_files + * */ + public PageResp list(@NotNull ListDocumentReq req) { + if (req == null || req.getDatasetID() == null) { + throw new IllegalArgumentException("req is required"); } - /* - * Delete text, images, sheets, and other files in the knowledge base, supporting batch deletion. + Integer pageNum = req.getPage(); + Integer pageSize = req.getSize(); + + // 创建分页获取器 + PageFetcher pageFetcher = + request -> { + ListDocumentResp resp = + Utils.execute( + api.list( + ListDocumentReq.of( + req.getDatasetID(), request.getPageNum(), request.getPageSize()), + req)); + return PageResponse.builder() + .hasMore(resp.getDocumentInfos().size() == request.getPageSize()) + .data(resp.getDocumentInfos()) + .pageNum(request.getPageNum()) + .logID(resp.getLogID()) + .pageSize(request.getPageSize()) + .total(resp.getTotal().intValue()) + .build(); + }; - docs en: https://www.coze.com/docs/developer_guides/delete_knowledge_files - docs zh: https://www.coze.cn/docs/developer_guides/delete_knowledge_files - * */ - public DeleteDocumentResp delete(DeleteDocumentReq req) { - String logID = Utils.execute(api.delete(req, req)).getLogID(); - return DeleteDocumentResp.builder().logID(logID).build(); - } + // 创建分页器 + PageNumBasedPaginator paginator = new PageNumBasedPaginator<>(pageFetcher, pageSize); - /* - * View the file list of a specified knowledge base, which includes lists of documents, spreadsheets, or images. - - docs en: https://www.coze.com/docs/developer_guides/list_knowledge_files - docs zh: https://www.coze.cn/docs/developer_guides/list_knowledge_files - * */ - public PageResp list(@NotNull ListDocumentReq req) { - if (req == null || req.getDatasetID() == null) { - throw new IllegalArgumentException("req is required"); - } - - Integer pageNum = req.getPage(); - Integer pageSize = req.getSize(); - - // 创建分页获取器 - PageFetcher pageFetcher = request -> { - ListDocumentResp resp = Utils.execute(api.list(ListDocumentReq.of(req.getDatasetID(), request.getPageNum(), request.getPageSize()), req)); - return PageResponse.builder() - .hasMore(resp.getDocumentInfos().size() == request.getPageSize()) - .data(resp.getDocumentInfos()) - .pageNum(request.getPageNum()) - .logID(resp.getLogID()) - .pageSize(request.getPageSize()) - .total(resp.getTotal().intValue()) - .build(); - }; + // 获取当前页数据 + PageRequest initialRequest = PageRequest.builder().pageNum(pageNum).pageSize(pageSize).build(); - // 创建分页器 - PageNumBasedPaginator paginator = new PageNumBasedPaginator<>(pageFetcher, pageSize); - - // 获取当前页数据 - PageRequest initialRequest = PageRequest.builder() - .pageNum(pageNum) - .pageSize(pageSize) - .build(); - - PageResponse currentPage = pageFetcher.fetch(initialRequest); - - return PageResp.builder() - .total(currentPage.getTotal()) - .items(currentPage.getData()) - .iterator(paginator) - .hasMore(currentPage.isHasMore()) - .logID(currentPage.getLogID()) - .build(); - } + PageResponse currentPage = pageFetcher.fetch(initialRequest); + return PageResp.builder() + .total(currentPage.getTotal()) + .items(currentPage.getData()) + .iterator(paginator) + .hasMore(currentPage.isHasMore()) + .logID(currentPage.getLogID()) + .build(); + } } diff --git a/api/src/main/java/com/coze/openapi/service/service/file/FileService.java b/api/src/main/java/com/coze/openapi/service/service/file/FileService.java index 02abc09c..1468d177 100644 --- a/api/src/main/java/com/coze/openapi/service/service/file/FileService.java +++ b/api/src/main/java/com/coze/openapi/service/service/file/FileService.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.service.service.file; import java.io.File; @@ -17,58 +18,53 @@ import okhttp3.RequestBody; public class FileService { - private final FileAPI api; + private final FileAPI api; - public FileService(FileAPI api) { - this.api = api; - } - - /** - * Upload files to Coze platform. - * - * Local files cannot be used directly in messages. Before creating messages or conversations, - * you need to call this interface to upload local files to the platform first. - * After uploading the file, you can use it directly in multimodal content in messages - * by specifying the file_id. - * - * docs en: https://www.coze.com/docs/developer_guides/upload_files - * docs zh: https://www.coze.cn/docs/developer_guides/upload_files + public FileService(FileAPI api) { + this.api = api; + } - */ - public UploadFileResp upload(UploadFileReq req) { - if (req.getFilePath() != null) { - File file = new File(req.getFilePath()); - return uploadFile(file, file.getName(), req); - } - if (req.getFileBytes() != null) { - return uploadFile(req.getFileBytes(), req.getFileName(), req); - } - if (req.getFile() != null) { - return uploadFile(req.getFile(), req.getFileName(), req); - } - throw new IllegalArgumentException("file source is required"); + /** + * Upload files to Coze platform. + * + *

Local files cannot be used directly in messages. Before creating messages or conversations, + * you need to call this interface to upload local files to the platform first. After uploading + * the file, you can use it directly in multimodal content in messages by specifying the file_id. + * + *

docs en: https://www.coze.com/docs/developer_guides/upload_files docs zh: + * https://www.coze.cn/docs/developer_guides/upload_files + */ + public UploadFileResp upload(UploadFileReq req) { + if (req.getFilePath() != null) { + File file = new File(req.getFilePath()); + return uploadFile(file, file.getName(), req); } + if (req.getFileBytes() != null) { + return uploadFile(req.getFileBytes(), req.getFileName(), req); + } + if (req.getFile() != null) { + return uploadFile(req.getFile(), req.getFileName(), req); + } + throw new IllegalArgumentException("file source is required"); + } - /** - * Internal unified upload processing method - */ - private UploadFileResp uploadFile(Object fileSource, String filename, BaseReq req) { - RequestBody requestFile; - if (fileSource instanceof File) { - requestFile = RequestBody.create((File) fileSource, MediaType.parse("multipart/form-data")); - } else { - requestFile = RequestBody.create((byte[]) fileSource, MediaType.parse("multipart/form-data")); - } - - MultipartBody.Part body = MultipartBody.Part.createFormData("file", filename, requestFile); - - BaseResponse resp = Utils.execute(api.upload(body, req)); - return UploadFileResp.builder().fileInfo(resp.getData()).logID(resp.getLogID()).build(); + /** Internal unified upload processing method */ + private UploadFileResp uploadFile(Object fileSource, String filename, BaseReq req) { + RequestBody requestFile; + if (fileSource instanceof File) { + requestFile = RequestBody.create((File) fileSource, MediaType.parse("multipart/form-data")); + } else { + requestFile = RequestBody.create((byte[]) fileSource, MediaType.parse("multipart/form-data")); } - public RetrieveFileResp retrieve(RetrieveFileReq req) { - BaseResponse resp = Utils.execute(api.retrieve(req.getFileID(), req)); - return RetrieveFileResp.builder().fileInfo(resp.getData()).logID(resp.getLogID()).build(); - } + MultipartBody.Part body = MultipartBody.Part.createFormData("file", filename, requestFile); + + BaseResponse resp = Utils.execute(api.upload(body, req)); + return UploadFileResp.builder().fileInfo(resp.getData()).logID(resp.getLogID()).build(); + } + public RetrieveFileResp retrieve(RetrieveFileReq req) { + BaseResponse resp = Utils.execute(api.retrieve(req.getFileID(), req)); + return RetrieveFileResp.builder().fileInfo(resp.getData()).logID(resp.getLogID()).build(); + } } diff --git a/api/src/main/java/com/coze/openapi/service/service/workflow/EventCallback.java b/api/src/main/java/com/coze/openapi/service/service/workflow/EventCallback.java index cf13b762..22bd8f5c 100644 --- a/api/src/main/java/com/coze/openapi/service/service/workflow/EventCallback.java +++ b/api/src/main/java/com/coze/openapi/service/service/workflow/EventCallback.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.service.service.workflow; import java.io.BufferedReader; @@ -12,30 +13,30 @@ public class EventCallback extends AbstractEventCallback { - public EventCallback(FlowableEmitter emitter) { - super(emitter); - } - - @Override - protected boolean processLine(String line, BufferedReader reader, String logID) throws IOException { - if (line.startsWith("id:")) { - String id = line.substring(3).trim(); - String event = reader.readLine().substring(6).trim(); - String data = reader.readLine().substring(5).trim(); - - Map eventLine = new HashMap<>(); - eventLine.put("id", id); - eventLine.put("event", event); - eventLine.put("data", data); - - WorkflowEvent eventData = WorkflowEvent.parseEvent(eventLine, logID); - - if (eventData != null) { - emitter.onNext(eventData); - return eventData.isDone(); - } - } - return false; + public EventCallback(FlowableEmitter emitter) { + super(emitter); + } + + @Override + protected boolean processLine(String line, BufferedReader reader, String logID) + throws IOException { + if (line.startsWith("id:")) { + String id = line.substring(3).trim(); + String event = reader.readLine().substring(6).trim(); + String data = reader.readLine().substring(5).trim(); + + Map eventLine = new HashMap<>(); + eventLine.put("id", id); + eventLine.put("event", event); + eventLine.put("data", data); + + WorkflowEvent eventData = WorkflowEvent.parseEvent(eventLine, logID); + + if (eventData != null) { + emitter.onNext(eventData); + return eventData.isDone(); + } } + return false; + } } - \ No newline at end of file diff --git a/api/src/main/java/com/coze/openapi/service/service/workflow/WorkflowRunHistoryService.java b/api/src/main/java/com/coze/openapi/service/service/workflow/WorkflowRunHistoryService.java index 2e043d74..b2ca8b0f 100644 --- a/api/src/main/java/com/coze/openapi/service/service/workflow/WorkflowRunHistoryService.java +++ b/api/src/main/java/com/coze/openapi/service/service/workflow/WorkflowRunHistoryService.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.service.service.workflow; import java.util.List; @@ -10,22 +11,23 @@ import com.coze.openapi.service.utils.Utils; public class WorkflowRunHistoryService { - private final WorkflowRunHistoryAPI workflowRunHistoryAPI; + private final WorkflowRunHistoryAPI workflowRunHistoryAPI; - public WorkflowRunHistoryService(WorkflowRunHistoryAPI workflowRunAPI) { - this.workflowRunHistoryAPI = workflowRunAPI; - } + public WorkflowRunHistoryService(WorkflowRunHistoryAPI workflowRunAPI) { + this.workflowRunHistoryAPI = workflowRunAPI; + } - /* - * After the workflow runs async, retrieve the execution results. - * docs cn: https://www.coze.cn/docs/developer_guides/workflow_history - * docs en: https://www.coze.com/docs/developer_guides/workflow_history - * */ - public RetrieveRunHistoryResp retrieve(RetrieveRunHistoryReq req) { - BaseResponse> resp = Utils.execute(workflowRunHistoryAPI.retrieve(req.getWorkflowID(), req.getExecuteID(), req)); - return RetrieveRunHistoryResp.builder() - .histories(resp.getData()) - .logID(resp.getLogID()) - .build(); - } + /* + * After the workflow runs async, retrieve the execution results. + * docs cn: https://www.coze.cn/docs/developer_guides/workflow_history + * docs en: https://www.coze.com/docs/developer_guides/workflow_history + * */ + public RetrieveRunHistoryResp retrieve(RetrieveRunHistoryReq req) { + BaseResponse> resp = + Utils.execute(workflowRunHistoryAPI.retrieve(req.getWorkflowID(), req.getExecuteID(), req)); + return RetrieveRunHistoryResp.builder() + .histories(resp.getData()) + .logID(resp.getLogID()) + .build(); + } } diff --git a/api/src/main/java/com/coze/openapi/service/service/workflow/WorkflowRunService.java b/api/src/main/java/com/coze/openapi/service/service/workflow/WorkflowRunService.java index b8948061..2b610bbc 100644 --- a/api/src/main/java/com/coze/openapi/service/service/workflow/WorkflowRunService.java +++ b/api/src/main/java/com/coze/openapi/service/service/workflow/WorkflowRunService.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.service.service.workflow; import com.coze.openapi.api.WorkflowRunAPI; @@ -14,55 +15,54 @@ import retrofit2.Call; public class WorkflowRunService { - - private final WorkflowRunAPI workflowRunAPI; - private final WorkflowRunHistoryService historyService; + private final WorkflowRunAPI workflowRunAPI; - public WorkflowRunService(WorkflowRunAPI runAPI, WorkflowRunHistoryAPI historyService) { - this.workflowRunAPI = runAPI; - this.historyService = new WorkflowRunHistoryService(historyService); - } + private final WorkflowRunHistoryService historyService; - /* - * Run the published workflow. - * This API is in non-streaming response mode. For nodes that support streaming output, - * you should run the API Run workflow (streaming response) to obtain streaming responses. - * - * docs en: https://www.coze.com/docs/developer_guides/workflow_run - * docs cn: https://www.coze.cn/docs/developer_guides/workflow_run - * */ - public RunWorkflowResp create(RunWorkflowReq req) { - return Utils.execute(workflowRunAPI.run(req, req)); - } + public WorkflowRunService(WorkflowRunAPI runAPI, WorkflowRunHistoryAPI historyService) { + this.workflowRunAPI = runAPI; + this.historyService = new WorkflowRunHistoryService(historyService); + } - /* - * Run the published workflow. - * This API is in non-streaming response mode. For nodes that support streaming output, - * you should run the API Run workflow (streaming response) to obtain streaming responses. - * - * docs en: https://www.coze.com/docs/developer_guides/workflow_run - * docs cn: https://www.coze.cn/docs/developer_guides/workflow_run - * */ - public Flowable stream(RunWorkflowReq req) { - return stream(workflowRunAPI.stream(req, req)); - } + /* + * Run the published workflow. + * This API is in non-streaming response mode. For nodes that support streaming output, + * you should run the API Run workflow (streaming response) to obtain streaming responses. + * + * docs en: https://www.coze.com/docs/developer_guides/workflow_run + * docs cn: https://www.coze.cn/docs/developer_guides/workflow_run + * */ + public RunWorkflowResp create(RunWorkflowReq req) { + return Utils.execute(workflowRunAPI.run(req, req)); + } - /* - * docs cn: https://www.coze.cn/docs/developer_guides/workflow_resume - * docs en: https://www.coze.com/docs/developer_guides/workflow_resume - * */ - public Flowable resume(ResumeRunReq req) { - return stream(workflowRunAPI.resume(req, req)); - } + /* + * Run the published workflow. + * This API is in non-streaming response mode. For nodes that support streaming output, + * you should run the API Run workflow (streaming response) to obtain streaming responses. + * + * docs en: https://www.coze.com/docs/developer_guides/workflow_run + * docs cn: https://www.coze.cn/docs/developer_guides/workflow_run + * */ + public Flowable stream(RunWorkflowReq req) { + return stream(workflowRunAPI.stream(req, req)); + } + /* + * docs cn: https://www.coze.cn/docs/developer_guides/workflow_resume + * docs en: https://www.coze.com/docs/developer_guides/workflow_resume + * */ + public Flowable resume(ResumeRunReq req) { + return stream(workflowRunAPI.resume(req, req)); + } - public static Flowable stream(Call apiCall) { - return Flowable.create(emitter -> apiCall.enqueue(new EventCallback(emitter)), BackpressureStrategy.BUFFER); - } + public static Flowable stream(Call apiCall) { + return Flowable.create( + emitter -> apiCall.enqueue(new EventCallback(emitter)), BackpressureStrategy.BUFFER); + } - public WorkflowRunHistoryService histories(){ - return historyService; - } - + public WorkflowRunHistoryService histories() { + return historyService; + } } diff --git a/api/src/main/java/com/coze/openapi/service/service/workflow/WorkflowService.java b/api/src/main/java/com/coze/openapi/service/service/workflow/WorkflowService.java index eb33ddaf..0d72281c 100644 --- a/api/src/main/java/com/coze/openapi/service/service/workflow/WorkflowService.java +++ b/api/src/main/java/com/coze/openapi/service/service/workflow/WorkflowService.java @@ -1,16 +1,17 @@ +/* (C)2024 */ package com.coze.openapi.service.service.workflow; import com.coze.openapi.api.WorkflowRunAPI; import com.coze.openapi.api.WorkflowRunHistoryAPI; public class WorkflowService { - private final WorkflowRunService runService; + private final WorkflowRunService runService; - public WorkflowService(WorkflowRunAPI api, WorkflowRunHistoryAPI historyAPI) { - this.runService = new WorkflowRunService(api, historyAPI); - } + public WorkflowService(WorkflowRunAPI api, WorkflowRunHistoryAPI historyAPI) { + this.runService = new WorkflowRunService(api, historyAPI); + } - public WorkflowRunService runs(){ - return runService; - } + public WorkflowRunService runs() { + return runService; + } } diff --git a/api/src/main/java/com/coze/openapi/service/service/workspace/WorkspaceService.java b/api/src/main/java/com/coze/openapi/service/service/workspace/WorkspaceService.java index a9942e31..fabbf6e4 100644 --- a/api/src/main/java/com/coze/openapi/service/service/workspace/WorkspaceService.java +++ b/api/src/main/java/com/coze/openapi/service/service/workspace/WorkspaceService.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package com.coze.openapi.service.service.workspace; import com.coze.openapi.api.WorkspaceAPI; @@ -5,61 +6,58 @@ import com.coze.openapi.client.common.pagination.PageFetcher; import com.coze.openapi.client.common.pagination.PageNumBasedPaginator; import com.coze.openapi.client.common.pagination.PageRequest; -import com.coze.openapi.client.common.pagination.PageResponse; import com.coze.openapi.client.common.pagination.PageResp; +import com.coze.openapi.client.common.pagination.PageResponse; import com.coze.openapi.client.workspace.ListWorkspaceReq; import com.coze.openapi.client.workspace.ListWorkspaceResp; import com.coze.openapi.client.workspace.model.Workspace; import com.coze.openapi.service.utils.Utils; public class WorkspaceService { - private final WorkspaceAPI workspaceAPI; - - public WorkspaceService(WorkspaceAPI workspaceAPI) { - this.workspaceAPI = workspaceAPI; - } + private final WorkspaceAPI workspaceAPI; - public PageResp list(ListWorkspaceReq req) { - if (req == null) { - throw new IllegalArgumentException("req is required"); - } + public WorkspaceService(WorkspaceAPI workspaceAPI) { + this.workspaceAPI = workspaceAPI; + } - Integer pageNum = req.getPageNum(); - Integer pageSize = req.getPageSize(); + public PageResp list(ListWorkspaceReq req) { + if (req == null) { + throw new IllegalArgumentException("req is required"); + } - // create paginator - PageFetcher pageFetcher = request -> { - BaseResponse resp = Utils.execute( - workspaceAPI.list(request.getPageNum(), request.getPageSize(), req) - ); - - return PageResponse.builder() - .hasMore(resp.getData().getWorkspaces().size() == request.getPageSize()) - .data(resp.getData().getWorkspaces()) - .pageNum(request.getPageNum()) - .pageSize(request.getPageSize()) - .total(resp.getData().getTotalCount()) - .logID(resp.getLogID()) - .build(); + Integer pageNum = req.getPageNum(); + Integer pageSize = req.getPageSize(); + + // create paginator + PageFetcher pageFetcher = + request -> { + BaseResponse resp = + Utils.execute(workspaceAPI.list(request.getPageNum(), request.getPageSize(), req)); + + return PageResponse.builder() + .hasMore(resp.getData().getWorkspaces().size() == request.getPageSize()) + .data(resp.getData().getWorkspaces()) + .pageNum(request.getPageNum()) + .pageSize(request.getPageSize()) + .total(resp.getData().getTotalCount()) + .logID(resp.getLogID()) + .build(); }; - // create paginator - PageNumBasedPaginator paginator = new PageNumBasedPaginator<>(pageFetcher, pageSize); + // create paginator + PageNumBasedPaginator paginator = new PageNumBasedPaginator<>(pageFetcher, pageSize); - // get data from current page - PageRequest initialRequest = PageRequest.builder() - .pageNum(pageNum) - .pageSize(pageSize) - .build(); - - PageResponse firstPage = pageFetcher.fetch(initialRequest); + // get data from current page + PageRequest initialRequest = PageRequest.builder().pageNum(pageNum).pageSize(pageSize).build(); - return PageResp.builder() - .total(firstPage.getTotal()) - .items(firstPage.getData()) - .iterator(paginator) - .hasMore(firstPage.isHasMore()) - .logID(firstPage.getLogID()) - .build(); - } + PageResponse firstPage = pageFetcher.fetch(initialRequest); + + return PageResp.builder() + .total(firstPage.getTotal()) + .items(firstPage.getData()) + .iterator(paginator) + .hasMore(firstPage.isHasMore()) + .logID(firstPage.getLogID()) + .build(); + } } diff --git a/api/src/main/java/com/coze/openapi/service/utils/UserAgentInterceptor.java b/api/src/main/java/com/coze/openapi/service/utils/UserAgentInterceptor.java index bc03a80b..5b139c69 100644 --- a/api/src/main/java/com/coze/openapi/service/utils/UserAgentInterceptor.java +++ b/api/src/main/java/com/coze/openapi/service/utils/UserAgentInterceptor.java @@ -1,78 +1,73 @@ +/* (C)2024 */ package com.coze.openapi.service.utils; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + import com.fasterxml.jackson.databind.ObjectMapper; + import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - public class UserAgentInterceptor implements Interceptor { - @Override - public Response intercept(Chain chain) throws IOException { - Request request = chain.request() - .newBuilder() - .addHeader("User-Agent", getUserAgent()) - .addHeader("X-Coze-Client-User-Agent", getCozeClientUserAgent()) - .build(); - return chain.proceed(request); - } - - public static final String VERSION = "1.0.0"; // 假设版本号 - private static final ObjectMapper objectMapper = new ObjectMapper(); + @Override + public Response intercept(Chain chain) throws IOException { + Request request = + chain + .request() + .newBuilder() + .addHeader("User-Agent", getUserAgent()) + .addHeader("X-Coze-Client-User-Agent", getCozeClientUserAgent()) + .build(); + return chain.proceed(request); + } - /** - * 获取操作系统版本 - */ - private static String getOsVersion() { - String osName = System.getProperty("os.name").toLowerCase(); - String osVersion; + public static final String VERSION = "1.0.0"; // 假设版本号 + private static final ObjectMapper objectMapper = new ObjectMapper(); - if (osName.contains("mac")) { - osVersion = System.getProperty("os.version"); - } else if (osName.contains("windows")) { - osVersion = System.getProperty("os.version"); - } else if (osName.contains("linux")) { - osVersion = System.getProperty("os.version"); - } else { - osVersion = System.getProperty("os.version"); - } + /** 获取操作系统版本 */ + private static String getOsVersion() { + String osName = System.getProperty("os.name").toLowerCase(); + String osVersion; - return osVersion; + if (osName.contains("mac")) { + osVersion = System.getProperty("os.version"); + } else if (osName.contains("windows")) { + osVersion = System.getProperty("os.version"); + } else if (osName.contains("linux")) { + osVersion = System.getProperty("os.version"); + } else { + osVersion = System.getProperty("os.version"); } - /** - * 获取用户代理字符串 - */ - private static String getUserAgent() { - String javaVersion = System.getProperty("java.version").split("\\.")[0]; - String osName = System.getProperty("os.name").toLowerCase(); - String osVersion = getOsVersion(); + return osVersion; + } - return String.format("cozepy/%s java/%s %s/%s", - VERSION, - javaVersion, - osName, - osVersion).toLowerCase(); - } + /** 获取用户代理字符串 */ + private static String getUserAgent() { + String javaVersion = System.getProperty("java.version").split("\\.")[0]; + String osName = System.getProperty("os.name").toLowerCase(); + String osVersion = getOsVersion(); + + return String.format("cozepy/%s java/%s %s/%s", VERSION, javaVersion, osName, osVersion) + .toLowerCase(); + } - /** - * 获取Coze客户端用户代理JSON - */ - private static String getCozeClientUserAgent() { - try{ - Map ua = new HashMap<>(); - ua.put("version", VERSION); - ua.put("lang", "java"); - ua.put("lang_version", System.getProperty("java.version").split("\\.")[0]); - ua.put("os_name", System.getProperty("os.name").toLowerCase()); - ua.put("os_version", getOsVersion()); - return objectMapper.writeValueAsString(ua); - }catch (Exception e){ - } - return ""; + /** 获取Coze客户端用户代理JSON */ + private static String getCozeClientUserAgent() { + try { + Map ua = new HashMap<>(); + ua.put("version", VERSION); + ua.put("lang", "java"); + ua.put("lang_version", System.getProperty("java.version").split("\\.")[0]); + ua.put("os_name", System.getProperty("os.name").toLowerCase()); + ua.put("os_version", getOsVersion()); + return objectMapper.writeValueAsString(ua); + } catch (Exception e) { } -} \ No newline at end of file + return ""; + } +} diff --git a/api/src/main/java/com/coze/openapi/service/utils/Utils.java b/api/src/main/java/com/coze/openapi/service/utils/Utils.java index cda0cd14..5d65704f 100644 --- a/api/src/main/java/com/coze/openapi/service/utils/Utils.java +++ b/api/src/main/java/com/coze/openapi/service/utils/Utils.java @@ -1,5 +1,7 @@ +/* (C)2024 */ package com.coze.openapi.service.utils; +import java.security.SecureRandom; import com.coze.openapi.client.common.BaseResp; import com.coze.openapi.client.common.BaseResponse; @@ -12,79 +14,76 @@ import retrofit2.HttpException; import retrofit2.Response; -import java.security.SecureRandom; - public class Utils { - public static final String LOG_HEADER = "x-tt-logid"; - private static final ObjectMapper mapper = defaultObjectMapper(); - - public static T execute(Call call) { - try{ - Response response = call.execute(); - if (!response.isSuccessful()) { - throw new HttpException(response); - } - T body = response.body(); - - // 处理不同类型的响应 - if (body instanceof BaseResponse) { - BaseResponse baseResponse = (BaseResponse) body; - baseResponse.setLogID(getLogID(response)); - - if (baseResponse.getData() instanceof BaseResp) { - BaseResp baseResp = (BaseResp) baseResponse.getData(); - baseResp.setLogID(getLogID(response)); - } - } else if (body instanceof BaseResp) { - BaseResp baseResp = (BaseResp) body; - baseResp.setLogID(getLogID(response)); - } - - return body; - }catch (Exception e){ - throw new RuntimeException(e); + public static final String LOG_HEADER = "x-tt-logid"; + private static final ObjectMapper mapper = defaultObjectMapper(); + + public static T execute(Call call) { + try { + Response response = call.execute(); + if (!response.isSuccessful()) { + throw new HttpException(response); + } + T body = response.body(); + + // 处理不同类型的响应 + if (body instanceof BaseResponse) { + BaseResponse baseResponse = (BaseResponse) body; + baseResponse.setLogID(getLogID(response)); + + if (baseResponse.getData() instanceof BaseResp) { + BaseResp baseResp = (BaseResp) baseResponse.getData(); + baseResp.setLogID(getLogID(response)); } - + } else if (body instanceof BaseResp) { + BaseResp baseResp = (BaseResp) body; + baseResp.setLogID(getLogID(response)); + } + + return body; + } catch (Exception e) { + throw new RuntimeException(e); } - - public static ObjectMapper defaultObjectMapper() { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - return mapper; + } + + public static ObjectMapper defaultObjectMapper() { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + return mapper; + } + + public static String getLogID(Response response) { + return response.raw().headers().get(LOG_HEADER); + } + + public static String toJson(Object obj) { + try { + return mapper.writeValueAsString(obj); + } catch (JsonProcessingException e) { + throw new RuntimeException("Failed to convert object to JSON string", e); } + } - public static String getLogID(Response response) { - return response.raw().headers().get(LOG_HEADER); + public static T fromJson(String json, Class clazz) { + try { + return mapper.readValue(json, clazz); + } catch (JsonProcessingException e) { + throw new RuntimeException("Failed to parse object from JSON string", e); } - - public static String toJson(Object obj) { - try{ - return mapper.writeValueAsString(obj); - } catch (JsonProcessingException e) { - throw new RuntimeException("Failed to convert object to JSON string", e); - } - } - - public static T fromJson(String json, Class clazz) { - try { - return mapper.readValue(json, clazz); - } catch (JsonProcessingException e) { - throw new RuntimeException("Failed to parse object from JSON string", e); - } - } - - public static String genRandomSign(int length) { - byte[] bytes = new byte[length / 2]; - new SecureRandom().nextBytes(bytes); - return bytesToHex(bytes); - } - - private static String bytesToHex(byte[] bytes) { - StringBuilder result = new StringBuilder(); - for (byte b : bytes) { - result.append(String.format("%02x", b)); - } - return result.toString(); + } + + public static String genRandomSign(int length) { + byte[] bytes = new byte[length / 2]; + new SecureRandom().nextBytes(bytes); + return bytesToHex(bytes); + } + + private static String bytesToHex(byte[] bytes) { + StringBuilder result = new StringBuilder(); + for (byte b : bytes) { + result.append(String.format("%02x", b)); } + return result.toString(); + } } diff --git a/api/src/test/java/com/coze/openapi/service/service/audio/RoomServiceTest.java b/api/src/test/java/com/coze/openapi/service/service/audio/RoomServiceTest.java index 7ac9cb90..048fee77 100644 --- a/api/src/test/java/com/coze/openapi/service/service/audio/RoomServiceTest.java +++ b/api/src/test/java/com/coze/openapi/service/service/audio/RoomServiceTest.java @@ -1,66 +1,64 @@ +/* (C)2024 */ package com.coze.openapi.service.service.audio; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + import com.coze.openapi.api.AudioRoomAPI; import com.coze.openapi.client.audio.rooms.CreateRoomReq; import com.coze.openapi.client.audio.rooms.CreateRoomResp; import com.coze.openapi.client.common.BaseResponse; import com.coze.openapi.utils.Utils; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; + import retrofit2.Call; import retrofit2.Response; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; - class RoomServiceTest { - @Mock - private AudioRoomAPI audioRoomAPI; + @Mock private AudioRoomAPI audioRoomAPI; - @Mock - private Call> createCall; + @Mock private Call> createCall; - private RoomService roomService; + private RoomService roomService; - @BeforeEach - void setUp() { - MockitoAnnotations.openMocks(this); - roomService = new RoomService(audioRoomAPI); - } + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + roomService = new RoomService(audioRoomAPI); + } - @Test - void testCreate() throws Exception { - // 准备测试数据 - CreateRoomReq req = CreateRoomReq.builder() - .botID("mock bot id") - .build(); + @Test + void testCreate() throws Exception { + // 准备测试数据 + CreateRoomReq req = CreateRoomReq.builder().botID("mock bot id").build(); - CreateRoomResp createResp = CreateRoomResp.builder() - .roomID("room_id") - .build(); + CreateRoomResp createResp = CreateRoomResp.builder().roomID("room_id").build(); - BaseResponse baseResponse = BaseResponse.builder() - .code(0) - .msg("success") - .logID(Utils.TEST_LOG_ID) - .data(createResp) - .build(); + BaseResponse baseResponse = + BaseResponse.builder() + .code(0) + .msg("success") + .logID(Utils.TEST_LOG_ID) + .data(createResp) + .build(); - // 设置 mock 行为 - when(audioRoomAPI.create(any(CreateRoomReq.class), any(CreateRoomReq.class))) - .thenReturn(createCall); - when(createCall.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); + // 设置 mock 行为 + when(audioRoomAPI.create(any(CreateRoomReq.class), any(CreateRoomReq.class))) + .thenReturn(createCall); + when(createCall.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); - // 执行测试 - CreateRoomResp result = roomService.create(req); + // 执行测试 + CreateRoomResp result = roomService.create(req); - // 验证结果 - assertNotNull(result); - assertEquals("room_id", result.getRoomID()); - assertEquals(Utils.TEST_LOG_ID, result.getLogID()); - } -} \ No newline at end of file + // 验证结果 + assertNotNull(result); + assertEquals("room_id", result.getRoomID()); + assertEquals(Utils.TEST_LOG_ID, result.getLogID()); + } +} diff --git a/api/src/test/java/com/coze/openapi/service/service/audio/SpeechServiceTest.java b/api/src/test/java/com/coze/openapi/service/service/audio/SpeechServiceTest.java index 4cec2266..b6b43de8 100644 --- a/api/src/test/java/com/coze/openapi/service/service/audio/SpeechServiceTest.java +++ b/api/src/test/java/com/coze/openapi/service/service/audio/SpeechServiceTest.java @@ -1,78 +1,72 @@ +/* (C)2024 */ package com.coze.openapi.service.service.audio; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + import com.coze.openapi.api.AudioSpeechAPI; import com.coze.openapi.client.audio.speech.CreateSpeechReq; import com.coze.openapi.client.audio.speech.CreateSpeechResp; -import com.coze.openapi.utils.Utils; + import okhttp3.MediaType; import okhttp3.ResponseBody; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; import retrofit2.Call; import retrofit2.Response; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; - class SpeechServiceTest { - @Mock - private AudioSpeechAPI audioSpeechAPI; - - @Mock - private Call createCall; - - private SpeechService speechService; - - @BeforeEach - void setUp() { - MockitoAnnotations.openMocks(this); - speechService = new SpeechService(audioSpeechAPI); - } - - @Test - void testCreate() throws Exception { - // 准备测试数据 - CreateSpeechReq req = CreateSpeechReq.builder() - .input("Test speech") - .voiceID("mock voice id") - .build(); - - ResponseBody responseBody = ResponseBody.create( - new byte[]{1, 2, 3, 4}, - MediaType.parse("audio/mpeg") - ); - - // 设置 mock 行为 - when(audioSpeechAPI.create(any(CreateSpeechReq.class), any(CreateSpeechReq.class))) - .thenReturn(createCall); - when(createCall.execute()).thenReturn(Response.success(responseBody)); - - // 执行测试 - CreateSpeechResp result = speechService.create(req); - - // 验证结果 - assertNotNull(result); - assertNotNull(result.getResponse()); - } - - @Test - void testCreateWithError() throws Exception{ - // 准备测试数据 - CreateSpeechReq req = CreateSpeechReq.builder() - .input("Test speech") - .voiceID("mock voice id") - .build(); - - // 设置 mock 行为 - when(audioSpeechAPI.create(any(CreateSpeechReq.class), any(CreateSpeechReq.class))) - .thenReturn(createCall); - when(createCall.execute()).thenThrow(new RuntimeException("Network error")); - - // 验证异常抛出 - assertThrows(RuntimeException.class, () -> speechService.create(req)); - } -} \ No newline at end of file + @Mock private AudioSpeechAPI audioSpeechAPI; + + @Mock private Call createCall; + + private SpeechService speechService; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + speechService = new SpeechService(audioSpeechAPI); + } + + @Test + void testCreate() throws Exception { + // 准备测试数据 + CreateSpeechReq req = + CreateSpeechReq.builder().input("Test speech").voiceID("mock voice id").build(); + + ResponseBody responseBody = + ResponseBody.create(new byte[] {1, 2, 3, 4}, MediaType.parse("audio/mpeg")); + + // 设置 mock 行为 + when(audioSpeechAPI.create(any(CreateSpeechReq.class), any(CreateSpeechReq.class))) + .thenReturn(createCall); + when(createCall.execute()).thenReturn(Response.success(responseBody)); + + // 执行测试 + CreateSpeechResp result = speechService.create(req); + + // 验证结果 + assertNotNull(result); + assertNotNull(result.getResponse()); + } + + @Test + void testCreateWithError() throws Exception { + // 准备测试数据 + CreateSpeechReq req = + CreateSpeechReq.builder().input("Test speech").voiceID("mock voice id").build(); + + // 设置 mock 行为 + when(audioSpeechAPI.create(any(CreateSpeechReq.class), any(CreateSpeechReq.class))) + .thenReturn(createCall); + when(createCall.execute()).thenThrow(new RuntimeException("Network error")); + + // 验证异常抛出 + assertThrows(RuntimeException.class, () -> speechService.create(req)); + } +} diff --git a/api/src/test/java/com/coze/openapi/service/service/audio/VoiceServiceTest.java b/api/src/test/java/com/coze/openapi/service/service/audio/VoiceServiceTest.java index 9b57eba3..71c34b2f 100644 --- a/api/src/test/java/com/coze/openapi/service/service/audio/VoiceServiceTest.java +++ b/api/src/test/java/com/coze/openapi/service/service/audio/VoiceServiceTest.java @@ -1,5 +1,21 @@ +/* (C)2024 */ package com.coze.openapi.service.service.audio; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +import java.io.File; +import java.io.IOException; +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + import com.coze.openapi.api.AudioVoiceAPI; import com.coze.openapi.client.audio.common.AudioFormat; import com.coze.openapi.client.audio.voices.*; @@ -7,133 +23,111 @@ import com.coze.openapi.client.common.BaseResponse; import com.coze.openapi.client.common.pagination.PageResp; import com.coze.openapi.utils.Utils; -import okhttp3.MultipartBody; -import okhttp3.RequestBody; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; + import retrofit2.Call; import retrofit2.Response; -import java.io.File; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.*; - class VoiceServiceTest { - @Mock - private AudioVoiceAPI audioVoiceAPI; - - @Mock - private Call> cloneCall; - - @Mock - private Call> listCall; - - private VoiceService voiceService; - - private static String mockFilePath; - private static File testFile; - - - @BeforeEach - void setUp() throws IOException { - MockitoAnnotations.openMocks(this); - voiceService = new VoiceService(audioVoiceAPI); - File mockFile = mock(File.class); - when(mockFile.exists()).thenReturn(true); - when(mockFile.isFile()).thenReturn(true); - - // 创建临时测试文件 - testFile = File.createTempFile("test", ".mp3"); - mockFilePath = testFile.getAbsolutePath(); - } - - @Test - void testClone() throws Exception { - // 准备测试数据 - CloneVoiceReq req = CloneVoiceReq.builder() - .voiceName("test_voice") - .audioFormat(AudioFormat.MP3) - .filePath(mockFilePath) - .build(); - - CloneVoiceResp cloneResp = CloneVoiceResp.builder() - .voiceID("voice_id") - .build(); - - BaseResponse baseResponse = BaseResponse.builder() - .code(0) - .msg("success") - .logID(Utils.TEST_LOG_ID) - .data(cloneResp) - .build(); - - // 设置 mock 行为 - when(audioVoiceAPI.clone(any(), any(), any(), any(), any(), any(), any(), any())).thenReturn(cloneCall); - when(cloneCall.execute()).thenReturn(Response.success(baseResponse)); - - // 执行测试 - CloneVoiceResp result = voiceService.clone(req); - - // 验证结果 - assertNotNull(result); - assertEquals("voice_id", result.getVoiceID()); - } - - @Test - void testList() throws Exception { - // 准备测试数��� - ListVoiceReq req = ListVoiceReq.builder() - .pageNum(1) - .pageSize(10) - .filterSystemVoice(false) - .build(); - - List voices = Arrays.asList( - Voice.builder().voiceID("voice1").name("Voice 1").build(), - Voice.builder().voiceID("voice2").name("Voice 2").build() - ); - - ListVoiceResp listResp = ListVoiceResp.builder() - .voiceList(voices) - .logID(Utils.TEST_LOG_ID) - .build(); - - BaseResponse baseResponse = BaseResponse.builder() - .code(0) - .msg("success") - .logID(Utils.TEST_LOG_ID) - .data(listResp) - .build(); - - // 设置 mock 行为 - when(audioVoiceAPI.list(eq(false), eq(1), eq(10), any(ListVoiceReq.class))) - .thenReturn(listCall); - when(listCall.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); - - // 执行测试 - PageResp result = voiceService.list(req); - - // 验证结果 - assertNotNull(result); - assertEquals(2, result.getItems().size()); - assertEquals("voice1", result.getItems().get(0).getVoiceID()); - assertEquals(Utils.TEST_LOG_ID, result.getLogID()); - } - - @AfterEach - void tearDown() { - // 清理临时文件 - if (testFile != null && testFile.exists()) { - testFile.delete(); - } + @Mock private AudioVoiceAPI audioVoiceAPI; + + @Mock private Call> cloneCall; + + @Mock private Call> listCall; + + private VoiceService voiceService; + + private static String mockFilePath; + private static File testFile; + + @BeforeEach + void setUp() throws IOException { + MockitoAnnotations.openMocks(this); + voiceService = new VoiceService(audioVoiceAPI); + File mockFile = mock(File.class); + when(mockFile.exists()).thenReturn(true); + when(mockFile.isFile()).thenReturn(true); + + // 创建临时测试文件 + testFile = File.createTempFile("test", ".mp3"); + mockFilePath = testFile.getAbsolutePath(); + } + + @Test + void testClone() throws Exception { + // 准备测试数据 + CloneVoiceReq req = + CloneVoiceReq.builder() + .voiceName("test_voice") + .audioFormat(AudioFormat.MP3) + .filePath(mockFilePath) + .build(); + + CloneVoiceResp cloneResp = CloneVoiceResp.builder().voiceID("voice_id").build(); + + BaseResponse baseResponse = + BaseResponse.builder() + .code(0) + .msg("success") + .logID(Utils.TEST_LOG_ID) + .data(cloneResp) + .build(); + + // 设置 mock 行为 + when(audioVoiceAPI.clone(any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(cloneCall); + when(cloneCall.execute()).thenReturn(Response.success(baseResponse)); + + // 执行测试 + CloneVoiceResp result = voiceService.clone(req); + + // 验证结果 + assertNotNull(result); + assertEquals("voice_id", result.getVoiceID()); + } + + @Test + void testList() throws Exception { + // 准备测试数��� + ListVoiceReq req = + ListVoiceReq.builder().pageNum(1).pageSize(10).filterSystemVoice(false).build(); + + List voices = + Arrays.asList( + Voice.builder().voiceID("voice1").name("Voice 1").build(), + Voice.builder().voiceID("voice2").name("Voice 2").build()); + + ListVoiceResp listResp = + ListVoiceResp.builder().voiceList(voices).logID(Utils.TEST_LOG_ID).build(); + + BaseResponse baseResponse = + BaseResponse.builder() + .code(0) + .msg("success") + .logID(Utils.TEST_LOG_ID) + .data(listResp) + .build(); + + // 设置 mock 行为 + when(audioVoiceAPI.list(eq(false), eq(1), eq(10), any(ListVoiceReq.class))) + .thenReturn(listCall); + when(listCall.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); + + // 执行测试 + PageResp result = voiceService.list(req); + + // 验证结果 + assertNotNull(result); + assertEquals(2, result.getItems().size()); + assertEquals("voice1", result.getItems().get(0).getVoiceID()); + assertEquals(Utils.TEST_LOG_ID, result.getLogID()); + } + + @AfterEach + void tearDown() { + // 清理临时文件 + if (testFile != null && testFile.exists()) { + testFile.delete(); } -} \ No newline at end of file + } +} diff --git a/api/src/test/java/com/coze/openapi/service/service/bots/BotServiceTest.java b/api/src/test/java/com/coze/openapi/service/service/bots/BotServiceTest.java index f59179c7..ff8bec1d 100644 --- a/api/src/test/java/com/coze/openapi/service/service/bots/BotServiceTest.java +++ b/api/src/test/java/com/coze/openapi/service/service/bots/BotServiceTest.java @@ -1,5 +1,18 @@ +/* (C)2024 */ package com.coze.openapi.service.service.bots; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + import com.coze.openapi.api.BotAPI; import com.coze.openapi.client.bots.*; import com.coze.openapi.client.bots.model.Bot; @@ -7,213 +20,171 @@ import com.coze.openapi.client.common.BaseResponse; import com.coze.openapi.client.common.pagination.PageResp; import com.coze.openapi.utils.Utils; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; + import retrofit2.Call; import retrofit2.Response; -import java.util.Arrays; -import java.util.List; +class BotServiceTest { -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.when; + @Mock private BotAPI botAPI; -class BotServiceTest { + @Mock private Call> listCall; + + @Mock private Call> retrieveCall; + + @Mock private Call> createCall; + + @Mock private Call> updateCall; + + @Mock private Call> publishCall; + + private BotService botService; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + botService = new BotService(botAPI); + } + + @Test + public void testList() throws Exception { + // 准备测试数据 + String spaceId = "test_space_id"; + ListBotReq req = ListBotReq.builder().spaceID(spaceId).pageNum(1).pageSize(20).build(); + + // 模拟返回数据 + List bots = + Arrays.asList( + SimpleBot.builder().botID("bot1").botName("Bot 1").build(), + SimpleBot.builder().botID("bot2").botName("Bot 2").build()); + + ListBotResp listBotResp = ListBotResp.builder().total(2).bots(bots).build(); + + BaseResponse baseResponse = + BaseResponse.builder() + .code(0) + .msg("success") + .logID(Utils.TEST_LOG_ID) + .data(listBotResp) + .build(); - @Mock - private BotAPI botAPI; - - @Mock - private Call> listCall; - - @Mock - private Call> retrieveCall; - - @Mock - private Call> createCall; - - @Mock - private Call> updateCall; - - @Mock - private Call> publishCall; - - private BotService botService; - - @BeforeEach - void setUp() { - MockitoAnnotations.openMocks(this); - botService = new BotService(botAPI); - } - - @Test - public void testList() throws Exception { - // 准备测试数据 - String spaceId = "test_space_id"; - ListBotReq req = ListBotReq.builder() - .spaceID(spaceId) - .pageNum(1) - .pageSize(20) - .build(); - - // 模拟返回数据 - List bots = Arrays.asList( - SimpleBot.builder().botID("bot1").botName("Bot 1").build(), - SimpleBot.builder().botID("bot2").botName("Bot 2").build() - ); - - ListBotResp listBotResp = ListBotResp.builder() - .total(2) - .bots(bots) - .build(); - - BaseResponse baseResponse = BaseResponse.builder() - .code(0) - .msg("success") - .logID(Utils.TEST_LOG_ID) - .data(listBotResp) - .build(); - - // 设置 mock 行为 - when(botAPI.list(eq(spaceId), eq(1), eq(20), any(ListBotReq.class))) - .thenReturn(listCall); - when(listCall.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); - - // 执行测试 - PageResp result = botService.list(req); - - // 验证结果 - assertNotNull(result); - assertEquals(2, result.getTotal()); - assertEquals(2, result.getItems().size()); - assertEquals(Utils.TEST_LOG_ID, result.getLogID()); - assertEquals("bot1", result.getItems().get(0).getBotID()); - } - - @Test - void testRetrieve() throws Exception { - // 准备测试数据 - String botId = "test_bot_id"; - RetrieveBotReq req = RetrieveBotReq.builder() - .botID(botId) - .build(); - - Bot bot = Bot.builder() - .botID(botId) - .name("Test Bot") - .build(); - - BaseResponse baseResponse = BaseResponse.builder() - .code(0) - .msg("success") - .logID(Utils.TEST_LOG_ID) - .data(bot) - .build(); - - // 设置 mock 行为 - when(botAPI.retrieve(eq(botId), any(RetrieveBotReq.class))) - .thenReturn(retrieveCall); - when(retrieveCall.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); - - // 执行测试 - RetrieveBotResp result = botService.retrieve(req); - - // 验证结果 - assertNotNull(result); - assertEquals(Utils.TEST_LOG_ID, result.getLogID()); - assertEquals(botId, result.getBot().getBotID()); - } - - @Test - void testCreate() throws Exception { - // 准备测试数据 - CreateBotReq req = CreateBotReq.builder() - .name("New Bot") - .spaceID("mock_space_id") - .build(); - - CreateBotResp createResp = CreateBotResp.builder() - .botID("new_bot_id") - .build(); - - BaseResponse baseResponse = BaseResponse.builder() - .code(0) - .msg("success") - .logID(Utils.TEST_LOG_ID) - .data(createResp) - .build(); - - // 设置 mock 行为 - when(botAPI.create(any(CreateBotReq.class), any(CreateBotReq.class))) - .thenReturn(createCall); - when(createCall.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); - - // 执行测试 - CreateBotResp result = botService.create(req); - - // 验证结果 - assertNotNull(result); - assertEquals("new_bot_id", result.getBotID()); - } - - @Test - void testUpdate() throws Exception { - // 准备测试数据 - UpdateBotReq req = UpdateBotReq.builder() - .botID("bot_id") - .name("Updated Bot") - .build(); - - BaseResponse baseResponse = BaseResponse.builder() - .code(0) - .msg("success") - .logID(Utils.TEST_LOG_ID) - .build(); - - // 设置 mock 行为 - when(botAPI.update(any(UpdateBotReq.class), any(UpdateBotReq.class))) - .thenReturn(updateCall); - when(updateCall.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); - - // 执行测试 - UpdateBotResp result = botService.update(req); - - // 验证结果 - assertNotNull(result); - assertEquals(Utils.TEST_LOG_ID, result.getLogID()); - } - - @Test - void testPublish() throws Exception { - // 准备测试数据 - PublishBotReq req = PublishBotReq.builder() - .botID("bot_id") - .build(); - - PublishBotResp publishResp = PublishBotResp.builder() - .botID("bot_id") - .build(); - - BaseResponse baseResponse = BaseResponse.builder() - .code(0) - .msg("success") - .logID(Utils.TEST_LOG_ID) - .data(publishResp) - .build(); - - // 设置 mock 行为 - when(botAPI.publish(any(PublishBotReq.class), any(PublishBotReq.class))) - .thenReturn(publishCall); - when(publishCall.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); - - // 执行测试 - PublishBotResp result = botService.publish(req); - - // 验证结果 - assertNotNull(result); - assertEquals("bot_id", result.getBotID()); - } -} \ No newline at end of file + // 设置 mock 行为 + when(botAPI.list(eq(spaceId), eq(1), eq(20), any(ListBotReq.class))).thenReturn(listCall); + when(listCall.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); + + // 执行测试 + PageResp result = botService.list(req); + + // 验证结果 + assertNotNull(result); + assertEquals(2, result.getTotal()); + assertEquals(2, result.getItems().size()); + assertEquals(Utils.TEST_LOG_ID, result.getLogID()); + assertEquals("bot1", result.getItems().get(0).getBotID()); + } + + @Test + void testRetrieve() throws Exception { + // 准备测试数据 + String botId = "test_bot_id"; + RetrieveBotReq req = RetrieveBotReq.builder().botID(botId).build(); + + Bot bot = Bot.builder().botID(botId).name("Test Bot").build(); + + BaseResponse baseResponse = + BaseResponse.builder() + .code(0) + .msg("success") + .logID(Utils.TEST_LOG_ID) + .data(bot) + .build(); + + // 设置 mock 行为 + when(botAPI.retrieve(eq(botId), any(RetrieveBotReq.class))).thenReturn(retrieveCall); + when(retrieveCall.execute()) + .thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); + + // 执行测试 + RetrieveBotResp result = botService.retrieve(req); + + // 验证结果 + assertNotNull(result); + assertEquals(Utils.TEST_LOG_ID, result.getLogID()); + assertEquals(botId, result.getBot().getBotID()); + } + + @Test + void testCreate() throws Exception { + // 准备测试数据 + CreateBotReq req = CreateBotReq.builder().name("New Bot").spaceID("mock_space_id").build(); + + CreateBotResp createResp = CreateBotResp.builder().botID("new_bot_id").build(); + + BaseResponse baseResponse = + BaseResponse.builder() + .code(0) + .msg("success") + .logID(Utils.TEST_LOG_ID) + .data(createResp) + .build(); + + // 设置 mock 行为 + when(botAPI.create(any(CreateBotReq.class), any(CreateBotReq.class))).thenReturn(createCall); + when(createCall.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); + + // 执行测试 + CreateBotResp result = botService.create(req); + + // 验证结果 + assertNotNull(result); + assertEquals("new_bot_id", result.getBotID()); + } + + @Test + void testUpdate() throws Exception { + // 准备测试数据 + UpdateBotReq req = UpdateBotReq.builder().botID("bot_id").name("Updated Bot").build(); + + BaseResponse baseResponse = + BaseResponse.builder().code(0).msg("success").logID(Utils.TEST_LOG_ID).build(); + + // 设置 mock 行为 + when(botAPI.update(any(UpdateBotReq.class), any(UpdateBotReq.class))).thenReturn(updateCall); + when(updateCall.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); + + // 执行测试 + UpdateBotResp result = botService.update(req); + + // 验证结果 + assertNotNull(result); + assertEquals(Utils.TEST_LOG_ID, result.getLogID()); + } + + @Test + void testPublish() throws Exception { + // 准备测试数据 + PublishBotReq req = PublishBotReq.builder().botID("bot_id").build(); + + PublishBotResp publishResp = PublishBotResp.builder().botID("bot_id").build(); + + BaseResponse baseResponse = + BaseResponse.builder() + .code(0) + .msg("success") + .logID(Utils.TEST_LOG_ID) + .data(publishResp) + .build(); + + // 设置 mock 行为 + when(botAPI.publish(any(PublishBotReq.class), any(PublishBotReq.class))) + .thenReturn(publishCall); + when(publishCall.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); + + // 执行测试 + PublishBotResp result = botService.publish(req); + + // 验证结果 + assertNotNull(result); + assertEquals("bot_id", result.getBotID()); + } +} diff --git a/api/src/test/java/com/coze/openapi/service/service/chat/ChatMessageServiceTest.java b/api/src/test/java/com/coze/openapi/service/service/chat/ChatMessageServiceTest.java index 6ba569dc..959075d6 100644 --- a/api/src/test/java/com/coze/openapi/service/service/chat/ChatMessageServiceTest.java +++ b/api/src/test/java/com/coze/openapi/service/service/chat/ChatMessageServiceTest.java @@ -1,76 +1,76 @@ +/* (C)2024 */ package com.coze.openapi.service.service.chat; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + import com.coze.openapi.api.ChatMessageAPI; import com.coze.openapi.client.chat.message.ListMessageReq; import com.coze.openapi.client.chat.message.ListMessageResp; import com.coze.openapi.client.common.BaseResponse; import com.coze.openapi.client.connversations.message.model.Message; import com.coze.openapi.utils.Utils; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; + import retrofit2.Call; import retrofit2.Response; -import java.util.Arrays; -import java.util.List; +class ChatMessageServiceTest { -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.when; + @Mock private ChatMessageAPI chatMessageAPI; -class ChatMessageServiceTest { + @Mock private Call>> listCall; + + private ChatMessageService chatMessageService; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + chatMessageService = new ChatMessageService(chatMessageAPI); + } + + @Test + void testList() throws Exception { + // 准备测试数据 + String conversationID = "test_conversation_id"; + String chatID = "test_chat_id"; + ListMessageReq req = + ListMessageReq.builder().conversationID(conversationID).chatID(chatID).build(); + + List messages = + Arrays.asList( + Message.builder().id("msg1").content("Hello").build(), + Message.builder().id("msg2").content("World").build()); + + BaseResponse> baseResponse = + BaseResponse.>builder() + .code(0) + .msg("success") + .logID(Utils.TEST_LOG_ID) + .data(messages) + .build(); + + // 设置 mock 行为 + when(chatMessageAPI.list(eq(conversationID), eq(chatID), any(ListMessageReq.class))) + .thenReturn(listCall); + when(listCall.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); + + // 执行测试 + ListMessageResp result = chatMessageService.list(req); - @Mock - private ChatMessageAPI chatMessageAPI; - - @Mock - private Call>> listCall; - - private ChatMessageService chatMessageService; - - @BeforeEach - void setUp() { - MockitoAnnotations.openMocks(this); - chatMessageService = new ChatMessageService(chatMessageAPI); - } - - @Test - void testList() throws Exception { - // 准备测试数据 - String conversationID = "test_conversation_id"; - String chatID = "test_chat_id"; - ListMessageReq req = ListMessageReq.builder() - .conversationID(conversationID) - .chatID(chatID) - .build(); - - List messages = Arrays.asList( - Message.builder().id("msg1").content("Hello").build(), - Message.builder().id("msg2").content("World").build() - ); - - BaseResponse> baseResponse = BaseResponse.>builder() - .code(0) - .msg("success") - .logID(Utils.TEST_LOG_ID) - .data(messages) - .build(); - - // 设置 mock 行为 - when(chatMessageAPI.list(eq(conversationID), eq(chatID), any(ListMessageReq.class))) - .thenReturn(listCall); - when(listCall.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); - - // 执行测试 - ListMessageResp result = chatMessageService.list(req); - - // 验证结果 - assertNotNull(result); - assertEquals(Utils.TEST_LOG_ID, result.getLogID()); - assertEquals(2, result.getMessages().size()); - assertEquals("msg1", result.getMessages().get(0).getId()); - assertEquals("Hello", result.getMessages().get(0).getContent()); - } -} \ No newline at end of file + // 验证结果 + assertNotNull(result); + assertEquals(Utils.TEST_LOG_ID, result.getLogID()); + assertEquals(2, result.getMessages().size()); + assertEquals("msg1", result.getMessages().get(0).getId()); + assertEquals("Hello", result.getMessages().get(0).getContent()); + } +} diff --git a/api/src/test/java/com/coze/openapi/service/service/chat/ChatServiceTest.java b/api/src/test/java/com/coze/openapi/service/service/chat/ChatServiceTest.java index 72b0971b..b96dd4bb 100644 --- a/api/src/test/java/com/coze/openapi/service/service/chat/ChatServiceTest.java +++ b/api/src/test/java/com/coze/openapi/service/service/chat/ChatServiceTest.java @@ -1,5 +1,17 @@ +/* (C)2024 */ package com.coze.openapi.service.service.chat; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.when; + +import java.util.Collections; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + import com.coze.openapi.api.ChatAPI; import com.coze.openapi.api.ChatMessageAPI; import com.coze.openapi.client.chat.*; @@ -8,189 +20,180 @@ import com.coze.openapi.client.chat.model.ToolOutput; import com.coze.openapi.client.common.BaseResponse; import com.coze.openapi.utils.Utils; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; + import retrofit2.Call; import retrofit2.Response; -import java.util.Arrays; -import java.util.Collections; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.when; - class ChatServiceTest { - @Mock - private ChatAPI chatAPI; - - @Mock - private ChatMessageAPI chatMessageAPI; - - @Mock - private Call> chatCall; - - private ChatService chatService; - - @BeforeEach - void setUp() { - MockitoAnnotations.openMocks(this); - chatService = new ChatService(chatAPI, chatMessageAPI); - } - - @Test - void testCreate() throws Exception { - // 准备测试数据 - String conversationID = "test_conversation_id"; - String botID = "test_bot_id"; - String userID = "test_user_id"; - CreateChatReq req = CreateChatReq.builder() - .conversationID(conversationID) - .botID(botID) - .userID(userID) - .build(); - - Chat chat = Chat.builder() - .id("chat_id") - .conversationID(conversationID) - .status(ChatStatus.COMPLETED) - .build(); - - BaseResponse baseResponse = BaseResponse.builder() - .code(0) - .msg("success") - .logID(Utils.TEST_LOG_ID) - .data(chat) - .build(); - - // 设置 mock 行为 - when(chatAPI.chat(eq(conversationID), any(CreateChatReq.class), any(CreateChatReq.class))) - .thenReturn(chatCall); - when(chatCall.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); - - // 执行测试 - CreateChatResp result = chatService.create(req); - - // 验证结果 - assertNotNull(result); - assertEquals(Utils.TEST_LOG_ID, result.getLogID()); - assertEquals("chat_id", result.getChat().getID()); - assertEquals(ChatStatus.COMPLETED, result.getChat().getStatus()); - } - - @Test - void testRetrieve() throws Exception { - // 准备测试数据 - String conversationID = "test_conversation_id"; - String chatID = "test_chat_id"; - RetrieveChatReq req = RetrieveChatReq.builder() - .conversationID(conversationID) - .chatID(chatID) - .build(); - - Chat chat = Chat.builder() - .id(chatID) - .conversationID(conversationID) - .status(ChatStatus.COMPLETED) - .build(); - - BaseResponse baseResponse = BaseResponse.builder() - .code(0) - .msg("success") - .logID(Utils.TEST_LOG_ID) - .data(chat) - .build(); - - // 设置 mock 行为 - when(chatAPI.retrieve(eq(conversationID), eq(chatID), any(RetrieveChatReq.class))) - .thenReturn(chatCall); - when(chatCall.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); - - // 执行测试 - RetrieveChatResp result = chatService.retrieve(req); - - // 验证结果 - assertNotNull(result); - assertEquals(Utils.TEST_LOG_ID, result.getLogID()); - assertEquals(chatID, result.getChat().getID()); - } - - @Test - void testCancel() throws Exception { - // 准备测试数据 - String conversationID = "test_conversation_id"; - String chatID = "test_chat_id"; - CancelChatReq req = CancelChatReq.builder() - .conversationID(conversationID) - .chatID(chatID) - .build(); - - Chat chat = Chat.builder() - .id(chatID) - .conversationID(conversationID) - .status(ChatStatus.CANCELLED) - .build(); - - BaseResponse baseResponse = BaseResponse.builder() - .code(0) - .msg("success") - .logID(Utils.TEST_LOG_ID) - .data(chat) - .build(); - - // 设置 mock 行为 - when(chatAPI.cancel(any(CancelChatReq.class), any(CancelChatReq.class))) - .thenReturn(chatCall); - when(chatCall.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); - - // 执行测试 - CancelChatResp result = chatService.cancel(req); - - // 验证结果 - assertNotNull(result); - assertEquals(Utils.TEST_LOG_ID, result.getLogID()); - assertEquals(ChatStatus.CANCELLED, result.getChat().getStatus()); - } - - @Test - void testSubmitToolOutputs() throws Exception { - // 准备测试数据 - String conversationID = "test_conversation_id"; - String chatID = "test_chat_id"; - SubmitToolOutputsReq req = SubmitToolOutputsReq.builder() - .conversationID(conversationID) - .chatID(chatID) - .toolOutputs(Collections.singletonList(new ToolOutput("mock_id", "mock_output"))) - .build(); - - Chat chat = Chat.builder() - .id(chatID) - .conversationID(conversationID) - .status(ChatStatus.COMPLETED) - .build(); - - BaseResponse baseResponse = BaseResponse.builder() - .code(0) - .msg("success") - .logID(Utils.TEST_LOG_ID) - .data(chat) - .build(); - - // 设置 mock 行为 - when(chatAPI.submitToolOutputs(eq(conversationID), eq(chatID), - any(SubmitToolOutputsReq.class), any(SubmitToolOutputsReq.class))) - .thenReturn(chatCall); - when(chatCall.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); - - // 执行测试 - SubmitToolOutputsResp result = chatService.submitToolOutputs(req); - - // 验证结果 - assertNotNull(result); - assertEquals(Utils.TEST_LOG_ID, result.getLogID()); - assertEquals(chatID, result.getChat().getID()); - } -} \ No newline at end of file + @Mock private ChatAPI chatAPI; + + @Mock private ChatMessageAPI chatMessageAPI; + + @Mock private Call> chatCall; + + private ChatService chatService; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + chatService = new ChatService(chatAPI, chatMessageAPI); + } + + @Test + void testCreate() throws Exception { + // 准备测试数据 + String conversationID = "test_conversation_id"; + String botID = "test_bot_id"; + String userID = "test_user_id"; + CreateChatReq req = + CreateChatReq.builder().conversationID(conversationID).botID(botID).userID(userID).build(); + + Chat chat = + Chat.builder() + .id("chat_id") + .conversationID(conversationID) + .status(ChatStatus.COMPLETED) + .build(); + + BaseResponse baseResponse = + BaseResponse.builder() + .code(0) + .msg("success") + .logID(Utils.TEST_LOG_ID) + .data(chat) + .build(); + + // 设置 mock 行为 + when(chatAPI.chat(eq(conversationID), any(CreateChatReq.class), any(CreateChatReq.class))) + .thenReturn(chatCall); + when(chatCall.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); + + // 执行测试 + CreateChatResp result = chatService.create(req); + + // 验证结果 + assertNotNull(result); + assertEquals(Utils.TEST_LOG_ID, result.getLogID()); + assertEquals("chat_id", result.getChat().getID()); + assertEquals(ChatStatus.COMPLETED, result.getChat().getStatus()); + } + + @Test + void testRetrieve() throws Exception { + // 准备测试数据 + String conversationID = "test_conversation_id"; + String chatID = "test_chat_id"; + RetrieveChatReq req = + RetrieveChatReq.builder().conversationID(conversationID).chatID(chatID).build(); + + Chat chat = + Chat.builder() + .id(chatID) + .conversationID(conversationID) + .status(ChatStatus.COMPLETED) + .build(); + + BaseResponse baseResponse = + BaseResponse.builder() + .code(0) + .msg("success") + .logID(Utils.TEST_LOG_ID) + .data(chat) + .build(); + + // 设置 mock 行为 + when(chatAPI.retrieve(eq(conversationID), eq(chatID), any(RetrieveChatReq.class))) + .thenReturn(chatCall); + when(chatCall.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); + + // 执行测试 + RetrieveChatResp result = chatService.retrieve(req); + + // 验证结果 + assertNotNull(result); + assertEquals(Utils.TEST_LOG_ID, result.getLogID()); + assertEquals(chatID, result.getChat().getID()); + } + + @Test + void testCancel() throws Exception { + // 准备测试数据 + String conversationID = "test_conversation_id"; + String chatID = "test_chat_id"; + CancelChatReq req = + CancelChatReq.builder().conversationID(conversationID).chatID(chatID).build(); + + Chat chat = + Chat.builder() + .id(chatID) + .conversationID(conversationID) + .status(ChatStatus.CANCELLED) + .build(); + + BaseResponse baseResponse = + BaseResponse.builder() + .code(0) + .msg("success") + .logID(Utils.TEST_LOG_ID) + .data(chat) + .build(); + + // 设置 mock 行为 + when(chatAPI.cancel(any(CancelChatReq.class), any(CancelChatReq.class))).thenReturn(chatCall); + when(chatCall.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); + + // 执行测试 + CancelChatResp result = chatService.cancel(req); + + // 验证结果 + assertNotNull(result); + assertEquals(Utils.TEST_LOG_ID, result.getLogID()); + assertEquals(ChatStatus.CANCELLED, result.getChat().getStatus()); + } + + @Test + void testSubmitToolOutputs() throws Exception { + // 准备测试数据 + String conversationID = "test_conversation_id"; + String chatID = "test_chat_id"; + SubmitToolOutputsReq req = + SubmitToolOutputsReq.builder() + .conversationID(conversationID) + .chatID(chatID) + .toolOutputs(Collections.singletonList(new ToolOutput("mock_id", "mock_output"))) + .build(); + + Chat chat = + Chat.builder() + .id(chatID) + .conversationID(conversationID) + .status(ChatStatus.COMPLETED) + .build(); + + BaseResponse baseResponse = + BaseResponse.builder() + .code(0) + .msg("success") + .logID(Utils.TEST_LOG_ID) + .data(chat) + .build(); + + // 设置 mock 行为 + when(chatAPI.submitToolOutputs( + eq(conversationID), + eq(chatID), + any(SubmitToolOutputsReq.class), + any(SubmitToolOutputsReq.class))) + .thenReturn(chatCall); + when(chatCall.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); + + // 执行测试 + SubmitToolOutputsResp result = chatService.submitToolOutputs(req); + + // 验证结果 + assertNotNull(result); + assertEquals(Utils.TEST_LOG_ID, result.getLogID()); + assertEquals(chatID, result.getChat().getID()); + } +} diff --git a/api/src/test/java/com/coze/openapi/service/service/common/AbstractEventCallbackTest.java b/api/src/test/java/com/coze/openapi/service/service/common/AbstractEventCallbackTest.java index 9e53c2d5..ef895394 100644 --- a/api/src/test/java/com/coze/openapi/service/service/common/AbstractEventCallbackTest.java +++ b/api/src/test/java/com/coze/openapi/service/service/common/AbstractEventCallbackTest.java @@ -1,172 +1,153 @@ +/* (C)2024 */ package com.coze.openapi.service.service.common; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +import java.io.BufferedReader; +import java.io.IOException; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import com.coze.openapi.client.common.BaseResponse; import com.coze.openapi.client.exception.CozeApiExcetion; import com.coze.openapi.client.exception.CozeError; -import com.coze.openapi.client.common.BaseResponse; import com.coze.openapi.utils.Utils; + import io.reactivex.FlowableEmitter; import okhttp3.Headers; import okhttp3.MediaType; import okhttp3.ResponseBody; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; import retrofit2.Call; import retrofit2.Response; -import java.io.BufferedReader; -import java.io.IOException; - -import static org.mockito.Mockito.*; -import static org.junit.jupiter.api.Assertions.*; - class AbstractEventCallbackTest { - @Mock - private FlowableEmitter emitter; - - @Mock - private Call call; - - private TestEventCallback callback; - - private static class TestEventCallback extends AbstractEventCallback { - public TestEventCallback(FlowableEmitter emitter) { - super(emitter); - } - - @Override - protected boolean processLine(String line, BufferedReader reader, String logID) { - emitter.onNext(line); - return line.contains("done"); - } - } - - @BeforeEach - void setUp() { - MockitoAnnotations.openMocks(this); - callback = new TestEventCallback(emitter); - when(emitter.isCancelled()).thenReturn(false); - } - - @Test - void testSuccessfulStreamResponse() throws IOException { - // 准备测试数据 - String testData = "test line 1\ntest line 2\n done\n"; - ResponseBody responseBody = ResponseBody.create( - testData, - MediaType.parse("text/event-stream") - ); - Response response = Response.success(responseBody, Utils.getCommonHeader()); - - // 执行测试 - callback.onResponse(call, response); - - // 验证结果 - verify(emitter, times(3)).onNext(anyString()); - verify(emitter).onNext("test line 1"); - verify(emitter).onNext("test line 2"); - verify(emitter).onComplete(); - } - - @Test - void testErrorResponse() throws IOException { - // 准备错误响应数据 - CozeError error = new CozeError(); - error.setErrorMessage("Test error"); - String errorJson = "{\"error_message\":\"Test error\"}"; - ResponseBody errorBody = ResponseBody.create( - errorJson, - MediaType.parse("application/json") - ); - Response response = Response.error(400, errorBody); - - // 执行测试 - callback.onResponse(call, response); - - // 验证结果 - verify(emitter).onError(any(CozeApiExcetion.class)); - } - - @Test - void testJsonResponse() throws IOException { - // 准备 JSON 响应数据 - BaseResponse baseResponse = BaseResponse.builder() - .code(0) - .msg("success") - .data("test data") - .build(); - String jsonResponse = "{\"code\":0,\"msg\":\"success\",\"data\":\"test data\"}"; - ResponseBody responseBody = ResponseBody.create( - jsonResponse, - MediaType.parse("application/json") - ); - Headers headers = Headers.of( - "Content-Type", "application/json", - Utils.LOG_HEADER, "test_log_id" - ); - Response response = Response.success(responseBody, headers); - - // 执行测试 - callback.onResponse(call, response); - - // 验证结果 - verify(emitter, never()).onNext(anyString()); - verify(emitter, never()).onError(any()); - } - - @Test - void testErrorJsonResponse() throws IOException { - // 准备错误的 JSON 响应数据 - String jsonResponse = "{\"code\":1001,\"msg\":\"error message\"}"; - ResponseBody responseBody = ResponseBody.create( - jsonResponse, - MediaType.parse("application/json") - ); - Headers headers = Headers.of( - "Content-Type", "application/json", - Utils.LOG_HEADER, "test_log_id" - ); - Response response = Response.success(responseBody, headers); - - // 执行测试 - callback.onResponse(call, response); - - // 验证结果 - verify(emitter).onError(any(CozeApiExcetion.class)); - } + @Mock private FlowableEmitter emitter; - @Test - void testOnFailure() { - // 准备测试数据 - Throwable error = new IOException("Network error"); + @Mock private Call call; - // 执行测试 - callback.onFailure(call, error); + private TestEventCallback callback; - // 验证结果 - verify(emitter).onError(error); + private static class TestEventCallback extends AbstractEventCallback { + public TestEventCallback(FlowableEmitter emitter) { + super(emitter); } - @Test - void testCancelledEmitter() throws IOException { - // 设置 emitter 为已取消状态 - when(emitter.isCancelled()).thenReturn(true); - - // 准备测试数据 - String testData = "test line\n"; - ResponseBody responseBody = ResponseBody.create( - testData, - MediaType.parse("text/event-stream") - ); - Response response = Response.success(responseBody); - - // 执行测试 - callback.onResponse(call, response); - - // 验证结果 - verify(emitter, never()).onNext(anyString()); - verify(emitter).onComplete(); + @Override + protected boolean processLine(String line, BufferedReader reader, String logID) { + emitter.onNext(line); + return line.contains("done"); } -} \ No newline at end of file + } + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + callback = new TestEventCallback(emitter); + when(emitter.isCancelled()).thenReturn(false); + } + + @Test + void testSuccessfulStreamResponse() throws IOException { + // 准备测试数据 + String testData = "test line 1\ntest line 2\n done\n"; + ResponseBody responseBody = ResponseBody.create(testData, MediaType.parse("text/event-stream")); + Response response = Response.success(responseBody, Utils.getCommonHeader()); + + // 执行测试 + callback.onResponse(call, response); + + // 验证结果 + verify(emitter, times(3)).onNext(anyString()); + verify(emitter).onNext("test line 1"); + verify(emitter).onNext("test line 2"); + verify(emitter).onComplete(); + } + + @Test + void testErrorResponse() throws IOException { + // 准备错误响应数据 + CozeError error = new CozeError(); + error.setErrorMessage("Test error"); + String errorJson = "{\"error_message\":\"Test error\"}"; + ResponseBody errorBody = ResponseBody.create(errorJson, MediaType.parse("application/json")); + Response response = Response.error(400, errorBody); + + // 执行测试 + callback.onResponse(call, response); + + // 验证结果 + verify(emitter).onError(any(CozeApiExcetion.class)); + } + + @Test + void testJsonResponse() throws IOException { + // 准备 JSON 响应数据 + BaseResponse baseResponse = + BaseResponse.builder().code(0).msg("success").data("test data").build(); + String jsonResponse = "{\"code\":0,\"msg\":\"success\",\"data\":\"test data\"}"; + ResponseBody responseBody = + ResponseBody.create(jsonResponse, MediaType.parse("application/json")); + Headers headers = + Headers.of("Content-Type", "application/json", Utils.LOG_HEADER, "test_log_id"); + Response response = Response.success(responseBody, headers); + + // 执行测试 + callback.onResponse(call, response); + + // 验证结果 + verify(emitter, never()).onNext(anyString()); + verify(emitter, never()).onError(any()); + } + + @Test + void testErrorJsonResponse() throws IOException { + // 准备错误的 JSON 响应数据 + String jsonResponse = "{\"code\":1001,\"msg\":\"error message\"}"; + ResponseBody responseBody = + ResponseBody.create(jsonResponse, MediaType.parse("application/json")); + Headers headers = + Headers.of("Content-Type", "application/json", Utils.LOG_HEADER, "test_log_id"); + Response response = Response.success(responseBody, headers); + + // 执行测试 + callback.onResponse(call, response); + + // 验证结果 + verify(emitter).onError(any(CozeApiExcetion.class)); + } + + @Test + void testOnFailure() { + // 准备测试数据 + Throwable error = new IOException("Network error"); + + // 执行测试 + callback.onFailure(call, error); + + // 验证结果 + verify(emitter).onError(error); + } + + @Test + void testCancelledEmitter() throws IOException { + // 设置 emitter 为已取消状态 + when(emitter.isCancelled()).thenReturn(true); + + // 准备测试数据 + String testData = "test line\n"; + ResponseBody responseBody = ResponseBody.create(testData, MediaType.parse("text/event-stream")); + Response response = Response.success(responseBody); + + // 执行测试 + callback.onResponse(call, response); + + // 验证结果 + verify(emitter, never()).onNext(anyString()); + verify(emitter).onComplete(); + } +} diff --git a/api/src/test/java/com/coze/openapi/service/service/conversation/ConversationServiceTest.java b/api/src/test/java/com/coze/openapi/service/service/conversation/ConversationServiceTest.java index e992a212..805c82df 100644 --- a/api/src/test/java/com/coze/openapi/service/service/conversation/ConversationServiceTest.java +++ b/api/src/test/java/com/coze/openapi/service/service/conversation/ConversationServiceTest.java @@ -1,5 +1,19 @@ +/* (C)2024 */ package com.coze.openapi.service.service.conversation; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + import com.coze.openapi.api.ConversationAPI; import com.coze.openapi.api.ConversationMessageAPI; import com.coze.openapi.client.common.BaseResponse; @@ -7,175 +21,154 @@ import com.coze.openapi.client.connversations.*; import com.coze.openapi.client.connversations.model.Conversation; import com.coze.openapi.utils.Utils; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; + import retrofit2.Call; import retrofit2.Response; -import java.util.Arrays; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - class ConversationServiceTest { - @Mock - private ConversationAPI conversationAPI; - - @Mock - private ConversationMessageAPI messageAPI; - - private ConversationService conversationService; - - @BeforeEach - void setUp() { - MockitoAnnotations.openMocks(this); - conversationService = new ConversationService(conversationAPI, messageAPI); - } - - @Test - void testCreate() throws Exception { - // 准备测试数据 - CreateConversationReq req = CreateConversationReq.builder() - .botID("test_bot_id") - .build(); - - Conversation conversation = Conversation.builder() - .id("conv_id") - .build(); - - BaseResponse baseResponse = BaseResponse.builder() - .code(0) - .msg("success") - .logID(Utils.TEST_LOG_ID) - .data(conversation) - .build(); - - // 创建 mock Call 对象 - Call> call = mock(Call.class); - when(conversationAPI.create(any(CreateConversationReq.class), any(CreateConversationReq.class))) - .thenReturn(call); - when(call.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); - - // 执行测试 - CreateConversationResp result = conversationService.create(req); - - // 验证结果 - assertNotNull(result); - assertEquals("conv_id", result.getConversation().getId()); - } - - @Test - void testList() throws Exception { - // 准备测试数据 - String botId = "test_bot_id"; - ListConversationReq req = ListConversationReq.builder() - .botID(botId) - .pageNum(1) - .pageSize(10) - .build(); - - List conversations = Arrays.asList( - Conversation.builder().id("conv1").build(), - Conversation.builder().id("conv2").build() - ); - - ListConversationResp listResp = ListConversationResp.builder() - .conversations(conversations) - .hasMore(false) - .logID(Utils.TEST_LOG_ID) - .build(); - - BaseResponse baseResponse = BaseResponse.builder() - .code(0) - .msg("success") - .logID(Utils.TEST_LOG_ID) - .data(listResp) - .build(); - - // 创建 mock Call 对象 - Call> call = mock(Call.class); - when(conversationAPI.list(eq(botId), eq(1), eq(10), any(ListConversationReq.class))) - .thenReturn(call); - when(call.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); - - // 执行测试 - PageResp result = conversationService.list(req); - - // 验证结果 - assertNotNull(result); - assertEquals(2, result.getItems().size()); - assertEquals("conv1", result.getItems().get(0).getId()); - } - - @Test - void testRetrieve() throws Exception { - // 准备测试数据 - String conversationId = "test_conversation_id"; - RetrieveConversationReq req = RetrieveConversationReq.builder() - .conversationID(conversationId) - .build(); - - Conversation conversation = Conversation.builder() - .id(conversationId) - .build(); - - BaseResponse baseResponse = BaseResponse.builder() - .code(0) - .msg("success") - .logID(Utils.TEST_LOG_ID) - .data(conversation) - .build(); - - // 创建 mock Call 对象 - Call> call = mock(Call.class); - when(conversationAPI.retrieve(eq(conversationId), any(RetrieveConversationReq.class))) - .thenReturn(call); - when(call.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); - - // 执行测试 - RetrieveConversationResp result = conversationService.retrieve(req); - - // 验证结果 - assertNotNull(result); - assertEquals(conversationId, result.getConversation().getId()); - } - - @Test - void testClear() throws Exception { - // 准备测试数据 - String conversationId = "test_conversation_id"; - ClearConversationReq req = ClearConversationReq.builder() - .conversationID(conversationId) - .build(); - - ClearConversationResp clearResp = ClearConversationResp.builder() - .conversationID(conversationId) - .build(); - - BaseResponse baseResponse = BaseResponse.builder() - .code(0) - .msg("success") - .logID(Utils.TEST_LOG_ID) - .data(clearResp) - .build(); - - // 创建 mock Call 对象 - Call> call = mock(Call.class); - when(conversationAPI.clear(eq(conversationId), any(ClearConversationReq.class))) - .thenReturn(call); - when(call.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); - - // 执行测试 - ClearConversationResp result = conversationService.clear(req); - - // 验证结果 - assertNotNull(result); - assertEquals(conversationId, result.getConversationID()); - } -} \ No newline at end of file + @Mock private ConversationAPI conversationAPI; + + @Mock private ConversationMessageAPI messageAPI; + + private ConversationService conversationService; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + conversationService = new ConversationService(conversationAPI, messageAPI); + } + + @Test + void testCreate() throws Exception { + // 准备测试数据 + CreateConversationReq req = CreateConversationReq.builder().botID("test_bot_id").build(); + + Conversation conversation = Conversation.builder().id("conv_id").build(); + + BaseResponse baseResponse = + BaseResponse.builder() + .code(0) + .msg("success") + .logID(Utils.TEST_LOG_ID) + .data(conversation) + .build(); + + // 创建 mock Call 对象 + Call> call = mock(Call.class); + when(conversationAPI.create(any(CreateConversationReq.class), any(CreateConversationReq.class))) + .thenReturn(call); + when(call.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); + + // 执行测试 + CreateConversationResp result = conversationService.create(req); + + // 验证结果 + assertNotNull(result); + assertEquals("conv_id", result.getConversation().getId()); + } + + @Test + void testList() throws Exception { + // 准备测试数据 + String botId = "test_bot_id"; + ListConversationReq req = + ListConversationReq.builder().botID(botId).pageNum(1).pageSize(10).build(); + + List conversations = + Arrays.asList( + Conversation.builder().id("conv1").build(), Conversation.builder().id("conv2").build()); + + ListConversationResp listResp = + ListConversationResp.builder() + .conversations(conversations) + .hasMore(false) + .logID(Utils.TEST_LOG_ID) + .build(); + + BaseResponse baseResponse = + BaseResponse.builder() + .code(0) + .msg("success") + .logID(Utils.TEST_LOG_ID) + .data(listResp) + .build(); + + // 创建 mock Call 对象 + Call> call = mock(Call.class); + when(conversationAPI.list(eq(botId), eq(1), eq(10), any(ListConversationReq.class))) + .thenReturn(call); + when(call.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); + + // 执行测试 + PageResp result = conversationService.list(req); + + // 验证结果 + assertNotNull(result); + assertEquals(2, result.getItems().size()); + assertEquals("conv1", result.getItems().get(0).getId()); + } + + @Test + void testRetrieve() throws Exception { + // 准备测试数据 + String conversationId = "test_conversation_id"; + RetrieveConversationReq req = + RetrieveConversationReq.builder().conversationID(conversationId).build(); + + Conversation conversation = Conversation.builder().id(conversationId).build(); + + BaseResponse baseResponse = + BaseResponse.builder() + .code(0) + .msg("success") + .logID(Utils.TEST_LOG_ID) + .data(conversation) + .build(); + + // 创建 mock Call 对象 + Call> call = mock(Call.class); + when(conversationAPI.retrieve(eq(conversationId), any(RetrieveConversationReq.class))) + .thenReturn(call); + when(call.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); + + // 执行测试 + RetrieveConversationResp result = conversationService.retrieve(req); + + // 验证结果 + assertNotNull(result); + assertEquals(conversationId, result.getConversation().getId()); + } + + @Test + void testClear() throws Exception { + // 准备测试数据 + String conversationId = "test_conversation_id"; + ClearConversationReq req = + ClearConversationReq.builder().conversationID(conversationId).build(); + + ClearConversationResp clearResp = + ClearConversationResp.builder().conversationID(conversationId).build(); + + BaseResponse baseResponse = + BaseResponse.builder() + .code(0) + .msg("success") + .logID(Utils.TEST_LOG_ID) + .data(clearResp) + .build(); + + // 创建 mock Call 对象 + Call> call = mock(Call.class); + when(conversationAPI.clear(eq(conversationId), any(ClearConversationReq.class))) + .thenReturn(call); + when(call.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); + + // 执行测试 + ClearConversationResp result = conversationService.clear(req); + + // 验证结果 + assertNotNull(result); + assertEquals(conversationId, result.getConversationID()); + } +} diff --git a/api/src/test/java/com/coze/openapi/service/service/conversation/MessageServiceTest.java b/api/src/test/java/com/coze/openapi/service/service/conversation/MessageServiceTest.java index c957bc23..f69dc773 100644 --- a/api/src/test/java/com/coze/openapi/service/service/conversation/MessageServiceTest.java +++ b/api/src/test/java/com/coze/openapi/service/service/conversation/MessageServiceTest.java @@ -1,5 +1,19 @@ +/* (C)2024 */ package com.coze.openapi.service.service.conversation; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + import com.coze.openapi.api.ConversationMessageAPI; import com.coze.openapi.client.common.BaseResponse; import com.coze.openapi.client.common.pagination.PageResp; @@ -8,180 +22,160 @@ import com.coze.openapi.client.connversations.message.model.MessageContentType; import com.coze.openapi.client.connversations.message.model.MessageRole; import com.coze.openapi.utils.Utils; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; + import retrofit2.Call; import retrofit2.Response; -import java.util.Arrays; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - class MessageServiceTest { - @Mock - private ConversationMessageAPI messageAPI; - - private MessageService messageService; - - @BeforeEach - void setUp() { - MockitoAnnotations.openMocks(this); - messageService = new MessageService(messageAPI); - } - - @Test - void testCreate() throws Exception { - // 准���测试数据 - String conversationId = "test_conversation_id"; - CreateMessageReq req = CreateMessageReq.builder() - .conversationID(conversationId) - .role(MessageRole.USER) - .contentType(MessageContentType.TEXT) - .content("Test message") - .build(); - - Message message = Message.buildUserQuestionText("Test message"); - message.setId("msg_id"); - - BaseResponse baseResponse = BaseResponse.builder() - .code(0) - .msg("success") - .logID(Utils.TEST_LOG_ID) - .data(message) - .build(); - - // 创建 mock Call 对象 - Call> call = mock(Call.class); - when(messageAPI.create(eq(conversationId), any(CreateMessageReq.class), any(CreateMessageReq.class))) - .thenReturn(call); - when(call.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); - - // 执行测试 - CreateMessageResp result = messageService.create(req); - - // 验证结果 - assertNotNull(result); - assertEquals("msg_id", result.getMessage().getId()); - assertEquals(Utils.TEST_LOG_ID, result.getLogID()); - } - - @Test - void testList() throws Exception { - // 准备测试数据 - String conversationId = "test_conversation_id"; - ListMessageReq req = ListMessageReq.builder() - .conversationID(conversationId) - .limit(10) - .build(); - - List messages = Arrays.asList( - Message.builder().id("msg1").content("Message 1").build(), - Message.builder().id("msg2").content("Message 2").build() - ); - - ListMessageResp listResp = ListMessageResp.builder() - .data(messages) - .firstID("msg1") - .lastID("msg2") - .build(); - - BaseResponse baseResponse = BaseResponse.builder() - .code(0) - .msg("success") - .logID(Utils.TEST_LOG_ID) - .data(listResp) - .build(); - - // 创建 mock Call 对象 - Call call = mock(Call.class); - when(messageAPI.list(eq(conversationId), any(ListMessageReq.class), any(ListMessageReq.class))) - .thenReturn(call); - when(call.execute()).thenReturn(Response.success(baseResponse.getData(), Utils.getCommonHeader())); - - // 执行测试 - PageResp result = messageService.list(req); - - // 验证结果 - assertNotNull(result); - assertEquals(2, result.getItems().size()); - assertEquals("msg1", result.getItems().get(0).getId()); - } - - @Test - void testRetrieve() throws Exception { - // 准备测试数据 - String conversationId = "test_conversation_id"; - String messageId = "test_message_id"; - RetrieveMessageReq req = RetrieveMessageReq.builder() - .conversationID(conversationId) - .messageID(messageId) - .build(); - - Message message = Message.builder() - .id(messageId) - .content("Test message") - .build(); - - BaseResponse baseResponse = BaseResponse.builder() - .code(0) - .msg("success") - .logID(Utils.TEST_LOG_ID) - .data(message) - .build(); - - // 创建 mock Call 对象 - Call> call = mock(Call.class); - when(messageAPI.retrieve(eq(conversationId), eq(messageId), any(RetrieveMessageReq.class))) - .thenReturn(call); - when(call.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); - - // 执行测试 - RetrieveMessageResp result = messageService.retrieve(req); - - // 验证结果 - assertNotNull(result); - assertEquals(messageId, result.getMessage().getId()); - } - - @Test - void testDelete() throws Exception { - // 准备测试数据 - String conversationId = "test_conversation_id"; - String messageId = "test_message_id"; - DeleteMessageReq req = DeleteMessageReq.builder() - .conversationID(conversationId) - .messageID(messageId) - .build(); - - Message message = Message.builder() - .id(messageId) - .build(); - - BaseResponse baseResponse = BaseResponse.builder() - .code(0) - .msg("success") - .logID(Utils.TEST_LOG_ID) - .data(message) - .build(); - - // 创建 mock Call 对象 - Call> call = mock(Call.class); - when(messageAPI.delete(eq(conversationId), eq(messageId), any(DeleteMessageReq.class))) - .thenReturn(call); - when(call.execute()).thenReturn(Response.success(baseResponse)); - - // 执行测试 - DeleteMessageResp result = messageService.delete(req); - - // 验证结果 - assertNotNull(result); - assertEquals(messageId, result.getMessage().getId()); - } -} \ No newline at end of file + @Mock private ConversationMessageAPI messageAPI; + + private MessageService messageService; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + messageService = new MessageService(messageAPI); + } + + @Test + void testCreate() throws Exception { + // 准���测试数据 + String conversationId = "test_conversation_id"; + CreateMessageReq req = + CreateMessageReq.builder() + .conversationID(conversationId) + .role(MessageRole.USER) + .contentType(MessageContentType.TEXT) + .content("Test message") + .build(); + + Message message = Message.buildUserQuestionText("Test message"); + message.setId("msg_id"); + + BaseResponse baseResponse = + BaseResponse.builder() + .code(0) + .msg("success") + .logID(Utils.TEST_LOG_ID) + .data(message) + .build(); + + // 创建 mock Call 对象 + Call> call = mock(Call.class); + when(messageAPI.create( + eq(conversationId), any(CreateMessageReq.class), any(CreateMessageReq.class))) + .thenReturn(call); + when(call.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); + + // 执行测试 + CreateMessageResp result = messageService.create(req); + + // 验证结果 + assertNotNull(result); + assertEquals("msg_id", result.getMessage().getId()); + assertEquals(Utils.TEST_LOG_ID, result.getLogID()); + } + + @Test + void testList() throws Exception { + // 准备测试数据 + String conversationId = "test_conversation_id"; + ListMessageReq req = ListMessageReq.builder().conversationID(conversationId).limit(10).build(); + + List messages = + Arrays.asList( + Message.builder().id("msg1").content("Message 1").build(), + Message.builder().id("msg2").content("Message 2").build()); + + ListMessageResp listResp = + ListMessageResp.builder().data(messages).firstID("msg1").lastID("msg2").build(); + + BaseResponse baseResponse = + BaseResponse.builder() + .code(0) + .msg("success") + .logID(Utils.TEST_LOG_ID) + .data(listResp) + .build(); + + // 创建 mock Call 对象 + Call call = mock(Call.class); + when(messageAPI.list(eq(conversationId), any(ListMessageReq.class), any(ListMessageReq.class))) + .thenReturn(call); + when(call.execute()) + .thenReturn(Response.success(baseResponse.getData(), Utils.getCommonHeader())); + + // 执行测试 + PageResp result = messageService.list(req); + + // 验证结果 + assertNotNull(result); + assertEquals(2, result.getItems().size()); + assertEquals("msg1", result.getItems().get(0).getId()); + } + + @Test + void testRetrieve() throws Exception { + // 准备测试数据 + String conversationId = "test_conversation_id"; + String messageId = "test_message_id"; + RetrieveMessageReq req = + RetrieveMessageReq.builder().conversationID(conversationId).messageID(messageId).build(); + + Message message = Message.builder().id(messageId).content("Test message").build(); + + BaseResponse baseResponse = + BaseResponse.builder() + .code(0) + .msg("success") + .logID(Utils.TEST_LOG_ID) + .data(message) + .build(); + + // 创建 mock Call 对象 + Call> call = mock(Call.class); + when(messageAPI.retrieve(eq(conversationId), eq(messageId), any(RetrieveMessageReq.class))) + .thenReturn(call); + when(call.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); + + // 执行测试 + RetrieveMessageResp result = messageService.retrieve(req); + + // 验证结果 + assertNotNull(result); + assertEquals(messageId, result.getMessage().getId()); + } + + @Test + void testDelete() throws Exception { + // 准备测试数据 + String conversationId = "test_conversation_id"; + String messageId = "test_message_id"; + DeleteMessageReq req = + DeleteMessageReq.builder().conversationID(conversationId).messageID(messageId).build(); + + Message message = Message.builder().id(messageId).build(); + + BaseResponse baseResponse = + BaseResponse.builder() + .code(0) + .msg("success") + .logID(Utils.TEST_LOG_ID) + .data(message) + .build(); + + // 创建 mock Call 对象 + Call> call = mock(Call.class); + when(messageAPI.delete(eq(conversationId), eq(messageId), any(DeleteMessageReq.class))) + .thenReturn(call); + when(call.execute()).thenReturn(Response.success(baseResponse)); + + // 执行测试 + DeleteMessageResp result = messageService.delete(req); + + // 验证结果 + assertNotNull(result); + assertEquals(messageId, result.getMessage().getId()); + } +} diff --git a/api/src/test/java/com/coze/openapi/service/service/dataset/DocumentServiceTest.java b/api/src/test/java/com/coze/openapi/service/service/dataset/DocumentServiceTest.java index 89d6e5b3..754811fe 100644 --- a/api/src/test/java/com/coze/openapi/service/service/dataset/DocumentServiceTest.java +++ b/api/src/test/java/com/coze/openapi/service/service/dataset/DocumentServiceTest.java @@ -1,5 +1,20 @@ +/* (C)2024 */ package com.coze.openapi.service.service.dataset; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + import com.coze.openapi.api.DocumentAPI; import com.coze.openapi.client.common.BaseResponse; import com.coze.openapi.client.common.pagination.PageResp; @@ -7,158 +22,132 @@ import com.coze.openapi.client.dataset.document.model.Document; import com.coze.openapi.client.dataset.document.model.DocumentBase; import com.coze.openapi.utils.Utils; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; + import retrofit2.Call; import retrofit2.Response; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - class DocumentServiceTest { - @Mock - private DocumentAPI documentAPI; - - private DocumentService documentService; - - private Long dataSetID = 12345L; - - @BeforeEach - void setUp() { - MockitoAnnotations.openMocks(this); - documentService = new DocumentService(documentAPI); - } - - @Test - void testCreate() throws Exception { - // 准备测试数据 - CreateDocumentReq req = CreateDocumentReq.builder() - .datasetID(dataSetID) - .documentBases(Collections.singletonList(DocumentBase.buildWebPage("web document", "www.coze.com"))) - .build(); - - CreateDocumentResp createResp = CreateDocumentResp.builder() - .documentInfos(Arrays.asList( - Document.builder() - .documentID("123456") - .build() - )) - .logID(Utils.TEST_LOG_ID) - .build(); - - // 创建 mock Call 对象 - Call call = mock(Call.class); - when(documentAPI.create(any(CreateDocumentReq.class), any(CreateDocumentReq.class))) - .thenReturn(call); - when(call.execute()).thenReturn(Response.success(createResp, Utils.getCommonHeader())); - - // 执行测试 - CreateDocumentResp result = documentService.create(req); - - // 验证结果 - assertNotNull(result); - assertEquals("123456", result.getDocumentInfos().get(0).getDocumentID()); - assertEquals(Utils.TEST_LOG_ID, result.getLogID()); - } - - @Test - void testUpdate() throws Exception { - // 准备测试数据 - UpdateDocumentReq req = UpdateDocumentReq.builder() - .documentID(12345L) - .documentName("updated_name") - .build(); - - BaseResponse baseResponse = BaseResponse.builder() - .code(0) - .msg("success") - .logID(Utils.TEST_LOG_ID) - .build(); - - // 创建 mock Call 对象 - Call> call = mock(Call.class); - when(documentAPI.update(any(UpdateDocumentReq.class), any(UpdateDocumentReq.class))) - .thenReturn(call); - when(call.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); - - // 执行测试 - UpdateDocumentResp result = documentService.update(req); - - // 验证结果 - assertNotNull(result); - assertEquals(Utils.TEST_LOG_ID, result.getLogID()); - } - - @Test - void testDelete() throws Exception { - // 准备测试数据 - DeleteDocumentReq req = DeleteDocumentReq.builder() - .documentIDs(Arrays.asList(12345L, 123456L)) - .build(); - - BaseResponse baseResponse = BaseResponse.builder() - .code(0) - .msg("success") - .logID(Utils.TEST_LOG_ID) - .build(); - - // 创建 mock Call 对象 - Call> call = mock(Call.class); - when(documentAPI.delete(any(DeleteDocumentReq.class), any(DeleteDocumentReq.class))) - .thenReturn(call); - when(call.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); - - // 执行测试 - DeleteDocumentResp result = documentService.delete(req); - - // 验证结果 - assertNotNull(result); - assertEquals(Utils.TEST_LOG_ID, result.getLogID()); - } - - @Test - void testList() throws Exception { - // 准备测试数据 - ListDocumentReq req = ListDocumentReq.builder() - .datasetID(dataSetID) - .page(1) - .size(10) - .build(); - - List documents = Arrays.asList( - Document.builder().documentID("doc1").name("Document 1").build(), - Document.builder().documentID("doc2").name("Document 2").build() - ); - - ListDocumentResp listResp = ListDocumentResp.builder() - .documentInfos(documents) - .total(2L) - .logID(Utils.TEST_LOG_ID) - .build(); - - // 创建 mock Call 对象 - Call call = mock(Call.class); - when(documentAPI.list(any(ListDocumentReq.class), any(ListDocumentReq.class))) - .thenReturn(call); - when(call.execute()).thenReturn(Response.success(listResp, Utils.getCommonHeader())); - - // 执行测试 - PageResp result = documentService.list(req); - - // 验证结果 - assertNotNull(result); - assertEquals(2, result.getItems().size()); - assertEquals("doc1", result.getItems().get(0).getDocumentID()); - assertEquals(Utils.TEST_LOG_ID, result.getLogID()); - assertEquals(2, result.getTotal()); - } -} \ No newline at end of file + @Mock private DocumentAPI documentAPI; + + private DocumentService documentService; + + private Long dataSetID = 12345L; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + documentService = new DocumentService(documentAPI); + } + + @Test + void testCreate() throws Exception { + // 准备测试数据 + CreateDocumentReq req = + CreateDocumentReq.builder() + .datasetID(dataSetID) + .documentBases( + Collections.singletonList( + DocumentBase.buildWebPage("web document", "www.coze.com"))) + .build(); + + CreateDocumentResp createResp = + CreateDocumentResp.builder() + .documentInfos(Arrays.asList(Document.builder().documentID("123456").build())) + .logID(Utils.TEST_LOG_ID) + .build(); + + // 创建 mock Call 对象 + Call call = mock(Call.class); + when(documentAPI.create(any(CreateDocumentReq.class), any(CreateDocumentReq.class))) + .thenReturn(call); + when(call.execute()).thenReturn(Response.success(createResp, Utils.getCommonHeader())); + + // 执行测试 + CreateDocumentResp result = documentService.create(req); + + // 验证结果 + assertNotNull(result); + assertEquals("123456", result.getDocumentInfos().get(0).getDocumentID()); + assertEquals(Utils.TEST_LOG_ID, result.getLogID()); + } + + @Test + void testUpdate() throws Exception { + // 准备测试数据 + UpdateDocumentReq req = + UpdateDocumentReq.builder().documentID(12345L).documentName("updated_name").build(); + + BaseResponse baseResponse = + BaseResponse.builder().code(0).msg("success").logID(Utils.TEST_LOG_ID).build(); + + // 创建 mock Call 对象 + Call> call = mock(Call.class); + when(documentAPI.update(any(UpdateDocumentReq.class), any(UpdateDocumentReq.class))) + .thenReturn(call); + when(call.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); + + // 执行测试 + UpdateDocumentResp result = documentService.update(req); + + // 验证结果 + assertNotNull(result); + assertEquals(Utils.TEST_LOG_ID, result.getLogID()); + } + + @Test + void testDelete() throws Exception { + // 准备测试数据 + DeleteDocumentReq req = + DeleteDocumentReq.builder().documentIDs(Arrays.asList(12345L, 123456L)).build(); + + BaseResponse baseResponse = + BaseResponse.builder().code(0).msg("success").logID(Utils.TEST_LOG_ID).build(); + + // 创建 mock Call 对象 + Call> call = mock(Call.class); + when(documentAPI.delete(any(DeleteDocumentReq.class), any(DeleteDocumentReq.class))) + .thenReturn(call); + when(call.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); + + // 执行测试 + DeleteDocumentResp result = documentService.delete(req); + + // 验证结果 + assertNotNull(result); + assertEquals(Utils.TEST_LOG_ID, result.getLogID()); + } + + @Test + void testList() throws Exception { + // 准备测试数据 + ListDocumentReq req = ListDocumentReq.builder().datasetID(dataSetID).page(1).size(10).build(); + + List documents = + Arrays.asList( + Document.builder().documentID("doc1").name("Document 1").build(), + Document.builder().documentID("doc2").name("Document 2").build()); + + ListDocumentResp listResp = + ListDocumentResp.builder() + .documentInfos(documents) + .total(2L) + .logID(Utils.TEST_LOG_ID) + .build(); + + // 创建 mock Call 对象 + Call call = mock(Call.class); + when(documentAPI.list(any(ListDocumentReq.class), any(ListDocumentReq.class))).thenReturn(call); + when(call.execute()).thenReturn(Response.success(listResp, Utils.getCommonHeader())); + + // 执行测试 + PageResp result = documentService.list(req); + + // 验证结果 + assertNotNull(result); + assertEquals(2, result.getItems().size()); + assertEquals("doc1", result.getItems().get(0).getDocumentID()); + assertEquals(Utils.TEST_LOG_ID, result.getLogID()); + assertEquals(2, result.getTotal()); + } +} diff --git a/api/src/test/java/com/coze/openapi/service/service/file/FileServiceTest.java b/api/src/test/java/com/coze/openapi/service/service/file/FileServiceTest.java index 9d7d65d6..8c94c93e 100644 --- a/api/src/test/java/com/coze/openapi/service/service/file/FileServiceTest.java +++ b/api/src/test/java/com/coze/openapi/service/service/file/FileServiceTest.java @@ -1,5 +1,20 @@ +/* (C)2024 */ package com.coze.openapi.service.service.file; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.File; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + import com.coze.openapi.api.FileAPI; import com.coze.openapi.client.common.BaseResponse; import com.coze.openapi.client.files.RetrieveFileReq; @@ -8,164 +23,131 @@ import com.coze.openapi.client.files.UploadFileResp; import com.coze.openapi.client.files.model.FileInfo; import com.coze.openapi.utils.Utils; + import okhttp3.MultipartBody; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; import retrofit2.Call; import retrofit2.Response; -import java.io.File; -import java.io.FileWriter; -import java.nio.file.Path; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - class FileServiceTest { - @Mock - private FileAPI fileAPI; - - private FileService fileService; - - private File testFile; - private FileInfo mockFileInfo; - private BaseResponse mockBaseResponse; - - @BeforeEach - void setUp() throws Exception { - MockitoAnnotations.openMocks(this); - fileService = new FileService(fileAPI); - - // 创建测试文件 - testFile = File.createTempFile("test", ".txt"); - - // 准备通用的 mock 响应数据 - mockFileInfo = FileInfo.builder() - .id("file_id") - .fileName("test.txt") - .bytes(1024) - .build(); - - mockBaseResponse = BaseResponse.builder() - .code(0) - .msg("success") - .logID(Utils.TEST_LOG_ID) - .data(mockFileInfo) - .build(); - } - - @Test - void testUploadWithFilePath() throws Exception { - // 准备测试数据 - UploadFileReq req = UploadFileReq.builder() - .filePath(testFile.getAbsolutePath()) - .build(); - - // 创建 mock Call 对象 - Call> call = mock(Call.class); - when(fileAPI.upload(any(MultipartBody.Part.class), any(UploadFileReq.class))) - .thenReturn(call); - when(call.execute()).thenReturn(Response.success(mockBaseResponse, Utils.getCommonHeader())); - - // 执行测试 - UploadFileResp result = fileService.upload(req); - - // 验证结果 - assertNotNull(result); - assertEquals("file_id", result.getFileInfo().getID()); - assertEquals(Utils.TEST_LOG_ID, result.getLogID()); - } - - @Test - void testUploadWithFileBytes() throws Exception { - // 准备测试数据 - byte[] fileBytes = "Test content".getBytes(); - UploadFileReq req = UploadFileReq.builder() - .fileBytes(fileBytes) - .fileName("test.txt") - .build(); - - // 创建 mock Call 对象 - Call> call = mock(Call.class); - when(fileAPI.upload(any(MultipartBody.Part.class), any(UploadFileReq.class))) - .thenReturn(call); - when(call.execute()).thenReturn(Response.success(mockBaseResponse, Utils.getCommonHeader())); - - // 执行测试 - UploadFileResp result = fileService.upload(req); - - // 验证结果 - assertNotNull(result); - assertEquals("file_id", result.getFileInfo().getID()); - assertEquals(Utils.TEST_LOG_ID, result.getLogID()); - } - - @Test - void testUploadWithFile() throws Exception { - // 准备测试数据 - UploadFileReq req = UploadFileReq.builder() - .file(testFile) - .fileName("test.txt") - .build(); - - // 创建 mock Call 对象 - Call> call = mock(Call.class); - when(fileAPI.upload(any(MultipartBody.Part.class), any(UploadFileReq.class))) - .thenReturn(call); - when(call.execute()).thenReturn(Response.success(mockBaseResponse, Utils.getCommonHeader())); - - // 执行测试 - UploadFileResp result = fileService.upload(req); - - // 验证结果 - assertNotNull(result); - assertEquals("file_id", result.getFileInfo().getID()); - assertEquals(Utils.TEST_LOG_ID, result.getLogID()); - } - - @Test - void testUploadWithInvalidRequest() { - // 测试空请求 - UploadFileReq emptyReq = UploadFileReq.builder().build(); - assertThrows(IllegalArgumentException.class, () -> fileService.upload(emptyReq)); - } - - @Test - void testRetrieve() throws Exception { - // 准备测试数据 - String fileId = "test_file_id"; - RetrieveFileReq req = RetrieveFileReq.builder() - .fileID(fileId) - .build(); - - // 创建 mock Call 对象 - Call> call = mock(Call.class); - when(fileAPI.retrieve(eq(fileId), any(RetrieveFileReq.class))) - .thenReturn(call); - when(call.execute()).thenReturn(Response.success(mockBaseResponse, Utils.getCommonHeader())); - - // 执行测试 - RetrieveFileResp result = fileService.retrieve(req); - - // 验证结果 - assertNotNull(result); - assertEquals("file_id", result.getFileInfo().getID()); - assertEquals(Utils.TEST_LOG_ID, result.getLogID()); - } - - @AfterEach - void tearDown() { - // 清理临时文件 - if (testFile != null && testFile.exists()) { - testFile.delete(); - } + @Mock private FileAPI fileAPI; + + private FileService fileService; + + private File testFile; + private FileInfo mockFileInfo; + private BaseResponse mockBaseResponse; + + @BeforeEach + void setUp() throws Exception { + MockitoAnnotations.openMocks(this); + fileService = new FileService(fileAPI); + + // 创建测试文件 + testFile = File.createTempFile("test", ".txt"); + + // 准备通用的 mock 响应数据 + mockFileInfo = FileInfo.builder().id("file_id").fileName("test.txt").bytes(1024).build(); + + mockBaseResponse = + BaseResponse.builder() + .code(0) + .msg("success") + .logID(Utils.TEST_LOG_ID) + .data(mockFileInfo) + .build(); + } + + @Test + void testUploadWithFilePath() throws Exception { + // 准备测试数据 + UploadFileReq req = UploadFileReq.builder().filePath(testFile.getAbsolutePath()).build(); + + // 创建 mock Call 对象 + Call> call = mock(Call.class); + when(fileAPI.upload(any(MultipartBody.Part.class), any(UploadFileReq.class))).thenReturn(call); + when(call.execute()).thenReturn(Response.success(mockBaseResponse, Utils.getCommonHeader())); + + // 执行测试 + UploadFileResp result = fileService.upload(req); + + // 验证结果 + assertNotNull(result); + assertEquals("file_id", result.getFileInfo().getID()); + assertEquals(Utils.TEST_LOG_ID, result.getLogID()); + } + + @Test + void testUploadWithFileBytes() throws Exception { + // 准备测试数据 + byte[] fileBytes = "Test content".getBytes(); + UploadFileReq req = UploadFileReq.builder().fileBytes(fileBytes).fileName("test.txt").build(); + + // 创建 mock Call 对象 + Call> call = mock(Call.class); + when(fileAPI.upload(any(MultipartBody.Part.class), any(UploadFileReq.class))).thenReturn(call); + when(call.execute()).thenReturn(Response.success(mockBaseResponse, Utils.getCommonHeader())); + + // 执行测试 + UploadFileResp result = fileService.upload(req); + + // 验证结果 + assertNotNull(result); + assertEquals("file_id", result.getFileInfo().getID()); + assertEquals(Utils.TEST_LOG_ID, result.getLogID()); + } + + @Test + void testUploadWithFile() throws Exception { + // 准备测试数据 + UploadFileReq req = UploadFileReq.builder().file(testFile).fileName("test.txt").build(); + + // 创建 mock Call 对象 + Call> call = mock(Call.class); + when(fileAPI.upload(any(MultipartBody.Part.class), any(UploadFileReq.class))).thenReturn(call); + when(call.execute()).thenReturn(Response.success(mockBaseResponse, Utils.getCommonHeader())); + + // 执行测试 + UploadFileResp result = fileService.upload(req); + + // 验证结果 + assertNotNull(result); + assertEquals("file_id", result.getFileInfo().getID()); + assertEquals(Utils.TEST_LOG_ID, result.getLogID()); + } + + @Test + void testUploadWithInvalidRequest() { + // 测试空请求 + UploadFileReq emptyReq = UploadFileReq.builder().build(); + assertThrows(IllegalArgumentException.class, () -> fileService.upload(emptyReq)); + } + + @Test + void testRetrieve() throws Exception { + // 准备测试数据 + String fileId = "test_file_id"; + RetrieveFileReq req = RetrieveFileReq.builder().fileID(fileId).build(); + + // 创建 mock Call 对象 + Call> call = mock(Call.class); + when(fileAPI.retrieve(eq(fileId), any(RetrieveFileReq.class))).thenReturn(call); + when(call.execute()).thenReturn(Response.success(mockBaseResponse, Utils.getCommonHeader())); + + // 执行测试 + RetrieveFileResp result = fileService.retrieve(req); + + // 验证结果 + assertNotNull(result); + assertEquals("file_id", result.getFileInfo().getID()); + assertEquals(Utils.TEST_LOG_ID, result.getLogID()); + } + + @AfterEach + void tearDown() { + // 清理临时文件 + if (testFile != null && testFile.exists()) { + testFile.delete(); } -} \ No newline at end of file + } +} diff --git a/api/src/test/java/com/coze/openapi/service/service/workflow/EventCallbackTest.java b/api/src/test/java/com/coze/openapi/service/service/workflow/EventCallbackTest.java index 5245cbc8..aec8307e 100644 --- a/api/src/test/java/com/coze/openapi/service/service/workflow/EventCallbackTest.java +++ b/api/src/test/java/com/coze/openapi/service/service/workflow/EventCallbackTest.java @@ -1,55 +1,58 @@ +/* (C)2024 */ package com.coze.openapi.service.service.workflow; -import com.coze.openapi.client.workflows.run.model.WorkflowEvent; -import io.reactivex.FlowableEmitter; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.mockito.Mockito.*; + +import java.io.BufferedReader; +import java.io.StringReader; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.io.BufferedReader; -import java.io.StringReader; +import com.coze.openapi.client.workflows.run.model.WorkflowEvent; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.mockito.Mockito.*; +import io.reactivex.FlowableEmitter; class EventCallbackTest { - @Mock - private FlowableEmitter emitter; + @Mock private FlowableEmitter emitter; - private EventCallback callback; + private EventCallback callback; - @BeforeEach - void setUp() { - MockitoAnnotations.openMocks(this); - callback = new EventCallback(emitter); - } + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + callback = new EventCallback(emitter); + } - @Test - void testProcessLine() throws Exception { - // 准备测试数据 - String eventData = "id: 1\nevent: Message\ndata: {\"content\":\"为\",\"node_is_finish\":false,\"node_seq_id\":\"1\",\"node_title\":\"Message\"}"; - BufferedReader reader = new BufferedReader(new StringReader(eventData)); + @Test + void testProcessLine() throws Exception { + // 准备测试数据 + String eventData = + "id: 1\nevent: Message\ndata: {\"content\":\"为\",\"node_is_finish\":false,\"node_seq_id\":\"1\",\"node_title\":\"Message\"}"; + BufferedReader reader = new BufferedReader(new StringReader(eventData)); - // 执行测试 - callback.processLine(reader.readLine(), reader, "test_log_id"); + // 执行测试 + callback.processLine(reader.readLine(), reader, "test_log_id"); - // 验证结果 - verify(emitter, times(1)).onNext(any(WorkflowEvent.class)); - } + // 验证结果 + verify(emitter, times(1)).onNext(any(WorkflowEvent.class)); + } - @Test - void testProcessLineWithInvalidData() throws Exception { - // 准备测试数据 - String eventData = "invalid data\n"; - BufferedReader reader = new BufferedReader(new StringReader(eventData)); + @Test + void testProcessLineWithInvalidData() throws Exception { + // 准备测试数据 + String eventData = "invalid data\n"; + BufferedReader reader = new BufferedReader(new StringReader(eventData)); - // 执行测试 - boolean result = callback.processLine("invalid", reader, "test_log_id"); + // 执行测试 + boolean result = callback.processLine("invalid", reader, "test_log_id"); - // 验证结果 - assertFalse(result); - verify(emitter, never()).onNext(any(WorkflowEvent.class)); - } -} \ No newline at end of file + // 验证结果 + assertFalse(result); + verify(emitter, never()).onNext(any(WorkflowEvent.class)); + } +} diff --git a/api/src/test/java/com/coze/openapi/service/service/workflow/WorkFlowRunServiceTest.java b/api/src/test/java/com/coze/openapi/service/service/workflow/WorkFlowRunServiceTest.java index c1958b29..1ddebb4a 100644 --- a/api/src/test/java/com/coze/openapi/service/service/workflow/WorkFlowRunServiceTest.java +++ b/api/src/test/java/com/coze/openapi/service/service/workflow/WorkFlowRunServiceTest.java @@ -1,146 +1,143 @@ +/* (C)2024 */ package com.coze.openapi.service.service.workflow; +import static com.coze.openapi.service.service.workflow.WorkflowRunService.stream; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + import com.coze.openapi.api.WorkflowRunAPI; import com.coze.openapi.api.WorkflowRunHistoryAPI; import com.coze.openapi.client.workflows.run.RunWorkflowReq; import com.coze.openapi.client.workflows.run.RunWorkflowResp; import com.coze.openapi.client.workflows.run.model.WorkflowEvent; import com.coze.openapi.utils.Utils; + import io.reactivex.subscribers.TestSubscriber; import okhttp3.MediaType; import okhttp3.ResponseBody; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; import retrofit2.Call; import retrofit2.Response; import retrofit2.mock.Calls; -import java.util.concurrent.TimeUnit; - -import static com.coze.openapi.service.service.workflow.WorkflowRunService.stream; -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - public class WorkFlowRunServiceTest { - private String eventData = "id: 0\n" + - "event: Message\n" + - "data: {\"content\":\"msg\",\"node_is_finish\":false,\"node_seq_id\":\"0\",\"node_title\":\"Message\"}\n" + - "\n" + - "id: 1\n" + - "event: Message\n" + - "data: {\"content\":\"为\",\"node_is_finish\":false,\"node_seq_id\":\"1\",\"node_title\":\"Message\"}\n" + - "\n" + - "id: 2\n" + - "event: Message\n" + - "data: {\"content\":\"什么小明要带一把尺子去看电影因\",\"node_is_finish\":false,\"node_seq_id\":\"2\",\"node_title\":\"Message\"}\n" + - "\n" + - "id: 3\n" + - "event: Message\n" + - "data: {\"content\":\"为他听说电影很长,怕\",\"node_is_finish\":false,\"node_seq_id\":\"3\",\"node_title\":\"Message\"}\n" + - "\n" + - "id: 4\n" + - "event: Message\n" + - "data: {\"content\":\"坐不下!\",\"node_is_finish\":true,\"node_seq_id\":\"4\",\"node_title\":\"Message\"}\n" + - "\n" + - "id: 5\n" + - "event: Message\n" + - "data: {\"content\":\"{\\\"output\\\":\\\"为什么小明要带一把尺子去看电影?因为他听说电影很长,怕坐不下!\\\"}\",\"cost\":\"0.00\",\"node_is_finish\":true,\"node_seq_id\":\"0\",\"node_title\":\"\",\"token\":0}\n" + - "\n" + - "id: 0\n" + - "event: Error\n" + - "data: {\"error_code\":4000,\"error_message\":\"Request parameter error\"}\n" + - "\n" + - "id: 0\n" + - "event: Message\n" + - "data: {\"content\":\"请问你想查看哪个城市、哪一天的天气呢\",\"content_type\":\"text\",\"node_is_finish\":true,\"node_seq_id\":\"0\",\"node_title\":\"问答\"}\n" + - "\n" + - "id: 1\n" + - "event: Interrupt\n" + - "data: {\"interrupt_data\":{\"data\":\"\",\"event_id\":\"7404830425073352713/2769808280134765896\",\"type\":2},\"node_title\":\"问答\"}\n" + - "\n" + - "id: 6\n" + - "event: Done\n" + - "data: {}"; - - @Mock - private WorkflowRunAPI workflowRunAPI; - - @Mock - private WorkflowRunHistoryAPI workflowRunHistoryAPI; - - private WorkflowRunService workflowRunService; - - @BeforeEach - public void setup() { - MockitoAnnotations.openMocks(this); - workflowRunService = new WorkflowRunService(workflowRunAPI, workflowRunHistoryAPI); - } - - @Test - void parseStreamEventTest() { - // 准备请求数据 - RunWorkflowReq req = RunWorkflowReq.builder() - .workflowID("test-id") - .build(); - - // 准备 SSE 格式的响应数据 - // 使用 okio 的 Buffer 创建模拟的响应流 - ResponseBody responseBody = ResponseBody.create( - eventData, - MediaType.parse("text/event-stream; charset=utf-8") - ); - - // 模拟 API 调用 - Call call = Calls.response(responseBody); - TestSubscriber testSubscriber = new TestSubscriber<>(); - stream(call).subscribe(testSubscriber); - - testSubscriber.awaitTerminalEvent(5, TimeUnit.SECONDS); - - testSubscriber.assertNoErrors(); - testSubscriber.assertValueCount(10); - } - - @Test - void testCreate() throws Exception { - // 准备测试数据 - String workflowID = "test_workflow_id"; - String executeID = "test_execute_id"; - - RunWorkflowReq req = RunWorkflowReq.builder() - .workflowID(workflowID) - .build(); - - RunWorkflowResp baseResponse = RunWorkflowResp.builder() - .code(0) - .msg("success") - .executeID(executeID) - .logID(Utils.TEST_LOG_ID) - .data("data") - .build(); - - // 创建 mock Call 对象 - Call call = mock(Call.class); - when(workflowRunAPI.run(any(), any())).thenReturn(call); - when(call.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); - - // 执行测试 - RunWorkflowResp result = workflowRunService.create(req); - - // 验证结果 - assertNotNull(result); - assertEquals(executeID, result.getExecuteID()); - } - - @Test - void testHistories() { - // 验证 histories 方法 - WorkflowRunHistoryService historyService = workflowRunService.histories(); - assertNotNull(historyService); - } -} \ No newline at end of file + private String eventData = + "id: 0\n" + + "event: Message\n" + + "data: {\"content\":\"msg\",\"node_is_finish\":false,\"node_seq_id\":\"0\",\"node_title\":\"Message\"}\n" + + "\n" + + "id: 1\n" + + "event: Message\n" + + "data: {\"content\":\"为\",\"node_is_finish\":false,\"node_seq_id\":\"1\",\"node_title\":\"Message\"}\n" + + "\n" + + "id: 2\n" + + "event: Message\n" + + "data: {\"content\":\"什么小明要带一把尺子去看电影因\",\"node_is_finish\":false,\"node_seq_id\":\"2\",\"node_title\":\"Message\"}\n" + + "\n" + + "id: 3\n" + + "event: Message\n" + + "data: {\"content\":\"为他听说电影很长,怕\",\"node_is_finish\":false,\"node_seq_id\":\"3\",\"node_title\":\"Message\"}\n" + + "\n" + + "id: 4\n" + + "event: Message\n" + + "data: {\"content\":\"坐不下!\",\"node_is_finish\":true,\"node_seq_id\":\"4\",\"node_title\":\"Message\"}\n" + + "\n" + + "id: 5\n" + + "event: Message\n" + + "data: {\"content\":\"{\\\"output\\\":\\\"为什么小明要带一把尺子去看电影?因为他听说电影很长,怕坐不下!\\\"}\",\"cost\":\"0.00\",\"node_is_finish\":true,\"node_seq_id\":\"0\",\"node_title\":\"\",\"token\":0}\n" + + "\n" + + "id: 0\n" + + "event: Error\n" + + "data: {\"error_code\":4000,\"error_message\":\"Request parameter error\"}\n" + + "\n" + + "id: 0\n" + + "event: Message\n" + + "data: {\"content\":\"请问你想查看哪个城市、哪一天的天气呢\",\"content_type\":\"text\",\"node_is_finish\":true,\"node_seq_id\":\"0\",\"node_title\":\"问答\"}\n" + + "\n" + + "id: 1\n" + + "event: Interrupt\n" + + "data: {\"interrupt_data\":{\"data\":\"\",\"event_id\":\"7404830425073352713/2769808280134765896\",\"type\":2},\"node_title\":\"问答\"}\n" + + "\n" + + "id: 6\n" + + "event: Done\n" + + "data: {}"; + + @Mock private WorkflowRunAPI workflowRunAPI; + + @Mock private WorkflowRunHistoryAPI workflowRunHistoryAPI; + + private WorkflowRunService workflowRunService; + + @BeforeEach + public void setup() { + MockitoAnnotations.openMocks(this); + workflowRunService = new WorkflowRunService(workflowRunAPI, workflowRunHistoryAPI); + } + + @Test + void parseStreamEventTest() { + // 准备请求数据 + RunWorkflowReq req = RunWorkflowReq.builder().workflowID("test-id").build(); + + // 准备 SSE 格式的响应数据 + // 使用 okio 的 Buffer 创建模拟的响应流 + ResponseBody responseBody = + ResponseBody.create(eventData, MediaType.parse("text/event-stream; charset=utf-8")); + + // 模拟 API 调用 + Call call = Calls.response(responseBody); + TestSubscriber testSubscriber = new TestSubscriber<>(); + stream(call).subscribe(testSubscriber); + + testSubscriber.awaitTerminalEvent(5, TimeUnit.SECONDS); + + testSubscriber.assertNoErrors(); + testSubscriber.assertValueCount(10); + } + + @Test + void testCreate() throws Exception { + // 准备测试数据 + String workflowID = "test_workflow_id"; + String executeID = "test_execute_id"; + + RunWorkflowReq req = RunWorkflowReq.builder().workflowID(workflowID).build(); + + RunWorkflowResp baseResponse = + RunWorkflowResp.builder() + .code(0) + .msg("success") + .executeID(executeID) + .logID(Utils.TEST_LOG_ID) + .data("data") + .build(); + + // 创建 mock Call 对象 + Call call = mock(Call.class); + when(workflowRunAPI.run(any(), any())).thenReturn(call); + when(call.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); + + // 执行测试 + RunWorkflowResp result = workflowRunService.create(req); + + // 验证结果 + assertNotNull(result); + assertEquals(executeID, result.getExecuteID()); + } + + @Test + void testHistories() { + // 验证 histories 方法 + WorkflowRunHistoryService historyService = workflowRunService.histories(); + assertNotNull(historyService); + } +} diff --git a/api/src/test/java/com/coze/openapi/service/service/workflow/WorkflowRunHistoryServiceTest.java b/api/src/test/java/com/coze/openapi/service/service/workflow/WorkflowRunHistoryServiceTest.java index b8a167c9..b7e87d0a 100644 --- a/api/src/test/java/com/coze/openapi/service/service/workflow/WorkflowRunHistoryServiceTest.java +++ b/api/src/test/java/com/coze/openapi/service/service/workflow/WorkflowRunHistoryServiceTest.java @@ -1,75 +1,76 @@ +/* (C)2024 */ package com.coze.openapi.service.service.workflow; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + import com.coze.openapi.api.WorkflowRunHistoryAPI; import com.coze.openapi.client.common.BaseResponse; import com.coze.openapi.client.workflows.run.RetrieveRunHistoryReq; import com.coze.openapi.client.workflows.run.RetrieveRunHistoryResp; import com.coze.openapi.client.workflows.run.model.WorkflowRunHistory; import com.coze.openapi.utils.Utils; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; + import retrofit2.Call; import retrofit2.Response; -import java.util.Arrays; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - class WorkflowRunHistoryServiceTest { - @Mock - private WorkflowRunHistoryAPI historyAPI; + @Mock private WorkflowRunHistoryAPI historyAPI; - private WorkflowRunHistoryService historyService; + private WorkflowRunHistoryService historyService; - @BeforeEach - void setUp() { - MockitoAnnotations.openMocks(this); - historyService = new WorkflowRunHistoryService(historyAPI); - } + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + historyService = new WorkflowRunHistoryService(historyAPI); + } - @Test - void testRetrieve() throws Exception { - // 准备测试数据 - String workflowId = "workflow_id"; - String executeId = "execute_id"; - RetrieveRunHistoryReq req = RetrieveRunHistoryReq.builder() - .workflowID(workflowId) - .executeID(executeId) - .build(); + @Test + void testRetrieve() throws Exception { + // 准备测试数据 + String workflowId = "workflow_id"; + String executeId = "execute_id"; + RetrieveRunHistoryReq req = + RetrieveRunHistoryReq.builder().workflowID(workflowId).executeID(executeId).build(); - List histories = Arrays.asList( - WorkflowRunHistory.builder().executeID("node1").build(), - WorkflowRunHistory.builder().executeID("node2").build() - ); + List histories = + Arrays.asList( + WorkflowRunHistory.builder().executeID("node1").build(), + WorkflowRunHistory.builder().executeID("node2").build()); - BaseResponse> baseResponse = BaseResponse.>builder() - .code(0) - .msg("success") - .logID(Utils.TEST_LOG_ID) - .data(histories) - .build(); + BaseResponse> baseResponse = + BaseResponse.>builder() + .code(0) + .msg("success") + .logID(Utils.TEST_LOG_ID) + .data(histories) + .build(); - // 创建 mock Call 对象 - Call>> call = mock(Call.class); - when(historyAPI.retrieve(eq(workflowId), eq(executeId), any(RetrieveRunHistoryReq.class))) - .thenReturn(call); - when(call.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); + // 创建 mock Call 对象 + Call>> call = mock(Call.class); + when(historyAPI.retrieve(eq(workflowId), eq(executeId), any(RetrieveRunHistoryReq.class))) + .thenReturn(call); + when(call.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); - // 执行测试 - RetrieveRunHistoryResp result = historyService.retrieve(req); + // 执行测试 + RetrieveRunHistoryResp result = historyService.retrieve(req); - // 验证结果 - assertNotNull(result); - assertEquals(2, result.getHistories().size()); - assertEquals("node1", result.getHistories().get(0).getExecuteID()); - assertEquals(Utils.TEST_LOG_ID, result.getLogID()); - } -} \ No newline at end of file + // 验证结果 + assertNotNull(result); + assertEquals(2, result.getHistories().size()); + assertEquals("node1", result.getHistories().get(0).getExecuteID()); + assertEquals(Utils.TEST_LOG_ID, result.getLogID()); + } +} diff --git a/api/src/test/java/com/coze/openapi/service/service/workspace/WorkspaceServiceTest.java b/api/src/test/java/com/coze/openapi/service/service/workspace/WorkspaceServiceTest.java index 4b23faa0..9d351082 100644 --- a/api/src/test/java/com/coze/openapi/service/service/workspace/WorkspaceServiceTest.java +++ b/api/src/test/java/com/coze/openapi/service/service/workspace/WorkspaceServiceTest.java @@ -1,5 +1,20 @@ +/* (C)2024 */ package com.coze.openapi.service.service.workspace; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + import com.coze.openapi.api.WorkspaceAPI; import com.coze.openapi.client.common.BaseResponse; import com.coze.openapi.client.common.pagination.PageResp; @@ -7,132 +22,112 @@ import com.coze.openapi.client.workspace.ListWorkspaceResp; import com.coze.openapi.client.workspace.model.Workspace; import com.coze.openapi.utils.Utils; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; + import retrofit2.Call; import retrofit2.Response; -import java.util.Arrays; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - class WorkspaceServiceTest { - @Mock - private WorkspaceAPI workspaceAPI; - - private WorkspaceService workspaceService; - - @BeforeEach - void setUp() { - MockitoAnnotations.openMocks(this); - workspaceService = new WorkspaceService(workspaceAPI); - } - - @Test - void testListWorkspaces() throws Exception { - // 准备测试数据 - int pageNum = 1; - int pageSize = 2; - ListWorkspaceReq req = ListWorkspaceReq.builder() - .pageNum(pageNum) - .pageSize(pageSize) - .build(); - - // 准备模拟响应数据 - List workspaces = Arrays.asList( - Workspace.builder().id("workspace1").name("工作空间1").build(), - Workspace.builder().id("workspace2").name("工作空间2").build() - ); - - ListWorkspaceResp respData = ListWorkspaceResp.builder() - .workspaces(workspaces) - .totalCount(5) // 总共5条数据 - .build(); - - BaseResponse baseResponse = BaseResponse.builder() - .code(0) - .msg("success") - .logID(Utils.TEST_LOG_ID) - .data(respData) - .build(); - - // 创建 mock Call 对象 - Call> call = mock(Call.class); - when(workspaceAPI.list(eq(pageNum), eq(pageSize), any(ListWorkspaceReq.class))) - .thenReturn(call); - when(call.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); - - // 执行测试 - PageResp result = workspaceService.list(req); - - // 验证结果 - assertNotNull(result); - assertEquals(5, result.getTotal()); - assertEquals(2, result.getItems().size()); - assertTrue(result.getHasMore()); - assertEquals(Utils.TEST_LOG_ID, result.getLogID()); - assertEquals("workspace1", result.getItems().get(0).getId()); - assertEquals("工作空间1", result.getItems().get(0).getName()); - } - - @Test - void testListWorkspacesLastPage() throws Exception { - // 准备测试数据 - 最后一页 - int pageNum = 2; - int pageSize = 2; - ListWorkspaceReq req = ListWorkspaceReq.builder() - .pageNum(pageNum) - .pageSize(pageSize) - .build(); - - // 准备模拟响应数据 - 只有一条数据的最后一页 - List workspaces = Arrays.asList( - Workspace.builder().id("workspace3").name("工作空间3").build() - ); - - ListWorkspaceResp respData = ListWorkspaceResp.builder() - .workspaces(workspaces) - .totalCount(3) - .build(); - - BaseResponse baseResponse = BaseResponse.builder() - .code(0) - .msg("success") - .logID(Utils.TEST_LOG_ID) - .data(respData) - .build(); - - // 创建 mock Call 对象 - Call> call = mock(Call.class); - when(workspaceAPI.list(any(), any(), any())) - .thenReturn(call); - when(call.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); - - // 执行测试 - PageResp result = workspaceService.list(req); - - // 验证结果 - assertNotNull(result); - assertEquals(3, result.getTotal()); - assertEquals(1, result.getItems().size()); - assertFalse(result.getHasMore()); - } - - @Test - void testListWorkspacesWithNullRequest() { - // 验证空请求异常 - assertThrows(IllegalArgumentException.class, () -> { - workspaceService.list(null); + @Mock private WorkspaceAPI workspaceAPI; + + private WorkspaceService workspaceService; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + workspaceService = new WorkspaceService(workspaceAPI); + } + + @Test + void testListWorkspaces() throws Exception { + // 准备测试数据 + int pageNum = 1; + int pageSize = 2; + ListWorkspaceReq req = ListWorkspaceReq.builder().pageNum(pageNum).pageSize(pageSize).build(); + + // 准备模拟响应数据 + List workspaces = + Arrays.asList( + Workspace.builder().id("workspace1").name("工作空间1").build(), + Workspace.builder().id("workspace2").name("工作空间2").build()); + + ListWorkspaceResp respData = + ListWorkspaceResp.builder() + .workspaces(workspaces) + .totalCount(5) // 总共5条数据 + .build(); + + BaseResponse baseResponse = + BaseResponse.builder() + .code(0) + .msg("success") + .logID(Utils.TEST_LOG_ID) + .data(respData) + .build(); + + // 创建 mock Call 对象 + Call> call = mock(Call.class); + when(workspaceAPI.list(eq(pageNum), eq(pageSize), any(ListWorkspaceReq.class))) + .thenReturn(call); + when(call.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); + + // 执行测试 + PageResp result = workspaceService.list(req); + + // 验证结果 + assertNotNull(result); + assertEquals(5, result.getTotal()); + assertEquals(2, result.getItems().size()); + assertTrue(result.getHasMore()); + assertEquals(Utils.TEST_LOG_ID, result.getLogID()); + assertEquals("workspace1", result.getItems().get(0).getId()); + assertEquals("工作空间1", result.getItems().get(0).getName()); + } + + @Test + void testListWorkspacesLastPage() throws Exception { + // 准备测试数据 - 最后一页 + int pageNum = 2; + int pageSize = 2; + ListWorkspaceReq req = ListWorkspaceReq.builder().pageNum(pageNum).pageSize(pageSize).build(); + + // 准备模拟响应数据 - 只有一条数据的最后一页 + List workspaces = + Arrays.asList(Workspace.builder().id("workspace3").name("工作空间3").build()); + + ListWorkspaceResp respData = + ListWorkspaceResp.builder().workspaces(workspaces).totalCount(3).build(); + + BaseResponse baseResponse = + BaseResponse.builder() + .code(0) + .msg("success") + .logID(Utils.TEST_LOG_ID) + .data(respData) + .build(); + + // 创建 mock Call 对象 + Call> call = mock(Call.class); + when(workspaceAPI.list(any(), any(), any())).thenReturn(call); + when(call.execute()).thenReturn(Response.success(baseResponse, Utils.getCommonHeader())); + + // 执行测试 + PageResp result = workspaceService.list(req); + + // 验证结果 + assertNotNull(result); + assertEquals(3, result.getTotal()); + assertEquals(1, result.getItems().size()); + assertFalse(result.getHasMore()); + } + + @Test + void testListWorkspacesWithNullRequest() { + // 验证空请求异常 + assertThrows( + IllegalArgumentException.class, + () -> { + workspaceService.list(null); }); - } - - -} \ No newline at end of file + } +} diff --git a/api/src/test/java/com/coze/openapi/utils/Utils.java b/api/src/test/java/com/coze/openapi/utils/Utils.java index 688ad12e..ba3ad8b6 100644 --- a/api/src/test/java/com/coze/openapi/utils/Utils.java +++ b/api/src/test/java/com/coze/openapi/utils/Utils.java @@ -1,18 +1,22 @@ +/* (C)2024 */ package com.coze.openapi.utils; -import okhttp3.Headers; - import java.util.HashMap; +import okhttp3.Headers; + public class Utils { - public static final String LOG_HEADER = "x-tt-logid"; - public static final String TEST_LOG_ID = "test-log-id"; - private static final Headers commonHeader = Headers.of( - new HashMap() {{ - put(LOG_HEADER, TEST_LOG_ID); - }}); + public static final String LOG_HEADER = "x-tt-logid"; + public static final String TEST_LOG_ID = "test-log-id"; + private static final Headers commonHeader = + Headers.of( + new HashMap() { + { + put(LOG_HEADER, TEST_LOG_ID); + } + }); - public static Headers getCommonHeader(){ - return commonHeader; - } + public static Headers getCommonHeader() { + return commonHeader; + } } diff --git a/build.gradle b/build.gradle index 7988bbd8..fbf43cf9 100644 --- a/build.gradle +++ b/build.gradle @@ -11,6 +11,7 @@ allprojects { repositories { mavenCentral() + gradlePluginPortal() } } @@ -36,7 +37,7 @@ subprojects { spotless { java { removeUnusedImports() - googleJavaFormat('1.15.0') // 指定一个兼容 Java 8 的版本 + googleJavaFormat('1.7') endWithNewline() trimTrailingWhitespace() importOrder('java', 'javax', 'org', 'com', '') diff --git a/example/src/main/java/example/audio/room/AudioRoomsCreateExample.java b/example/src/main/java/example/audio/room/AudioRoomsCreateExample.java index b507abfa..38ddd96b 100644 --- a/example/src/main/java/example/audio/room/AudioRoomsCreateExample.java +++ b/example/src/main/java/example/audio/room/AudioRoomsCreateExample.java @@ -1,30 +1,29 @@ +/* (C)2024 */ package example.audio.room; import com.coze.openapi.client.audio.rooms.CreateRoomReq; import com.coze.openapi.client.audio.rooms.CreateRoomResp; -import com.coze.openapi.service.service.CozeAPI; import com.coze.openapi.service.auth.TokenAuth; +import com.coze.openapi.service.service.CozeAPI; public class AudioRoomsCreateExample { - public static void main(String[] args) { - String token = System.getenv("COZE_API_TOKEN"); - TokenAuth authCli = new TokenAuth(token); - CozeAPI coze = new CozeAPI.Builder() - .baseURL(System.getenv("COZE_API_BASE")) - .auth(authCli) - .readTimeout(10000) - .build(); - String botID = System.getenv("COZE_BOT_ID"); - String voiceID = System.getenv("COZE_VOICE_ID"); + public static void main(String[] args) { + String token = System.getenv("COZE_API_TOKEN"); + TokenAuth authCli = new TokenAuth(token); + CozeAPI coze = + new CozeAPI.Builder() + .baseURL(System.getenv("COZE_API_BASE")) + .auth(authCli) + .readTimeout(10000) + .build(); + String botID = System.getenv("COZE_BOT_ID"); + String voiceID = System.getenv("COZE_VOICE_ID"); - CreateRoomReq req = CreateRoomReq.builder() - .botID(botID) - .voiceID(voiceID) - .build(); - CreateRoomResp resp = coze.audio().rooms().create(req); - System.out.println(resp); - System.out.println(resp.getRoomID()); - System.out.println(resp.getLogID()); - } -} \ No newline at end of file + CreateRoomReq req = CreateRoomReq.builder().botID(botID).voiceID(voiceID).build(); + CreateRoomResp resp = coze.audio().rooms().create(req); + System.out.println(resp); + System.out.println(resp.getRoomID()); + System.out.println(resp.getLogID()); + } +} diff --git a/example/src/main/java/example/audio/speech/SpeechCreateExample.java b/example/src/main/java/example/audio/speech/SpeechCreateExample.java index 38440447..0d0fd218 100644 --- a/example/src/main/java/example/audio/speech/SpeechCreateExample.java +++ b/example/src/main/java/example/audio/speech/SpeechCreateExample.java @@ -1,37 +1,37 @@ +/* (C)2024 */ package example.audio.speech; +import java.io.IOException; + import com.coze.openapi.client.audio.speech.CreateSpeechReq; import com.coze.openapi.client.audio.speech.CreateSpeechResp; -import com.coze.openapi.service.service.CozeAPI; import com.coze.openapi.service.auth.TokenAuth; - -import java.io.IOException; +import com.coze.openapi.service.service.CozeAPI; public class SpeechCreateExample { - public static void main(String[] args) { - String token = System.getenv("COZE_API_TOKEN"); - TokenAuth authCli = new TokenAuth(token); - CozeAPI coze = new CozeAPI.Builder() - .baseURL(System.getenv("COZE_API_BASE")) - .auth(authCli) - .readTimeout(10000) - .build();; - String saveFilePath = System.getenv("SAVE_FILE_PATH"); - String voiceID = System.getenv("COZE_VOICE_ID"); - String content = "快来试一试吧"; + public static void main(String[] args) { + String token = System.getenv("COZE_API_TOKEN"); + TokenAuth authCli = new TokenAuth(token); + CozeAPI coze = + new CozeAPI.Builder() + .baseURL(System.getenv("COZE_API_BASE")) + .auth(authCli) + .readTimeout(10000) + .build(); + ; + String saveFilePath = System.getenv("SAVE_FILE_PATH"); + String voiceID = System.getenv("COZE_VOICE_ID"); + String content = "快来试一试吧"; - CreateSpeechReq req = CreateSpeechReq.builder() - .input(content) - .voiceID(voiceID) - .build(); + CreateSpeechReq req = CreateSpeechReq.builder().input(content).voiceID(voiceID).build(); - CreateSpeechResp resp = coze.audio().speech().create(req); - System.out.println(resp); - try { - resp.writeToFile(saveFilePath); - } catch (IOException e) { - e.printStackTrace(); - } + CreateSpeechResp resp = coze.audio().speech().create(req); + System.out.println(resp); + try { + resp.writeToFile(saveFilePath); + } catch (IOException e) { + e.printStackTrace(); } -} \ No newline at end of file + } +} diff --git a/example/src/main/java/example/audio/voice/VoiceCloneExample.java b/example/src/main/java/example/audio/voice/VoiceCloneExample.java index dae8de25..5cd566e9 100644 --- a/example/src/main/java/example/audio/voice/VoiceCloneExample.java +++ b/example/src/main/java/example/audio/voice/VoiceCloneExample.java @@ -1,30 +1,33 @@ +/* (C)2024 */ package example.audio.voice; +import com.coze.openapi.client.audio.common.AudioFormat; import com.coze.openapi.client.audio.voices.CloneVoiceReq; import com.coze.openapi.client.audio.voices.CloneVoiceResp; -import com.coze.openapi.client.audio.common.AudioFormat; -import com.coze.openapi.service.service.CozeAPI; import com.coze.openapi.service.auth.TokenAuth; +import com.coze.openapi.service.service.CozeAPI; public class VoiceCloneExample { - public static void main(String[] args) { - String token = System.getenv("COZE_API_TOKEN"); - TokenAuth authCli = new TokenAuth(token); - CozeAPI coze = new CozeAPI.Builder() - .baseURL(System.getenv("COZE_API_BASE")) - .auth(authCli) - .readTimeout(10000) - .connectTimeout(10000) - .build(); - String voiceFilePath = System.getenv("VOICE_FILE_PATH"); + public static void main(String[] args) { + String token = System.getenv("COZE_API_TOKEN"); + TokenAuth authCli = new TokenAuth(token); + CozeAPI coze = + new CozeAPI.Builder() + .baseURL(System.getenv("COZE_API_BASE")) + .auth(authCli) + .readTimeout(10000) + .connectTimeout(10000) + .build(); + String voiceFilePath = System.getenv("VOICE_FILE_PATH"); - CloneVoiceReq req = CloneVoiceReq.builder() - .filePath(voiceFilePath) - .voiceName("your voice name") - .audioFormat(AudioFormat.M4A) - .build(); - CloneVoiceResp resp = coze.audio().voices().clone(req); - System.out.println(resp); - } -} \ No newline at end of file + CloneVoiceReq req = + CloneVoiceReq.builder() + .filePath(voiceFilePath) + .voiceName("your voice name") + .audioFormat(AudioFormat.M4A) + .build(); + CloneVoiceResp resp = coze.audio().voices().clone(req); + System.out.println(resp); + } +} diff --git a/example/src/main/java/example/audio/voice/VoiceListExample.java b/example/src/main/java/example/audio/voice/VoiceListExample.java index ad1d0804..8a430e55 100644 --- a/example/src/main/java/example/audio/voice/VoiceListExample.java +++ b/example/src/main/java/example/audio/voice/VoiceListExample.java @@ -1,30 +1,32 @@ +/* (C)2024 */ package example.audio.voice; +import java.util.Iterator; + import com.coze.openapi.client.audio.voices.ListVoiceReq; import com.coze.openapi.client.audio.voices.model.Voice; import com.coze.openapi.client.common.pagination.PageResp; -import com.coze.openapi.service.service.CozeAPI; import com.coze.openapi.service.auth.TokenAuth; - -import java.util.Iterator; +import com.coze.openapi.service.service.CozeAPI; public class VoiceListExample { - public static void main(String[] args) { - String token = System.getenv("COZE_API_TOKEN"); - TokenAuth authCli = new TokenAuth(token); - CozeAPI coze = new CozeAPI.Builder() - .baseURL(System.getenv("COZE_API_BASE")) - .auth(authCli) - .readTimeout(10000) - .connectTimeout(10000) - .build(); + public static void main(String[] args) { + String token = System.getenv("COZE_API_TOKEN"); + TokenAuth authCli = new TokenAuth(token); + CozeAPI coze = + new CozeAPI.Builder() + .baseURL(System.getenv("COZE_API_BASE")) + .auth(authCli) + .readTimeout(10000) + .connectTimeout(10000) + .build(); - PageResp resp = coze.audio().voices().list(ListVoiceReq.builder().pageSize(10).build()); - Iterator iterator = resp.getIterator(); - while (iterator.hasNext()) { - Voice voice = iterator.next(); - System.out.println(voice); - } + PageResp resp = coze.audio().voices().list(ListVoiceReq.builder().pageSize(10).build()); + Iterator iterator = resp.getIterator(); + while (iterator.hasNext()) { + Voice voice = iterator.next(); + System.out.println(voice); } -} \ No newline at end of file + } +} diff --git a/example/src/main/java/example/auth/DeviceOAuthExample.java b/example/src/main/java/example/auth/DeviceOAuthExample.java index 1eef5f82..bc1cecbc 100644 --- a/example/src/main/java/example/auth/DeviceOAuthExample.java +++ b/example/src/main/java/example/auth/DeviceOAuthExample.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package example.auth; import com.coze.openapi.client.auth.DeviceAuthResp; @@ -22,93 +23,89 @@ * */ public class DeviceOAuthExample { - public static void main(String[] args) { - String clientID = System.getenv("COZE_DEVICE_OAUTH_CLIENT_ID"); - - /* - * The default access is api.coze.com, but if you need to access api.coze.cn, - * please use base_url to configure the api endpoint to access - */ - String cozeAPIBase = System.getenv("COZE_API_BASE"); - if(cozeAPIBase==null|| cozeAPIBase.isEmpty()){ - cozeAPIBase = Consts.COZE_COM_BASE_URL; - } - - DeviceOAuthClient oauth = new DeviceOAuthClient.DeviceOAuthBuilder() - .clientID(clientID) - .baseURL(cozeAPIBase) - .build(); - - /* - In the device oauth authorization process, developers need to first call the interface - of Coze to generate the device code to obtain the user_code and device_code. Then generate - the authorization link through the user_code, guide the user to open the link, fill in the - user_code, and consent to the authorization. Developers need to call the interface of Coze - to generate the token through the device_code. When the user has not authorized or rejected - the authorization, the interface will throw an error and return a specific error code. - After the user consents to the authorization, the interface will succeed and return the - access_token. - - - First, make a call to obtain 'getDeviceCode' - */ - - DeviceAuthResp codeResp = oauth.getDeviceCode(); - System.out.println(codeResp); - - /* - * The space permissions for which the Access Token is granted can be specified. As following codes: - * DeviceAuthResp wCodeResp = oauth.getDeviceCode("workspaceID"); - * */ + public static void main(String[] args) { + String clientID = System.getenv("COZE_DEVICE_OAUTH_CLIENT_ID"); + /* + * The default access is api.coze.com, but if you need to access api.coze.cn, + * please use base_url to configure the api endpoint to access + */ + String cozeAPIBase = System.getenv("COZE_API_BASE"); + if (cozeAPIBase == null || cozeAPIBase.isEmpty()) { + cozeAPIBase = Consts.COZE_COM_BASE_URL; + } + DeviceOAuthClient oauth = + new DeviceOAuthClient.DeviceOAuthBuilder().clientID(clientID).baseURL(cozeAPIBase).build(); + + /* + In the device oauth authorization process, developers need to first call the interface + of Coze to generate the device code to obtain the user_code and device_code. Then generate + the authorization link through the user_code, guide the user to open the link, fill in the + user_code, and consent to the authorization. Developers need to call the interface of Coze + to generate the token through the device_code. When the user has not authorized or rejected + the authorization, the interface will throw an error and return a specific error code. + After the user consents to the authorization, the interface will succeed and return the + access_token. + + + First, make a call to obtain 'getDeviceCode' + */ + + DeviceAuthResp codeResp = oauth.getDeviceCode(); + System.out.println(codeResp); + + /* + * The space permissions for which the Access Token is granted can be specified. As following codes: + * DeviceAuthResp wCodeResp = oauth.getDeviceCode("workspaceID"); + * */ + + /* + The returned device_code contains an authorization link. Developers need to guide users + to open up this link. + open codeResp.getVerificationUri + * */ + + System.out.println("Please open url: " + codeResp.getVerificationURL()); + + /* + The developers then need to use the device_code to poll Coze's interface to obtain the token. + The SDK has encapsulated this part of the code in and handled the different returned error + codes. The developers only need to invoke getAccessToken. + * */ + try { + /* + * if the developers set poll as true, the sdk will automatically handle pending and slow down exception + * */ + OAuthToken resp = oauth.getAccessToken(codeResp.getDeviceCode(), true); + System.out.println(resp); + + // use the access token to init Coze client + CozeAPI coze = + new CozeAPI.Builder() + .auth(new TokenAuth(resp.getAccessToken())) + .baseURL(cozeAPIBase) + .build(); + // When the token expires, you can also refresh and re-obtain the token + resp = oauth.refreshToken(resp.getRefreshToken()); + } catch (CozeAuthException e) { + if (AuthErrorCode.ACCESS_DENIED.equals(e.getCode())) { /* - The returned device_code contains an authorization link. Developers need to guide users - to open up this link. - open codeResp.getVerificationUri + The user rejected the authorization. + Developers need to guide the user to open the authorization link again. * */ - - System.out.println("Please open url: " + codeResp.getVerificationURL()); - - - + System.out.println("access denied"); + } else if (AuthErrorCode.EXPIRED_TOKEN.equals(e.getCode())) { /* - The developers then need to use the device_code to poll Coze's interface to obtain the token. - The SDK has encapsulated this part of the code in and handled the different returned error - codes. The developers only need to invoke getAccessToken. + The token has expired. Developers need to guide the user to open + the authorization link again. * */ - try { - /* - * if the developers set poll as true, the sdk will automatically handle pending and slow down exception - * */ - OAuthToken resp = oauth.getAccessToken(codeResp.getDeviceCode(), true); - System.out.println(resp); - - - // use the access token to init Coze client - CozeAPI coze = new CozeAPI.Builder().auth(new TokenAuth(resp.getAccessToken())).baseURL(cozeAPIBase).build(); - // When the token expires, you can also refresh and re-obtain the token - resp = oauth.refreshToken(resp.getRefreshToken()); - } catch (CozeAuthException e) { - if (AuthErrorCode.ACCESS_DENIED.equals(e.getCode())) { - /* - The user rejected the authorization. - Developers need to guide the user to open the authorization link again. - * */ - System.out.println("access denied"); - }else if (AuthErrorCode.EXPIRED_TOKEN.equals(e.getCode())){ - /* - The token has expired. Developers need to guide the user to open - the authorization link again. - * */ - System.out.println("expired token"); - } else { - e.printStackTrace(); - } - } catch (Exception e) { - e.printStackTrace(); - } - - + System.out.println("expired token"); + } else { + e.printStackTrace(); + } + } catch (Exception e) { + e.printStackTrace(); } -} \ No newline at end of file + } +} diff --git a/example/src/main/java/example/auth/HandlerExceptionExample.java b/example/src/main/java/example/auth/HandlerExceptionExample.java index 14d09c52..fc4f4a6d 100644 --- a/example/src/main/java/example/auth/HandlerExceptionExample.java +++ b/example/src/main/java/example/auth/HandlerExceptionExample.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package example.auth; import com.coze.openapi.client.auth.OAuthToken; @@ -5,72 +6,73 @@ import com.coze.openapi.client.exception.CozeAuthException; import com.coze.openapi.service.auth.WebOAuthClient; import com.coze.openapi.service.config.Consts; + /* * Using web oauth as example, show how to handle the Auth exception - * -*/ + * + */ public class HandlerExceptionExample { - public static void main(String[] args) { - String redirectURI = System.getenv("COZE_WEB_OAUTH_REDIRECT_URI"); - String clientSecret = System.getenv("COZE_WEB_OAUTH_CLIENT_SECRET"); - String clientID = System.getenv("COZE_WEB_OAUTH_CLIENT_ID"); - - /* - * The default access is api.coze.com, but if you need to access api.coze.cn, - * please use base_url to configure the api endpoint to access - */ - String cozeAPIBase = System.getenv("COZE_API_BASE"); - if(cozeAPIBase==null|| cozeAPIBase.isEmpty()){ - cozeAPIBase = Consts.COZE_COM_BASE_URL; - } + public static void main(String[] args) { + String redirectURI = System.getenv("COZE_WEB_OAUTH_REDIRECT_URI"); + String clientSecret = System.getenv("COZE_WEB_OAUTH_CLIENT_SECRET"); + String clientID = System.getenv("COZE_WEB_OAUTH_CLIENT_ID"); + /* + * The default access is api.coze.com, but if you need to access api.coze.cn, + * please use base_url to configure the api endpoint to access + */ + String cozeAPIBase = System.getenv("COZE_API_BASE"); + if (cozeAPIBase == null || cozeAPIBase.isEmpty()) { + cozeAPIBase = Consts.COZE_COM_BASE_URL; + } - /* - The sdk offers the WebOAuthClient class to establish an authorization for Web OAuth. - Firstly, it is required to initialize the WebOAuthApp with the client ID and client secret. - */ - WebOAuthClient oauth = new WebOAuthClient.WebOAuthBuilder() - .clientID(clientID) - .clientSecret(clientSecret) - .baseURL(cozeAPIBase) - .build(); + /* + The sdk offers the WebOAuthClient class to establish an authorization for Web OAuth. + Firstly, it is required to initialize the WebOAuthApp with the client ID and client secret. + */ + WebOAuthClient oauth = + new WebOAuthClient.WebOAuthBuilder() + .clientID(clientID) + .clientSecret(clientSecret) + .baseURL(cozeAPIBase) + .build(); - // Generate the authorization link and direct the user to open it. - String oauthURL = oauth.getOAuthURL(redirectURI, null); - System.out.println(oauthURL); + // Generate the authorization link and direct the user to open it. + String oauthURL = oauth.getOAuthURL(redirectURI, null); + System.out.println(oauthURL); - /* - * The space permissions for which the Access Token is granted can be specified. As following codes: - * oauthURL = oauth.getOAuthURL(redirectURI, null, "workspaceID"); - * */ + /* + * The space permissions for which the Access Token is granted can be specified. As following codes: + * oauthURL = oauth.getOAuthURL(redirectURI, null, "workspaceID"); + * */ - /* - After the user clicks the authorization consent button, the coze web page will redirect - to the redirect address configured in the authorization link and carry the authorization - code and state parameters in the address via the query string. + /* + After the user clicks the authorization consent button, the coze web page will redirect + to the redirect address configured in the authorization link and carry the authorization + code and state parameters in the address via the query string. - Get from the query of the redirect interface: query.get('code') - * */ - String code = "mock code"; + Get from the query of the redirect interface: query.get('code') + * */ + String code = "mock code"; - /* - After obtaining the code after redirection, the interface to exchange the code for a - token can be invoked to generate the coze access_token of the authorized user. - * */ - try{ - OAuthToken resp = oauth.getAccessToken(code, redirectURI); - System.out.println(resp); - } catch (CozeAuthException e) { - /* - * The SDK has enumerated existing authentication error codes - * You need to handle the exception and guide users to re-authenticate - * For different oauth type, the error code may be different, you should read document to get more information - */ - if (AuthErrorCode.AUTHORIZATION_PENDING.equals(e.getCode())){ - // The authorization code is invalid or expired, please re-authorize - } + /* + After obtaining the code after redirection, the interface to exchange the code for a + token can be invoked to generate the coze access_token of the authorized user. + * */ + try { + OAuthToken resp = oauth.getAccessToken(code, redirectURI); + System.out.println(resp); + } catch (CozeAuthException e) { + /* + * The SDK has enumerated existing authentication error codes + * You need to handle the exception and guide users to re-authenticate + * For different oauth type, the error code may be different, you should read document to get more information + */ + if (AuthErrorCode.AUTHORIZATION_PENDING.equals(e.getCode())) { + // The authorization code is invalid or expired, please re-authorize + } - System.out.println(e.getMessage()); - } + System.out.println(e.getMessage()); } + } } diff --git a/example/src/main/java/example/auth/JWTOAuthExample.java b/example/src/main/java/example/auth/JWTOAuthExample.java index f4979641..1885258d 100644 --- a/example/src/main/java/example/auth/JWTOAuthExample.java +++ b/example/src/main/java/example/auth/JWTOAuthExample.java @@ -1,14 +1,15 @@ +/* (C)2024 */ package example.auth; -import com.coze.openapi.client.auth.OAuthToken; -import com.coze.openapi.service.auth.JWTOAuthClient; -import com.coze.openapi.service.auth.JWTOAuth; -import com.coze.openapi.service.service.CozeAPI; - import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; -import java.nio.charset.StandardCharsets; + +import com.coze.openapi.client.auth.OAuthToken; +import com.coze.openapi.service.auth.JWTOAuth; +import com.coze.openapi.service.auth.JWTOAuthClient; +import com.coze.openapi.service.service.CozeAPI; /* This example is about how to use the service jwt oauth process to acquire user authorization. @@ -24,59 +25,61 @@ * */ public class JWTOAuthExample { - public static void main(String[] args) { - - // The default access is api.coze.com, but if you need to access api.coze.cn, - // please use base_url to configure the api endpoint to access - String cozeAPIBase = System.getenv("COZE_API_BASE"); - if(cozeAPIBase==null|| cozeAPIBase.isEmpty()){ - cozeAPIBase = "api.coze.cn"; - } - String jwtOauthClientID = System.getenv("COZE_JWT_OAUTH_CLIENT_ID"); - String jwtOauthPrivateKey = System.getenv("COZE_JWT_OAUTH_PRIVATE_KEY"); - String jwtOauthPrivateKeyFilePath = System.getenv("COZE_JWT_OAUTH_PRIVATE_KEY_FILE_PATH"); - String jwtOauthPublicKeyID = System.getenv("COZE_JWT_OAUTH_PUBLIC_KEY_ID"); + public static void main(String[] args) { + // The default access is api.coze.com, but if you need to access api.coze.cn, + // please use base_url to configure the api endpoint to access + String cozeAPIBase = System.getenv("COZE_API_BASE"); + if (cozeAPIBase == null || cozeAPIBase.isEmpty()) { + cozeAPIBase = "api.coze.cn"; + } + String jwtOauthClientID = System.getenv("COZE_JWT_OAUTH_CLIENT_ID"); + String jwtOauthPrivateKey = System.getenv("COZE_JWT_OAUTH_PRIVATE_KEY"); + String jwtOauthPrivateKeyFilePath = System.getenv("COZE_JWT_OAUTH_PRIVATE_KEY_FILE_PATH"); + String jwtOauthPublicKeyID = System.getenv("COZE_JWT_OAUTH_PUBLIC_KEY_ID"); - JWTOAuthClient oauth = null; - try { - jwtOauthPrivateKey = new String(Files.readAllBytes(Paths.get(jwtOauthPrivateKeyFilePath)), StandardCharsets.UTF_8); - } catch (IOException e) { - e.printStackTrace(); - } + JWTOAuthClient oauth = null; + try { + jwtOauthPrivateKey = + new String( + Files.readAllBytes(Paths.get(jwtOauthPrivateKeyFilePath)), StandardCharsets.UTF_8); + } catch (IOException e) { + e.printStackTrace(); + } - /* - The jwt oauth type requires using private to be able to issue a jwt token, and through - the jwt token, apply for an access_token from the coze service. The sdk encapsulates - this procedure, and only needs to use get_access_token to obtain the access_token under - the jwt oauth process. - Generate the authorization token - The default ttl is 900s, and developers can customize the expiration time, which can be - set up to 24 hours at most. - * */ - try { - oauth = new JWTOAuthClient.JWTOAuthBuilder() - .clientID(jwtOauthClientID) - .privateKey(jwtOauthPrivateKey) - .publicKey(jwtOauthPublicKeyID) - .baseURL(cozeAPIBase) - .build(); - } catch (Exception e) { - e.printStackTrace(); - return; - } + /* + The jwt oauth type requires using private to be able to issue a jwt token, and through + the jwt token, apply for an access_token from the coze service. The sdk encapsulates + this procedure, and only needs to use get_access_token to obtain the access_token under + the jwt oauth process. + Generate the authorization token + The default ttl is 900s, and developers can customize the expiration time, which can be + set up to 24 hours at most. + * */ + try { + oauth = + new JWTOAuthClient.JWTOAuthBuilder() + .clientID(jwtOauthClientID) + .privateKey(jwtOauthPrivateKey) + .publicKey(jwtOauthPublicKeyID) + .baseURL(cozeAPIBase) + .build(); + } catch (Exception e) { + e.printStackTrace(); + return; + } - try { - OAuthToken resp = oauth.getAccessToken(); - System.out.println(resp); - } catch (Exception e) { - e.printStackTrace(); - } - /* - The jwt oauth process does not support refreshing tokens. When the token expires, - just directly call get_access_token to generate a new token. - * */ - CozeAPI coze = new CozeAPI.Builder().auth(new JWTOAuth(oauth)).baseURL(cozeAPIBase).build(); - // you can also specify the scope and session for it + try { + OAuthToken resp = oauth.getAccessToken(); + System.out.println(resp); + } catch (Exception e) { + e.printStackTrace(); } -} \ No newline at end of file + /* + The jwt oauth process does not support refreshing tokens. When the token expires, + just directly call get_access_token to generate a new token. + * */ + CozeAPI coze = new CozeAPI.Builder().auth(new JWTOAuth(oauth)).baseURL(cozeAPIBase).build(); + // you can also specify the scope and session for it + } +} diff --git a/example/src/main/java/example/auth/PKCEOAuthExample.java b/example/src/main/java/example/auth/PKCEOAuthExample.java index cad1299e..4154e50d 100644 --- a/example/src/main/java/example/auth/PKCEOAuthExample.java +++ b/example/src/main/java/example/auth/PKCEOAuthExample.java @@ -1,7 +1,8 @@ +/* (C)2024 */ package example.auth; -import com.coze.openapi.client.auth.OAuthToken; import com.coze.openapi.client.auth.GetPKCEAuthURLResp; +import com.coze.openapi.client.auth.OAuthToken; import com.coze.openapi.service.auth.PKCEOAuthClient; import com.coze.openapi.service.auth.TokenAuth; import com.coze.openapi.service.config.Consts; @@ -24,58 +25,61 @@ * */ public class PKCEOAuthExample { - public static void main(String[] args) { - String redirectURI = System.getenv("COZE_PKCE_OAUTH_REDIRECT_URI"); - String clientID = System.getenv("COZE_PKCE_OAUTH_CLIENT_ID"); + public static void main(String[] args) { + String redirectURI = System.getenv("COZE_PKCE_OAUTH_REDIRECT_URI"); + String clientID = System.getenv("COZE_PKCE_OAUTH_CLIENT_ID"); - /* - * The default access is api.coze.com, but if you need to access api.coze.cn, - * please use base_url to configure the api endpoint to access - */ - String cozeAPIBase = System.getenv("COZE_API_BASE"); - if(cozeAPIBase==null|| cozeAPIBase.isEmpty()){ - cozeAPIBase = Consts.COZE_COM_BASE_URL; - } + /* + * The default access is api.coze.com, but if you need to access api.coze.cn, + * please use base_url to configure the api endpoint to access + */ + String cozeAPIBase = System.getenv("COZE_API_BASE"); + if (cozeAPIBase == null || cozeAPIBase.isEmpty()) { + cozeAPIBase = Consts.COZE_COM_BASE_URL; + } - PKCEOAuthClient oauth = new PKCEOAuthClient.PKCEOAuthBuilder() - .clientID(clientID) - .baseURL(cozeAPIBase) - .build(); + PKCEOAuthClient oauth = + new PKCEOAuthClient.PKCEOAuthBuilder().clientID(clientID).baseURL(cozeAPIBase).build(); - /* - In the SDK, we have wrapped up the code_challenge process of PKCE. Developers only need - to select the code_challenge_method. - * */ - GetPKCEAuthURLResp oauthURL = oauth.genOAuthURL(redirectURI, "state", PKCEOAuthClient.CodeChallengeMethod.S256); - System.out.println(oauthURL); + /* + In the SDK, we have wrapped up the code_challenge process of PKCE. Developers only need + to select the code_challenge_method. + * */ + GetPKCEAuthURLResp oauthURL = + oauth.genOAuthURL(redirectURI, "state", PKCEOAuthClient.CodeChallengeMethod.S256); + System.out.println(oauthURL); - /* - * The space permissions for which the Access Token is granted can be specified. As following codes: - * */ - oauthURL = oauth.genOAuthURL(redirectURI, "state", PKCEOAuthClient.CodeChallengeMethod.S256, "workspaceID"); - System.out.println(oauthURL); - - /* - After the user clicks the authorization consent button, the coze web page will redirect - to the redirect address configured in the authorization link and carry the authorization - code and state parameters in the address via the query string. + /* + * The space permissions for which the Access Token is granted can be specified. As following codes: + * oauthURL = oauth.genOAuthURL(redirectURI, "state", PKCEOAuthClient.CodeChallengeMethod.S256, "workspaceID"); + * System.out.println(oauthURL); + * */ - Get from the query of the redirect interface: query.get('code') - * */ - String code = "mock code"; + /* + After the user clicks the authorization consent button, the coze web page will redirect + to the redirect address configured in the authorization link and carry the authorization + code and state parameters in the address via the query string. - /* - After obtaining the code after redirection, the interface to exchange the code for a - token can be invoked to generate the coze access_token of the authorized user. - The developer should use code verifier returned by genOAuthURL() method - * */ - OAuthToken resp = oauth.getAccessToken(code, redirectURI, oauthURL.getCodeVerifier()); - System.out.println(resp); + Get from the query of the redirect interface: query.get('code') + * */ + String code = "mock code"; - // use the access token to init Coze client - CozeAPI coze = new CozeAPI.Builder().auth(new TokenAuth(resp.getAccessToken())).baseURL(cozeAPIBase).build(); - // When the token expires, you can also refresh and re-obtain the token - resp = oauth.refreshToken(resp.getRefreshToken()); - System.out.println(); - } -} \ No newline at end of file + /* + After obtaining the code after redirection, the interface to exchange the code for a + token can be invoked to generate the coze access_token of the authorized user. + The developer should use code verifier returned by genOAuthURL() method + * */ + OAuthToken resp = oauth.getAccessToken(code, redirectURI, oauthURL.getCodeVerifier()); + System.out.println(resp); + + // use the access token to init Coze client + CozeAPI coze = + new CozeAPI.Builder() + .auth(new TokenAuth(resp.getAccessToken())) + .baseURL(cozeAPIBase) + .build(); + // When the token expires, you can also refresh and re-obtain the token + resp = oauth.refreshToken(resp.getRefreshToken()); + System.out.println(); + } +} diff --git a/example/src/main/java/example/auth/PkceOauthExample.java b/example/src/main/java/example/auth/PkceOauthExample.java deleted file mode 100644 index b4c4bd07..00000000 --- a/example/src/main/java/example/auth/PkceOauthExample.java +++ /dev/null @@ -1,80 +0,0 @@ -package example.auth; - -import com.coze.openapi.client.auth.OAuthToken; -import com.coze.openapi.client.auth.GetPKCEAuthURLResp; -import com.coze.openapi.service.auth.PKCEOAuthClient; -import com.coze.openapi.service.auth.TokenAuth; -import com.coze.openapi.service.config.Consts; -import com.coze.openapi.service.service.CozeAPI; - -/* -How to effectuate OpenAPI authorization through the OAuth Proof Key for Code Exchange method. - -PKCE stands for Proof Key for Code Exchange, and it's an extension to the OAuth 2.0 authorization -code flow designed to enhance security for public clients, such as mobile and single-page -applications. - -Firstly, users need to access https://www.coze.com/open/oauth/apps. For the cn environment, -users need to access https://www.coze.cn/open/oauth/apps to create an OAuth App of the type -of Mobile/PC/Single-page application. -The specific creation process can be referred to in the document: -https://www.coze.com/docs/developer_guides/oauth_pkce. For the cn environment, it can be -accessed at https://www.coze.cn/docs/developer_guides/oauth_pkce. -After the creation is completed, the client ID can be obtained. -* */ -public class PKCEOAuthExample { - - public static void main(String[] args) { - String redirectURI = System.getenv("COZE_PKCE_OAUTH_REDIRECT_URI"); - String clientID = System.getenv("COZE_PKCE_OAUTH_CLIENT_ID"); - - /* - * The default access is api.coze.com, but if you need to access api.coze.cn, - * please use base_url to configure the api endpoint to access - */ - String cozeAPIBase = System.getenv("COZE_API_BASE"); - if(cozeAPIBase==null|| cozeAPIBase.isEmpty()){ - cozeAPIBase = Consts.COZE_COM_BASE_URL; - } - - PKCEOAuthClient oauth = new PKCEOAuthClient.PKCEOAuthBuilder() - .clientID(clientID) - .baseURL(cozeAPIBase) - .build(); - - /* - In the SDK, we have wrapped up the code_challenge process of PKCE. Developers only need - to select the code_challenge_method. - * */ - GetPKCEAuthURLResp oauthURL = oauth.genOAuthURL(redirectURI, "state", PKCEOAuthClient.CodeChallengeMethod.S256); - System.out.println(oauthURL); - - /* - * The space permissions for which the Access Token is granted can be specified. As following codes: - * oauthURL = oauth.genOAuthURL(redirectURI, "state", PKCEOAuthClient.CodeChallengeMethod.S256, "workspaceID"); - * */ - - /* - After the user clicks the authorization consent button, the coze web page will redirect - to the redirect address configured in the authorization link and carry the authorization - code and state parameters in the address via the query string. - - Get from the query of the redirect interface: query.get('code') - * */ - String code = "mock code"; - - /* - After obtaining the code after redirection, the interface to exchange the code for a - token can be invoked to generate the coze access_token of the authorized user. - The developer should use code verifier returned by genOAuthURL() method - * */ - OAuthToken resp = oauth.getAccessToken(code, redirectURI, oauthURL.getCodeVerifier()); - System.out.println(resp); - - // use the access token to init Coze client - CozeAPI coze = new CozeAPI.Builder().auth(new TokenAuth(resp.getAccessToken())).baseURL(cozeAPIBase).build(); - // When the token expires, you can also refresh and re-obtain the token - resp = oauth.refreshToken(resp.getRefreshToken()); - System.out.println(); - } -} \ No newline at end of file diff --git a/example/src/main/java/example/auth/TokenAuthExample.java b/example/src/main/java/example/auth/TokenAuthExample.java index 0964a977..55ddf6d2 100644 --- a/example/src/main/java/example/auth/TokenAuthExample.java +++ b/example/src/main/java/example/auth/TokenAuthExample.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package example.auth; import com.coze.openapi.service.auth.TokenAuth; @@ -15,29 +16,28 @@ secure environment to prevent this personal access token from being disclosed. */ public class TokenAuthExample { - public static void main(String[] args) { - String cozeAPIToken = System.getenv("COZE_API_TOKEN"); - - /* - * The default access is api.coze.com, but if you need to access api.coze.cn, - * please use base_url to configure the api endpoint to access - */ - String cozeAPIBase = System.getenv("COZE_API_BASE"); - if(cozeAPIBase==null|| cozeAPIBase.isEmpty()){ - cozeAPIBase = Consts.COZE_COM_BASE_URL; - } - - /* - * - * The Coze SDK offers the TokenAuth class for constructing an Auth class based on a fixed - * access token. Meanwhile, the Coze class enables the passing in of an Auth class to build - * a coze client. - * - * Therefore, you can utilize the following code to initialize a coze client. - * - * */ - CozeAPI coze = new CozeAPI.Builder().auth(new TokenAuth(cozeAPIToken)).baseURL(cozeAPIBase).build(); - + public static void main(String[] args) { + String cozeAPIToken = System.getenv("COZE_API_TOKEN"); + + /* + * The default access is api.coze.com, but if you need to access api.coze.cn, + * please use base_url to configure the api endpoint to access + */ + String cozeAPIBase = System.getenv("COZE_API_BASE"); + if (cozeAPIBase == null || cozeAPIBase.isEmpty()) { + cozeAPIBase = Consts.COZE_COM_BASE_URL; } + /* + * + * The Coze SDK offers the TokenAuth class for constructing an Auth class based on a fixed + * access token. Meanwhile, the Coze class enables the passing in of an Auth class to build + * a coze client. + * + * Therefore, you can utilize the following code to initialize a coze client. + * + * */ + CozeAPI coze = + new CozeAPI.Builder().auth(new TokenAuth(cozeAPIToken)).baseURL(cozeAPIBase).build(); + } } diff --git a/example/src/main/java/example/auth/WebOAuthExample.java b/example/src/main/java/example/auth/WebOAuthExample.java index 7c7d06e1..26381ba0 100644 --- a/example/src/main/java/example/auth/WebOAuthExample.java +++ b/example/src/main/java/example/auth/WebOAuthExample.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package example.auth; import com.coze.openapi.client.auth.OAuthToken; @@ -21,65 +22,69 @@ * */ public class WebOAuthExample { - public static void main(String[] args) { - String redirectURI = System.getenv("COZE_WEB_OAUTH_REDIRECT_URI"); - String clientSecret = System.getenv("COZE_WEB_OAUTH_CLIENT_SECRET"); - String clientID = System.getenv("COZE_WEB_OAUTH_CLIENT_ID"); - - /* - * The default access is api.coze.com, but if you need to access api.coze.cn, - * please use base_url to configure the api endpoint to access - */ - String cozeAPIBase = System.getenv("COZE_API_BASE"); - if(cozeAPIBase==null|| cozeAPIBase.isEmpty()){ - cozeAPIBase = Consts.COZE_COM_BASE_URL; - } + public static void main(String[] args) { + String redirectURI = System.getenv("COZE_WEB_OAUTH_REDIRECT_URI"); + String clientSecret = System.getenv("COZE_WEB_OAUTH_CLIENT_SECRET"); + String clientID = System.getenv("COZE_WEB_OAUTH_CLIENT_ID"); + /* + * The default access is api.coze.com, but if you need to access api.coze.cn, + * please use base_url to configure the api endpoint to access + */ + String cozeAPIBase = System.getenv("COZE_API_BASE"); + if (cozeAPIBase == null || cozeAPIBase.isEmpty()) { + cozeAPIBase = Consts.COZE_COM_BASE_URL; + } - /* - The sdk offers the WebOAuthClient class to establish an authorization for Web OAuth. - Firstly, it is required to initialize the WebOAuthApp with the client ID and client secret. - */ - WebOAuthClient oauth = new WebOAuthClient.WebOAuthBuilder() - .clientID(clientID) - .clientSecret(clientSecret) - .baseURL(cozeAPIBase) - .build(); + /* + The sdk offers the WebOAuthClient class to establish an authorization for Web OAuth. + Firstly, it is required to initialize the WebOAuthApp with the client ID and client secret. + */ + WebOAuthClient oauth = + new WebOAuthClient.WebOAuthBuilder() + .clientID(clientID) + .clientSecret(clientSecret) + .baseURL(cozeAPIBase) + .build(); - // Generate the authorization link and direct the user to open it. - String oauthURL = oauth.getOAuthURL(redirectURI, null); - System.out.println(oauthURL); + // Generate the authorization link and direct the user to open it. + String oauthURL = oauth.getOAuthURL(redirectURI, null); + System.out.println(oauthURL); - /* - * The space permissions for which the Access Token is granted can be specified. As following codes: - * */ - oauthURL = oauth.getOAuthURL(redirectURI, null, "workspaceID"); - System.out.println(oauthURL); + /* + * The space permissions for which the Access Token is granted can be specified. As following codes: + * */ + oauthURL = oauth.getOAuthURL(redirectURI, null, "workspaceID"); + System.out.println(oauthURL); - /* - After the user clicks the authorization consent button, the coze web page will redirect - to the redirect address configured in the authorization link and carry the authorization - code and state parameters in the address via the query string. + /* + After the user clicks the authorization consent button, the coze web page will redirect + to the redirect address configured in the authorization link and carry the authorization + code and state parameters in the address via the query string. - Get from the query of the redirect interface: query.get('code') - * */ - String code = "mock code"; + Get from the query of the redirect interface: query.get('code') + * */ + String code = "mock code"; - /* - After obtaining the code after redirection, the interface to exchange the code for a - token can be invoked to generate the coze access_token of the authorized user. - * */ - OAuthToken resp = oauth.getAccessToken(code, redirectURI); - System.out.println(resp); + /* + After obtaining the code after redirection, the interface to exchange the code for a + token can be invoked to generate the coze access_token of the authorized user. + * */ + OAuthToken resp = oauth.getAccessToken(code, redirectURI); + System.out.println(resp); - /* - * you can get request log by getLogID method - * */ - System.out.println(resp.getLogID()); + /* + * you can get request log by getLogID method + * */ + System.out.println(resp.getLogID()); - // use the access token to init Coze client - CozeAPI coze = new CozeAPI.Builder().auth(new TokenAuth(resp.getAccessToken())).baseURL(cozeAPIBase).build(); - // When the token expires, you can also refresh and re-obtain the token - resp = oauth.refreshToken(resp.getRefreshToken()); - } -} \ No newline at end of file + // use the access token to init Coze client + CozeAPI coze = + new CozeAPI.Builder() + .auth(new TokenAuth(resp.getAccessToken())) + .baseURL(cozeAPIBase) + .build(); + // When the token expires, you can also refresh and re-obtain the token + resp = oauth.refreshToken(resp.getRefreshToken()); + } +} diff --git a/example/src/main/java/example/bot/BotPublishExample.java b/example/src/main/java/example/bot/BotPublishExample.java index f6ce9c41..23366ed1 100644 --- a/example/src/main/java/example/bot/BotPublishExample.java +++ b/example/src/main/java/example/bot/BotPublishExample.java @@ -1,14 +1,15 @@ +/* (C)2024 */ package example.bot; +import java.util.Arrays; + import com.coze.openapi.client.bots.*; import com.coze.openapi.client.bots.model.BotOnboardingInfo; import com.coze.openapi.client.bots.model.BotPromptInfo; import com.coze.openapi.client.files.UploadFileReq; import com.coze.openapi.client.files.UploadFileResp; -import com.coze.openapi.service.service.CozeAPI; import com.coze.openapi.service.auth.TokenAuth; - -import java.util.Arrays; +import com.coze.openapi.service.service.CozeAPI; /* This example is for describing how to create a bot, update a bot and publish a bot to the API. @@ -16,83 +17,84 @@ * */ public class BotPublishExample { - public static void main(String[] args) { - // Get an access_token through personal access token or oauth. - String token = System.getenv("COZE_API_TOKEN"); - TokenAuth authCli = new TokenAuth(token); - - // Init the Coze client through the access_token. - CozeAPI coze = new CozeAPI.Builder() - .baseURL(System.getenv("COZE_API_BASE")) - .auth(authCli) - .readTimeout(10000) - .build();; + public static void main(String[] args) { + // Get an access_token through personal access token or oauth. + String token = System.getenv("COZE_API_TOKEN"); + TokenAuth authCli = new TokenAuth(token); - /* - * step one, create a bot - * */ - String workspaceID = System.getenv("WORKSPACE_ID"); + // Init the Coze client through the access_token. + CozeAPI coze = + new CozeAPI.Builder() + .baseURL(System.getenv("COZE_API_BASE")) + .auth(authCli) + .readTimeout(10000) + .build(); + ; - // set the prompt of your bot - BotPromptInfo promptInfo = new BotPromptInfo("your prompt"); + /* + * step one, create a bot + * */ + String workspaceID = System.getenv("WORKSPACE_ID"); - // set the onboarding info of your bot - BotOnboardingInfo onboardingInfo = BotOnboardingInfo.builder() - .prologue("the prologue of your bot") - .suggestedQuestions(Arrays.asList("question 1", "question 2")) - .build(); - // Call the upload file interface to get the avatar id. - String avatarPath = System.getenv("IMAGE_FILE_PATH"); - UploadFileResp avatarInfo = coze.files().upload(UploadFileReq.of(avatarPath)); - System.out.println(avatarInfo); + // set the prompt of your bot + BotPromptInfo promptInfo = new BotPromptInfo("your prompt"); - // build the request - CreateBotReq createReq = CreateBotReq.builder() - .spaceID(workspaceID) - .description("the description of your bot") - .name("the name of your bot") - .promptInfo(promptInfo) - .onboardingInfo(onboardingInfo) - .iconFileID(avatarInfo.getFileInfo().getID()) - .build(); + // set the onboarding info of your bot + BotOnboardingInfo onboardingInfo = + BotOnboardingInfo.builder() + .prologue("the prologue of your bot") + .suggestedQuestions(Arrays.asList("question 1", "question 2")) + .build(); + // Call the upload file interface to get the avatar id. + String avatarPath = System.getenv("IMAGE_FILE_PATH"); + UploadFileResp avatarInfo = coze.files().upload(UploadFileReq.of(avatarPath)); + System.out.println(avatarInfo); - // Invoke the creation interface to create a bot in the draft status, and you can get the bot id. - CreateBotResp createResp = coze.bots().create(createReq); - String botID = createResp.getBotID(); - System.out.println(createResp); + // build the request + CreateBotReq createReq = + CreateBotReq.builder() + .spaceID(workspaceID) + .description("the description of your bot") + .name("the name of your bot") + .promptInfo(promptInfo) + .onboardingInfo(onboardingInfo) + .iconFileID(avatarInfo.getFileInfo().getID()) + .build(); - /* - * step two, update the bot, you can update the bot after being created - * in this example, we will update the avatar of the bot - */ - PublishBotReq publishReq = PublishBotReq.builder() - .botID(botID) - .connectorIDs(Arrays.asList("1024")) - .build(); + // Invoke the creation interface to create a bot in the draft status, and you can get the bot + // id. + CreateBotResp createResp = coze.bots().create(createReq); + String botID = createResp.getBotID(); + System.out.println(createResp); - // Call the publishing interface to publish the bot on the api channel. - PublishBotResp updateResp = coze.bots().publish(publishReq); - System.out.println(updateResp); + /* + * step two, update the bot, you can update the bot after being created + * in this example, we will update the avatar of the bot + */ + PublishBotReq publishReq = + PublishBotReq.builder().botID(botID).connectorIDs(Arrays.asList("1024")).build(); - /* - * step three, you can also modify the bot configuration and republish it. - * in this example, we will update the avatar of the bot - */ + // Call the publishing interface to publish the bot on the api channel. + PublishBotResp updateResp = coze.bots().publish(publishReq); + System.out.println(updateResp); - // set the onboarding info of your bot - // Call the upload file interface to get the avatar id. - String newAvatarPath = System.getenv("IMAGE_FILE_PATH"); - UploadFileResp newAvatarInfo = coze.files().upload(UploadFileReq.of(newAvatarPath)); - System.out.println(newAvatarInfo); - // build the request - UpdateBotReq updateReq = UpdateBotReq.builder() - .botID(botID) - .iconFileID(newAvatarInfo.getFileInfo().getID()) - .build(); - // Invoke the update interface to update a bot, It means success that no exception has been thrown. - coze.bots().update(updateReq); - updateResp = coze.bots().publish(publishReq); - System.out.println(updateResp); + /* + * step three, you can also modify the bot configuration and republish it. + * in this example, we will update the avatar of the bot + */ - } -} \ No newline at end of file + // set the onboarding info of your bot + // Call the upload file interface to get the avatar id. + String newAvatarPath = System.getenv("IMAGE_FILE_PATH"); + UploadFileResp newAvatarInfo = coze.files().upload(UploadFileReq.of(newAvatarPath)); + System.out.println(newAvatarInfo); + // build the request + UpdateBotReq updateReq = + UpdateBotReq.builder().botID(botID).iconFileID(newAvatarInfo.getFileInfo().getID()).build(); + // Invoke the update interface to update a bot, It means success that no exception has been + // thrown. + coze.bots().update(updateReq); + updateResp = coze.bots().publish(publishReq); + System.out.println(updateResp); + } +} diff --git a/example/src/main/java/example/bot/BotRetrieveExample.java b/example/src/main/java/example/bot/BotRetrieveExample.java index 4222c928..724837b5 100644 --- a/example/src/main/java/example/bot/BotRetrieveExample.java +++ b/example/src/main/java/example/bot/BotRetrieveExample.java @@ -1,5 +1,9 @@ +/* (C)2024 */ package example.bot; +import java.io.IOException; +import java.util.Iterator; + import com.coze.openapi.client.bots.ListBotReq; import com.coze.openapi.client.bots.RetrieveBotReq; import com.coze.openapi.client.bots.RetrieveBotResp; @@ -9,60 +13,56 @@ import com.coze.openapi.service.auth.TokenAuth; import com.coze.openapi.service.service.CozeAPI; -import java.io.IOException; -import java.util.Iterator; - /* This example is for describing how to retrieve a bot, fetch published bot list from the API. The document for those interface: * */ public class BotRetrieveExample { - public static void main(String[] args) throws IOException { - // Get an access_token through personal access token or oauth. - String token = System.getenv("COZE_API_TOKEN"); - String botID = System.getenv("COZE_BOT_ID"); - TokenAuth authCli = new TokenAuth(token); + public static void main(String[] args) throws IOException { + // Get an access_token through personal access token or oauth. + String token = System.getenv("COZE_API_TOKEN"); + String botID = System.getenv("COZE_BOT_ID"); + TokenAuth authCli = new TokenAuth(token); - // Init the Coze client through the access_token. - CozeAPI coze = new CozeAPI.Builder() - .baseURL(System.getenv("COZE_API_BASE")) - .auth(authCli) - .readTimeout(10000) - .build();; + // Init the Coze client through the access_token. + CozeAPI coze = + new CozeAPI.Builder() + .baseURL(System.getenv("COZE_API_BASE")) + .auth(authCli) + .readTimeout(10000) + .build(); + ; - /* - * retrieve a bot - * */ - RetrieveBotResp botInfo = coze.bots().retrieve(RetrieveBotReq.of(botID)); - Bot bot = botInfo.getBot(); - System.out.println(bot); - System.out.println(botInfo.getLogID()); + /* + * retrieve a bot + * */ + RetrieveBotResp botInfo = coze.bots().retrieve(RetrieveBotReq.of(botID)); + Bot bot = botInfo.getBot(); + System.out.println(bot); + System.out.println(botInfo.getLogID()); - /* - * get published bot list - * */ + /* + * get published bot list + * */ - Integer pageNum = 1; - String workspaceID = System.getenv("WORKSPACE_ID"); - ListBotReq listBotReq = ListBotReq.builder() - .spaceID(workspaceID) - .pageNum(pageNum) - .pageSize(10) - .build(); - PageResp botList = coze.bots().list(listBotReq); + Integer pageNum = 1; + String workspaceID = System.getenv("WORKSPACE_ID"); + ListBotReq listBotReq = + ListBotReq.builder().spaceID(workspaceID).pageNum(pageNum).pageSize(10).build(); + PageResp botList = coze.bots().list(listBotReq); - // 2. The SDK encapsulates an iterator, which can be used to turn pages backward automatically. - Iterator iterator = botList.getIterator(); - while (iterator.hasNext()) { - iterator.forEachRemaining(System.out::println); - } + // 2. The SDK encapsulates an iterator, which can be used to turn pages backward automatically. + Iterator iterator = botList.getIterator(); + while (iterator.hasNext()) { + iterator.forEachRemaining(System.out::println); + } - // the page result will return followed information - System.out.println("total: " + botList.getTotal()); - System.out.println("has_more: " + botList.getHasMore()); - System.out.println("logID: " + botList.getLogID()); - for (SimpleBot item : botList.getItems()) { - System.out.println(item); - } + // the page result will return followed information + System.out.println("total: " + botList.getTotal()); + System.out.println("has_more: " + botList.getHasMore()); + System.out.println("logID: " + botList.getLogID()); + for (SimpleBot item : botList.getItems()) { + System.out.println(item); } + } } diff --git a/example/src/main/java/example/chat/ChatExample.java b/example/src/main/java/example/chat/ChatExample.java index 2e9b57fe..0cc45417 100644 --- a/example/src/main/java/example/chat/ChatExample.java +++ b/example/src/main/java/example/chat/ChatExample.java @@ -1,15 +1,16 @@ +/* (C)2024 */ package example.chat; +import java.util.Collections; +import java.util.concurrent.TimeUnit; + import com.coze.openapi.client.chat.*; import com.coze.openapi.client.chat.model.Chat; import com.coze.openapi.client.chat.model.ChatPoll; import com.coze.openapi.client.chat.model.ChatStatus; import com.coze.openapi.client.connversations.message.model.Message; -import com.coze.openapi.service.service.CozeAPI; import com.coze.openapi.service.auth.TokenAuth; - -import java.util.Collections; -import java.util.concurrent.TimeUnit; +import com.coze.openapi.service.service.CozeAPI; /* This example describes how to use the chat interface to initiate conversations, @@ -17,79 +18,80 @@ * */ public class ChatExample { - // For non-streaming chat API, it is necessary to create a chat first and then poll the chat results. - public static void main(String[] args) throws Exception { - // Get an access_token through personal access token or oauth. - String token = System.getenv("COZE_API_TOKEN"); - String botID = System.getenv("PUBLISHED_BOT_ID"); - String uid = System.getenv("USER_ID"); - - TokenAuth authCli = new TokenAuth(token); + // For non-streaming chat API, it is necessary to create a chat first and then poll the chat + // results. + public static void main(String[] args) throws Exception { + // Get an access_token through personal access token or oauth. + String token = System.getenv("COZE_API_TOKEN"); + String botID = System.getenv("PUBLISHED_BOT_ID"); + String uid = System.getenv("USER_ID"); - // Init the Coze client through the access_token. - CozeAPI coze = new CozeAPI.Builder() - .baseURL(System.getenv("COZE_API_BASE")) - .auth(authCli) - .readTimeout(10000) - .build(); + TokenAuth authCli = new TokenAuth(token); + // Init the Coze client through the access_token. + CozeAPI coze = + new CozeAPI.Builder() + .baseURL(System.getenv("COZE_API_BASE")) + .auth(authCli) + .readTimeout(10000) + .build(); - /* - * Step one, create chat - * Call the coze.chat().create() method to create a chat. The create method is a non-streaming - * chat and will return a Chat class. Developers should periodically check the status of the - * chat and handle them separately according to different states. - * */ - CreateChatReq req = CreateChatReq.builder() - .botID(botID) - .userID(uid) - .messages(Collections.singletonList(Message.buildUserQuestionText("What can you do?"))) - .build(); + /* + * Step one, create chat + * Call the coze.chat().create() method to create a chat. The create method is a non-streaming + * chat and will return a Chat class. Developers should periodically check the status of the + * chat and handle them separately according to different states. + * */ + CreateChatReq req = + CreateChatReq.builder() + .botID(botID) + .userID(uid) + .messages(Collections.singletonList(Message.buildUserQuestionText("What can you do?"))) + .build(); - CreateChatResp chatResp = coze.chat().create(req); - System.out.println(chatResp); - Chat chat = chatResp.getChat(); - // get chat id and conversationID - String chatID = chat.getID(); - String conversationID = chat.getConversationID(); + CreateChatResp chatResp = coze.chat().create(req); + System.out.println(chatResp); + Chat chat = chatResp.getChat(); + // get chat id and conversationID + String chatID = chat.getID(); + String conversationID = chat.getConversationID(); - /* - * Step two, poll the result of chat - * Assume the development allows at most one chat to run for 10 seconds. If it exceeds 10 seconds, - * the chat will be cancelled. - * And when the chat status is not completed, poll the status of the chat once every second. - * After the chat is completed, retrieve all messages in the chat. - * */ - long timeout = 10L; - long start = System.currentTimeMillis() / 1000; - while (ChatStatus.IN_PROGRESS.equals(chat.getStatus())) { - try { - // The API has a rate limit with 1 QPS. - TimeUnit.SECONDS.sleep(1); - } catch (InterruptedException e) { - e.printStackTrace(); - break; - } + /* + * Step two, poll the result of chat + * Assume the development allows at most one chat to run for 10 seconds. If it exceeds 10 seconds, + * the chat will be cancelled. + * And when the chat status is not completed, poll the status of the chat once every second. + * After the chat is completed, retrieve all messages in the chat. + * */ + long timeout = 10L; + long start = System.currentTimeMillis() / 1000; + while (ChatStatus.IN_PROGRESS.equals(chat.getStatus())) { + try { + // The API has a rate limit with 1 QPS. + TimeUnit.SECONDS.sleep(1); + } catch (InterruptedException e) { + e.printStackTrace(); + break; + } - if ((System.currentTimeMillis() / 1000) - start > timeout) { - // The chat can be cancelled before its completed. - System.out.println(coze.chat().cancel(CancelChatReq.of(conversationID, chatID))); - break; - } - RetrieveChatResp resp = coze.chat().retrieve(RetrieveChatReq.of(conversationID, chatID)); - System.out.println(resp); - chat = resp.getChat(); - if (ChatStatus.COMPLETED.equals(chat.getStatus())) { - break; - } - } - - - // The sdk provide an automatic polling method. - ChatPoll chat2 = coze.chat().createAndPoll(req); - System.out.println(chat2); - // the developer can also set the timeout. - ChatPoll chat3 = coze.chat().createAndPoll(req, timeout); - System.out.println(chat3); + if ((System.currentTimeMillis() / 1000) - start > timeout) { + // The chat can be cancelled before its completed. + System.out.println(coze.chat().cancel(CancelChatReq.of(conversationID, chatID))); + break; + } + RetrieveChatResp resp = coze.chat().retrieve(RetrieveChatReq.of(conversationID, chatID)); + System.out.println(resp); + chat = resp.getChat(); + if (ChatStatus.COMPLETED.equals(chat.getStatus())) { + break; + } } -} \ No newline at end of file + + // The sdk provide an automatic polling method. + ChatPoll chat2 = coze.chat().createAndPoll(req); + System.out.println(chat2); + // the developer can also set the timeout. + ChatPoll chat3 = coze.chat().createAndPoll(req, timeout); + System.out.println(chat3); + } +} diff --git a/example/src/main/java/example/chat/ChatWithImageExample.java b/example/src/main/java/example/chat/ChatWithImageExample.java index e6107b1e..56d38b6c 100644 --- a/example/src/main/java/example/chat/ChatWithImageExample.java +++ b/example/src/main/java/example/chat/ChatWithImageExample.java @@ -1,5 +1,9 @@ +/* (C)2024 */ package example.chat; +import java.util.Arrays; +import java.util.Collections; + import com.coze.openapi.client.chat.CreateChatReq; import com.coze.openapi.client.chat.model.ChatEvent; import com.coze.openapi.client.chat.model.ChatEventType; @@ -9,58 +13,60 @@ import com.coze.openapi.client.files.model.FileInfo; import com.coze.openapi.service.auth.TokenAuth; import com.coze.openapi.service.service.CozeAPI; -import io.reactivex.Flowable; -import java.util.Arrays; -import java.util.Collections; +import io.reactivex.Flowable; /* -* This example is about how to use the streaming interface to start a chat request -* with image upload and handle chat events -* */ + * This example is about how to use the streaming interface to start a chat request + * with image upload and handle chat events + * */ public class ChatWithImageExample { - public static void main(String[] args) { + public static void main(String[] args) { - // Get an access_token through personal access token or oauth. - String token = System.getenv("COZE_API_TOKEN"); - String botID = System.getenv("PUBLISHED_BOT_ID"); - String userID = System.getenv("USER_ID"); + // Get an access_token through personal access token or oauth. + String token = System.getenv("COZE_API_TOKEN"); + String botID = System.getenv("PUBLISHED_BOT_ID"); + String userID = System.getenv("USER_ID"); - TokenAuth authCli = new TokenAuth(token); + TokenAuth authCli = new TokenAuth(token); - // Init the Coze client through the access_token. - CozeAPI coze = new CozeAPI.Builder() - .baseURL(System.getenv("COZE_API_BASE")) - .auth(authCli) - .readTimeout(10000) - .build();; + // Init the Coze client through the access_token. + CozeAPI coze = + new CozeAPI.Builder() + .baseURL(System.getenv("COZE_API_BASE")) + .auth(authCli) + .readTimeout(10000) + .build(); + ; - // Call the upload file interface to get the image id. - String imagePath = System.getenv("IMAGE_FILE_PATH"); - FileInfo imageInfo = coze.files().upload(UploadFileReq.of(imagePath)).getFileInfo(); + // Call the upload file interface to get the image id. + String imagePath = System.getenv("IMAGE_FILE_PATH"); + FileInfo imageInfo = coze.files().upload(UploadFileReq.of(imagePath)).getFileInfo(); - /* - * Step one, create chat - * Call the coze.chat().stream() method to create a chat. The create method is a streaming - * chat and will return a Flowable ChatEvent. Developers should iterate the iterator to get - * chat event and handle them. - * */ - CreateChatReq req = CreateChatReq.builder() - .botID(botID) - .userID(userID) - .messages(Collections.singletonList(Message.buildUserQuestionObjects( + /* + * Step one, create chat + * Call the coze.chat().stream() method to create a chat. The create method is a streaming + * chat and will return a Flowable ChatEvent. Developers should iterate the iterator to get + * chat event and handle them. + * */ + CreateChatReq req = + CreateChatReq.builder() + .botID(botID) + .userID(userID) + .messages( + Collections.singletonList( + Message.buildUserQuestionObjects( Arrays.asList( - MessageObjectString.buildText("Describe this picture"), - MessageObjectString.buildImageByID(imageInfo.getID()) - ) - ))) - .build(); + MessageObjectString.buildText("Describe this picture"), + MessageObjectString.buildImageByID(imageInfo.getID()))))) + .build(); - Flowable resp = coze.chat().stream(req); - resp.blockingForEach(event -> { - if (ChatEventType.CONVERSATION_MESSAGE_DELTA.equals(event.getEvent())) { - System.out.print(event.getMessage().getContent()); - } + Flowable resp = coze.chat().stream(req); + resp.blockingForEach( + event -> { + if (ChatEventType.CONVERSATION_MESSAGE_DELTA.equals(event.getEvent())) { + System.out.print(event.getMessage().getContent()); + } }); - } + } } diff --git a/example/src/main/java/example/chat/StreamChatExample.java b/example/src/main/java/example/chat/StreamChatExample.java index c2d40634..128d71eb 100644 --- a/example/src/main/java/example/chat/StreamChatExample.java +++ b/example/src/main/java/example/chat/StreamChatExample.java @@ -1,60 +1,65 @@ +/* (C)2024 */ package example.chat; +import java.util.Collections; + import com.coze.openapi.client.chat.CreateChatReq; import com.coze.openapi.client.chat.model.ChatEvent; import com.coze.openapi.client.chat.model.ChatEventType; import com.coze.openapi.client.connversations.message.model.Message; -import com.coze.openapi.service.service.CozeAPI; import com.coze.openapi.service.auth.TokenAuth; +import com.coze.openapi.service.service.CozeAPI; import io.reactivex.Flowable; -import java.util.Collections; - /* * This example is about how to use the streaming interface to start a chat request * and handle chat events * */ public class StreamChatExample { - public static void main(String[] args) { - - // Get an access_token through personal access token or oauth. - String token = System.getenv("COZE_API_TOKEN"); - String botID = System.getenv("PUBLISHED_BOT_ID"); - String userID = System.getenv("USER_ID"); - - TokenAuth authCli = new TokenAuth(token); - - // Init the Coze client through the access_token. - CozeAPI coze = new CozeAPI.Builder() - .baseURL(System.getenv("COZE_API_BASE")) - .auth(authCli) - .readTimeout(10000) - .build();; - - /* - * Step one, create chat - * Call the coze.chat().stream() method to create a chat. The create method is a streaming - * chat and will return a Flowable ChatEvent. Developers should iterate the iterator to get - * chat event and handle them. - * */ - CreateChatReq req = CreateChatReq.builder() - .botID(botID) - .userID(userID) - .messages(Collections.singletonList(Message.buildUserQuestionText("What can you do?"))) - .build(); - - Flowable resp = coze.chat().stream(req); - resp.blockingForEach(event -> { - if (ChatEventType.CONVERSATION_MESSAGE_DELTA.equals(event.getEvent())) { - System.out.print(event.getMessage().getContent()); - } - if (ChatEventType.CONVERSATION_CHAT_COMPLETED.equals(event.getEvent())) { - System.out.println("Token usage:" + event.getChat().getUsage().getTokenCount()); - } + public static void main(String[] args) { + + // Get an access_token through personal access token or oauth. + String token = System.getenv("COZE_API_TOKEN"); + String botID = System.getenv("PUBLISHED_BOT_ID"); + String userID = System.getenv("USER_ID"); + + TokenAuth authCli = new TokenAuth(token); + + // Init the Coze client through the access_token. + CozeAPI coze = + new CozeAPI.Builder() + .baseURL(System.getenv("COZE_API_BASE")) + .auth(authCli) + .readTimeout(10000) + .build(); + ; + + /* + * Step one, create chat + * Call the coze.chat().stream() method to create a chat. The create method is a streaming + * chat and will return a Flowable ChatEvent. Developers should iterate the iterator to get + * chat event and handle them. + * */ + CreateChatReq req = + CreateChatReq.builder() + .botID(botID) + .userID(userID) + .messages(Collections.singletonList(Message.buildUserQuestionText("What can you do?"))) + .build(); + + Flowable resp = coze.chat().stream(req); + resp.blockingForEach( + event -> { + if (ChatEventType.CONVERSATION_MESSAGE_DELTA.equals(event.getEvent())) { + System.out.print(event.getMessage().getContent()); + } + if (ChatEventType.CONVERSATION_CHAT_COMPLETED.equals(event.getEvent())) { + System.out.println("Token usage:" + event.getChat().getUsage().getTokenCount()); + } }); - System.out.println("done"); - coze.shutdownExecutor(); - } -} \ No newline at end of file + System.out.println("done"); + coze.shutdownExecutor(); + } +} diff --git a/example/src/main/java/example/chat/SubmitToolOutputExample.java b/example/src/main/java/example/chat/SubmitToolOutputExample.java index 83434b39..d24b9fb2 100644 --- a/example/src/main/java/example/chat/SubmitToolOutputExample.java +++ b/example/src/main/java/example/chat/SubmitToolOutputExample.java @@ -1,7 +1,13 @@ +/* (C)2024 */ package example.chat; /* -* This use case teaches you how to use local plugin. -* */ + * This use case teaches you how to use local plugin. + * */ +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; + import com.coze.openapi.client.chat.CreateChatReq; import com.coze.openapi.client.chat.SubmitToolOutputsReq; import com.coze.openapi.client.chat.model.ChatEvent; @@ -9,92 +15,92 @@ import com.coze.openapi.client.chat.model.ChatToolCall; import com.coze.openapi.client.chat.model.ToolOutput; import com.coze.openapi.client.connversations.message.model.Message; -import com.coze.openapi.service.service.CozeAPI; import com.coze.openapi.service.auth.TokenAuth; +import com.coze.openapi.service.service.CozeAPI; import io.reactivex.Flowable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.atomic.AtomicReference; - public class SubmitToolOutputExample { - /* - * In this example, we assume that the user asks the bot about today's weather. - * This scenario requires the invocation of local plugins. - * */ - public static void main(String[] args) { - - // Get an access_token through personal access token or oauth. - String token = System.getenv("COZE_API_TOKEN"); - String botID = System.getenv("PUBLISHED_BOT_ID"); - String userID = System.getenv("USER_ID"); - TokenAuth authCli = new TokenAuth(token); - - // Init the Coze client through the access_token. - CozeAPI coze = new CozeAPI.Builder() - .baseURL(System.getenv("COZE_API_BASE")) - .auth(authCli) - .readTimeout(10000) - .build(); - - - CreateChatReq req = CreateChatReq.builder() - .botID(botID) - .userID(userID) - .messages(Collections.singletonList( - Message.buildUserQuestionText("how's the weather in ShenZhen today?"))) - .build(); - - AtomicReference pluginEventRef = new AtomicReference<>(); - AtomicReference conversationRef = new AtomicReference<>(); - Flowable resp = coze.chat().stream(req); - - resp.blockingForEach(event -> { - if (ChatEventType.CONVERSATION_MESSAGE_DELTA.equals(event.getEvent())) { - System.out.print(event.getMessage().getContent()); - } - /* - * handle the chat event, if event type is CONVERSATION_CHAT_REQUIRES_ACTION, - * it means the bot requires the invocation of local plugins. - * In this example, we will invoke the local plugin to get the weather information. - * */ - if (ChatEventType.CONVERSATION_CHAT_REQUIRES_ACTION.equals(event.getEvent())) { - System.out.println("need action"); - pluginEventRef.set(event); - conversationRef.set(event.getChat().getConversationID()); - } + /* + * In this example, we assume that the user asks the bot about today's weather. + * This scenario requires the invocation of local plugins. + * */ + public static void main(String[] args) { + + // Get an access_token through personal access token or oauth. + String token = System.getenv("COZE_API_TOKEN"); + String botID = System.getenv("PUBLISHED_BOT_ID"); + String userID = System.getenv("USER_ID"); + TokenAuth authCli = new TokenAuth(token); + + // Init the Coze client through the access_token. + CozeAPI coze = + new CozeAPI.Builder() + .baseURL(System.getenv("COZE_API_BASE")) + .auth(authCli) + .readTimeout(10000) + .build(); + + CreateChatReq req = + CreateChatReq.builder() + .botID(botID) + .userID(userID) + .messages( + Collections.singletonList( + Message.buildUserQuestionText("how's the weather in ShenZhen today?"))) + .build(); + + AtomicReference pluginEventRef = new AtomicReference<>(); + AtomicReference conversationRef = new AtomicReference<>(); + Flowable resp = coze.chat().stream(req); + + resp.blockingForEach( + event -> { + if (ChatEventType.CONVERSATION_MESSAGE_DELTA.equals(event.getEvent())) { + System.out.print(event.getMessage().getContent()); + } + /* + * handle the chat event, if event type is CONVERSATION_CHAT_REQUIRES_ACTION, + * it means the bot requires the invocation of local plugins. + * In this example, we will invoke the local plugin to get the weather information. + * */ + if (ChatEventType.CONVERSATION_CHAT_REQUIRES_ACTION.equals(event.getEvent())) { + System.out.println("need action"); + pluginEventRef.set(event); + conversationRef.set(event.getChat().getConversationID()); + } }); - String conversationID = conversationRef.get(); - ChatEvent pluginEvent = pluginEventRef.get(); - - List toolOutputs = new ArrayList<>(); - for (ChatToolCall callInfo : pluginEvent.getChat().getRequiredAction().getSubmitToolOutputs().getToolCalls()) { - String callID = callInfo.getID(); - // you can handle different plugin by name. - String functionName = callInfo.getFunction().getName(); - // you should unmarshal arguments if necessary. - String argsJson = callInfo.getFunction().getArguments(); - - toolOutputs.add(ToolOutput.of(callID, "It is 18 to 21")); - } + String conversationID = conversationRef.get(); + ChatEvent pluginEvent = pluginEventRef.get(); - SubmitToolOutputsReq toolReq = SubmitToolOutputsReq.builder() - .chatID(pluginEvent.getChat().getID()) - .conversationID(conversationID) - .toolOutputs(toolOutputs) - .build(); + List toolOutputs = new ArrayList<>(); + for (ChatToolCall callInfo : + pluginEvent.getChat().getRequiredAction().getSubmitToolOutputs().getToolCalls()) { + String callID = callInfo.getID(); + // you can handle different plugin by name. + String functionName = callInfo.getFunction().getName(); + // you should unmarshal arguments if necessary. + String argsJson = callInfo.getFunction().getArguments(); + toolOutputs.add(ToolOutput.of(callID, "It is 18 to 21")); + } - Flowable events = coze.chat().streamSubmitToolOutputs(toolReq); - events.blockingForEach(event -> { - if (ChatEventType.CONVERSATION_MESSAGE_DELTA.equals(event.getEvent())) { - System.out.print(event.getMessage().getContent()); - } + SubmitToolOutputsReq toolReq = + SubmitToolOutputsReq.builder() + .chatID(pluginEvent.getChat().getID()) + .conversationID(conversationID) + .toolOutputs(toolOutputs) + .build(); + + Flowable events = coze.chat().streamSubmitToolOutputs(toolReq); + events.blockingForEach( + event -> { + if (ChatEventType.CONVERSATION_MESSAGE_DELTA.equals(event.getEvent())) { + System.out.print(event.getMessage().getContent()); + } }); - coze.shutdownExecutor(); - } -} \ No newline at end of file + coze.shutdownExecutor(); + } +} diff --git a/example/src/main/java/example/conversation/ConversationCreateExample.java b/example/src/main/java/example/conversation/ConversationCreateExample.java index 40a953c4..3591ed7b 100644 --- a/example/src/main/java/example/conversation/ConversationCreateExample.java +++ b/example/src/main/java/example/conversation/ConversationCreateExample.java @@ -1,5 +1,8 @@ +/* (C)2024 */ package example.conversation; +import java.util.Arrays; + import com.coze.openapi.client.connversations.ClearConversationReq; import com.coze.openapi.client.connversations.ClearConversationResp; import com.coze.openapi.client.connversations.CreateConversationReq; @@ -10,49 +13,56 @@ import com.coze.openapi.client.connversations.message.CreateMessageResp; import com.coze.openapi.client.connversations.message.model.MessageObjectString; import com.coze.openapi.client.connversations.message.model.MessageRole; -import com.coze.openapi.service.service.CozeAPI; import com.coze.openapi.service.auth.TokenAuth; - -import java.util.Arrays; +import com.coze.openapi.service.service.CozeAPI; /* -* This example is about how to create conversation and retrieve. -* */ + * This example is about how to create conversation and retrieve. + * */ public class ConversationCreateExample { - public static void main(String[] args) { - // Get an access_token through personal access token or oauth. - String token = System.getenv("COZE_API_TOKEN"); - TokenAuth authCli = new TokenAuth(token); - - // Init the Coze client through the access_token. - CozeAPI coze = new CozeAPI.Builder() - .baseURL(System.getenv("COZE_API_BASE")) - .auth(authCli) - .readTimeout(10000) - .build();; - - CreateConversationResp resp = coze.conversations().create(new CreateConversationReq()); - System.out.println("create conversations" + resp); - - String conversationID = resp.getConversation().getId(); - RetrieveConversationResp getResp = coze.conversations().retrieve(RetrieveConversationReq.of(conversationID)); - System.out.println("retrieve conversations:" + getResp); - - // you can manually create message for conversation - CreateMessageResp msgs = coze.conversations().messages().create(CreateMessageReq - .builder() - .role(MessageRole.USER) - .conversationID(conversationID) - // if you want to create object content, you can use followed method to simplify your code - .objectContent( - Arrays.asList(MessageObjectString.buildText("hello"), - MessageObjectString.buildImageByURL(System.getenv("IMAGE_FILE_PATH")), - MessageObjectString.buildFileByURL(System.getenv("FILE_URL")))) - .build()); - System.out.println(msgs); - - ClearConversationResp clearResp = coze.conversations().clear(ClearConversationReq.of(conversationID)); - System.out.println(clearResp); - } -} \ No newline at end of file + public static void main(String[] args) { + // Get an access_token through personal access token or oauth. + String token = System.getenv("COZE_API_TOKEN"); + TokenAuth authCli = new TokenAuth(token); + + // Init the Coze client through the access_token. + CozeAPI coze = + new CozeAPI.Builder() + .baseURL(System.getenv("COZE_API_BASE")) + .auth(authCli) + .readTimeout(10000) + .build(); + ; + + CreateConversationResp resp = coze.conversations().create(new CreateConversationReq()); + System.out.println("create conversations" + resp); + + String conversationID = resp.getConversation().getId(); + RetrieveConversationResp getResp = + coze.conversations().retrieve(RetrieveConversationReq.of(conversationID)); + System.out.println("retrieve conversations:" + getResp); + + // you can manually create message for conversation + CreateMessageResp msgs = + coze.conversations() + .messages() + .create( + CreateMessageReq.builder() + .role(MessageRole.USER) + .conversationID(conversationID) + // if you want to create object content, you can use followed method to simplify + // your code + .objectContent( + Arrays.asList( + MessageObjectString.buildText("hello"), + MessageObjectString.buildImageByURL(System.getenv("IMAGE_FILE_PATH")), + MessageObjectString.buildFileByURL(System.getenv("FILE_URL")))) + .build()); + System.out.println(msgs); + + ClearConversationResp clearResp = + coze.conversations().clear(ClearConversationReq.of(conversationID)); + System.out.println(clearResp); + } +} diff --git a/example/src/main/java/example/conversation/ConversationsListExample.java b/example/src/main/java/example/conversation/ConversationsListExample.java index 579b9c4a..bcfd6de4 100644 --- a/example/src/main/java/example/conversation/ConversationsListExample.java +++ b/example/src/main/java/example/conversation/ConversationsListExample.java @@ -1,41 +1,43 @@ +/* (C)2024 */ package example.conversation; +import java.util.Iterator; + import com.coze.openapi.client.common.pagination.PageResp; import com.coze.openapi.client.connversations.ListConversationReq; import com.coze.openapi.client.connversations.model.Conversation; import com.coze.openapi.service.auth.TokenAuth; import com.coze.openapi.service.service.CozeAPI; -import java.util.Iterator; - public class ConversationsListExample { - public static void main(String[] args) { - // Get an access_token through personal access token or oauth. - String token = System.getenv("COZE_API_TOKEN"); - TokenAuth authCli = new TokenAuth(token); - - String botID = System.getenv("COZE_BOT_ID"); - - // Init the Coze client through the access_token. - CozeAPI coze = new CozeAPI.Builder() - .baseURL(System.getenv("COZE_API_BASE")) - .auth(authCli) - .readTimeout(10000) - .build();; - - // you can use iterator to automatically retrieve next page - PageResp conversations = coze.conversations().list(ListConversationReq.of(botID)); - Iterator iter = conversations.getIterator(); - iter.forEachRemaining(System.out::println); - - - // the page result will return followed information - System.out.println("total: " + conversations.getTotal()); - System.out.println("has_more: " + conversations.getHasMore()); - System.out.println("logID: " + conversations.getLogID()); - for (Conversation item : conversations.getItems()) { - System.out.println(item); - } + public static void main(String[] args) { + // Get an access_token through personal access token or oauth. + String token = System.getenv("COZE_API_TOKEN"); + TokenAuth authCli = new TokenAuth(token); + + String botID = System.getenv("COZE_BOT_ID"); + + // Init the Coze client through the access_token. + CozeAPI coze = + new CozeAPI.Builder() + .baseURL(System.getenv("COZE_API_BASE")) + .auth(authCli) + .readTimeout(10000) + .build(); + ; + + // you can use iterator to automatically retrieve next page + PageResp conversations = coze.conversations().list(ListConversationReq.of(botID)); + Iterator iter = conversations.getIterator(); + iter.forEachRemaining(System.out::println); + + // the page result will return followed information + System.out.println("total: " + conversations.getTotal()); + System.out.println("has_more: " + conversations.getHasMore()); + System.out.println("logID: " + conversations.getLogID()); + for (Conversation item : conversations.getItems()) { + System.out.println(item); } + } } diff --git a/example/src/main/java/example/conversation/message/MessageCrudExample.java b/example/src/main/java/example/conversation/message/MessageCrudExample.java index e2953178..137273c7 100644 --- a/example/src/main/java/example/conversation/message/MessageCrudExample.java +++ b/example/src/main/java/example/conversation/message/MessageCrudExample.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package example.conversation.message; import com.coze.openapi.client.connversations.message.CreateMessageReq; @@ -11,64 +12,75 @@ import com.coze.openapi.client.connversations.message.model.Message; import com.coze.openapi.client.connversations.message.model.MessageContentType; import com.coze.openapi.client.connversations.message.model.MessageRole; -import com.coze.openapi.service.service.CozeAPI; import com.coze.openapi.service.auth.TokenAuth; +import com.coze.openapi.service.service.CozeAPI; public class MessageCrudExample { - public static void main(String[] args) { - // Get an access_token through personal access token or oauth. - String token = System.getenv("COZE_API_TOKEN"); - TokenAuth authCli = new TokenAuth(token); - - // Init the Coze client through the access_token. - CozeAPI coze = new CozeAPI.Builder() - .baseURL(System.getenv("COZE_API_BASE")) - .auth(authCli) - .readTimeout(10000) - .build(); + public static void main(String[] args) { + // Get an access_token through personal access token or oauth. + String token = System.getenv("COZE_API_TOKEN"); + TokenAuth authCli = new TokenAuth(token); - String conversationID = System.getenv("CONVERSATION_ID"); + // Init the Coze client through the access_token. + CozeAPI coze = + new CozeAPI.Builder() + .baseURL(System.getenv("COZE_API_BASE")) + .auth(authCli) + .readTimeout(10000) + .build(); - /* - * create message to specific conversation - * */ - CreateMessageReq.CreateMessageReqBuilder builder = CreateMessageReq.builder(); - builder.conversationID(conversationID) - .role(MessageRole.USER) - .content("message count") - .contentType(MessageContentType.TEXT); - CreateMessageResp messageResp = coze.conversations().messages().create(builder.build()); - Message message = messageResp.getMessage(); - System.out.println(message); + String conversationID = System.getenv("CONVERSATION_ID"); - /* - * retrieve message - * */ - RetrieveMessageResp retrievedMsgResp = coze.conversations().messages().retrieve(RetrieveMessageReq.builder() - .conversationID(conversationID) - .messageID(message.getId()) - .build()); - Message retrievedMsg = retrievedMsgResp.getMessage(); - System.out.println(retrievedMsg); + /* + * create message to specific conversation + * */ + CreateMessageReq.CreateMessageReqBuilder builder = CreateMessageReq.builder(); + builder + .conversationID(conversationID) + .role(MessageRole.USER) + .content("message count") + .contentType(MessageContentType.TEXT); + CreateMessageResp messageResp = coze.conversations().messages().create(builder.build()); + Message message = messageResp.getMessage(); + System.out.println(message); - /* - * update message - * */ - UpdateMessageReq updateReq = UpdateMessageReq.builder() - .conversationID(conversationID).messageID(message.getId()) - .content(String.format("modified message content:%s", message.getContent())) - .contentType(MessageContentType.TEXT).build(); - UpdateMessageResp updateResp = coze.conversations().messages().update(updateReq); - Message updatedMsg = updateResp.getMessage(); - System.out.println(updatedMsg); + /* + * retrieve message + * */ + RetrieveMessageResp retrievedMsgResp = + coze.conversations() + .messages() + .retrieve( + RetrieveMessageReq.builder() + .conversationID(conversationID) + .messageID(message.getId()) + .build()); + Message retrievedMsg = retrievedMsgResp.getMessage(); + System.out.println(retrievedMsg); - /* - * delete message - * */ - DeleteMessageResp deletedMsgResp = coze.conversations().messages().delete(DeleteMessageReq.of(conversationID, message.getId())); - Message deletedMsg = deletedMsgResp.getMessage(); - System.out.println(deletedMsg); + /* + * update message + * */ + UpdateMessageReq updateReq = + UpdateMessageReq.builder() + .conversationID(conversationID) + .messageID(message.getId()) + .content(String.format("modified message content:%s", message.getContent())) + .contentType(MessageContentType.TEXT) + .build(); + UpdateMessageResp updateResp = coze.conversations().messages().update(updateReq); + Message updatedMsg = updateResp.getMessage(); + System.out.println(updatedMsg); - } -} \ No newline at end of file + /* + * delete message + * */ + DeleteMessageResp deletedMsgResp = + coze.conversations() + .messages() + .delete(DeleteMessageReq.of(conversationID, message.getId())); + Message deletedMsg = deletedMsgResp.getMessage(); + System.out.println(deletedMsg); + } +} diff --git a/example/src/main/java/example/conversation/message/MessageListExample.java b/example/src/main/java/example/conversation/message/MessageListExample.java index 5f66dc3c..d59f6fcc 100644 --- a/example/src/main/java/example/conversation/message/MessageListExample.java +++ b/example/src/main/java/example/conversation/message/MessageListExample.java @@ -1,47 +1,47 @@ +/* (C)2024 */ package example.conversation.message; +import java.util.Iterator; + +import com.coze.openapi.client.common.pagination.PageResp; import com.coze.openapi.client.connversations.message.ListMessageReq; import com.coze.openapi.client.connversations.message.model.Message; -import com.coze.openapi.client.common.pagination.PageResp; -import com.coze.openapi.service.service.CozeAPI; import com.coze.openapi.service.auth.TokenAuth; - -import java.util.Iterator; +import com.coze.openapi.service.service.CozeAPI; public class MessageListExample { - public static void main(String[] args) { - // Get an access_token through personal access token or oauth. - String token = System.getenv("COZE_API_TOKEN"); - TokenAuth authCli = new TokenAuth(token); - - // Init the Coze client through the access_token. - CozeAPI coze = new CozeAPI.Builder() - .baseURL(System.getenv("COZE_API_BASE")) - .auth(authCli) - .readTimeout(10000) - .build(); - - String conversationID = System.getenv("CONVERSATION_ID"); - Integer limit = 2; - - ListMessageReq req = ListMessageReq.builder() - .conversationID(conversationID) - .limit(limit) - .build(); - - // you can use iterator to automatically retrieve next page - PageResp messages = coze.conversations().messages().list(req); - Iterator iter = messages.getIterator(); - iter.forEachRemaining(System.out::println); - - // the page result will return followed information - System.out.println("total: " + messages.getTotal()); - System.out.println("has_more: " + messages.getHasMore()); - System.out.println("lastID: " + messages.getLastID()); - System.out.println("logID: " + messages.getLogID()); - for (Message item : messages.getItems()) { - System.out.println(item); - } + public static void main(String[] args) { + // Get an access_token through personal access token or oauth. + String token = System.getenv("COZE_API_TOKEN"); + TokenAuth authCli = new TokenAuth(token); + + // Init the Coze client through the access_token. + CozeAPI coze = + new CozeAPI.Builder() + .baseURL(System.getenv("COZE_API_BASE")) + .auth(authCli) + .readTimeout(10000) + .build(); + + String conversationID = System.getenv("CONVERSATION_ID"); + Integer limit = 2; + + ListMessageReq req = + ListMessageReq.builder().conversationID(conversationID).limit(limit).build(); + + // you can use iterator to automatically retrieve next page + PageResp messages = coze.conversations().messages().list(req); + Iterator iter = messages.getIterator(); + iter.forEachRemaining(System.out::println); + + // the page result will return followed information + System.out.println("total: " + messages.getTotal()); + System.out.println("has_more: " + messages.getHasMore()); + System.out.println("lastID: " + messages.getLastID()); + System.out.println("logID: " + messages.getLogID()); + for (Message item : messages.getItems()) { + System.out.println(item); } -} + } +} diff --git a/example/src/main/java/example/datasets/document/DocumentCrudExample.java b/example/src/main/java/example/datasets/document/DocumentCrudExample.java index 075637ba..5da9d0db 100644 --- a/example/src/main/java/example/datasets/document/DocumentCrudExample.java +++ b/example/src/main/java/example/datasets/document/DocumentCrudExample.java @@ -1,65 +1,71 @@ +/* (C)2024 */ package example.datasets.document; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + import com.coze.openapi.client.dataset.document.*; import com.coze.openapi.client.dataset.document.model.Document; import com.coze.openapi.client.dataset.document.model.DocumentBase; import com.coze.openapi.service.auth.TokenAuth; import com.coze.openapi.service.service.CozeAPI; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - public class DocumentCrudExample { - public static void main(String[] args) { + public static void main(String[] args) { - // Get an access_token through personal access token or oauth. - String token = System.getenv("COZE_API_TOKEN"); - TokenAuth authCli = new TokenAuth(token); + // Get an access_token through personal access token or oauth. + String token = System.getenv("COZE_API_TOKEN"); + TokenAuth authCli = new TokenAuth(token); - // Init the Coze client through the access_token. - CozeAPI coze = new CozeAPI.Builder() - .baseURL(System.getenv("COZE_API_BASE")) - .auth(authCli) - .readTimeout(10000) - .build();; + // Init the Coze client through the access_token. + CozeAPI coze = + new CozeAPI.Builder() + .baseURL(System.getenv("COZE_API_BASE")) + .auth(authCli) + .readTimeout(10000) + .build(); + ; - Long datasetID = Long.parseLong(System.getenv("DATASET_ID")); - /* - * create document in to specific dataset - * */ - CreateDocumentReq createReq = CreateDocumentReq.builder() - .datasetID(datasetID) - .documentBases(Arrays.asList( - DocumentBase.buildWebPage("web doc example", "https://bytedance.com"), - DocumentBase.buildLocalFile("file doc example", "your file content", "txt"))) - .build(); - CreateDocumentResp creatResp = coze.datasets().documents().create(createReq); - System.out.println(creatResp); - List documentIDs = new ArrayList<>(); - for (Document documentBase : creatResp.getDocumentInfos()) { - documentIDs.add(Long.parseLong(documentBase.getDocumentID())); - } - - /* - * update document. It means success that no exception has been thrown - * */ - UpdateDocumentReq updateReq = UpdateDocumentReq.builder() - .documentID(documentIDs.get(0)) - .documentName("new name") - .build(); - UpdateDocumentResp uploadFileResp = coze.datasets().documents().update(updateReq); - System.out.println(uploadFileResp); - - /* - * delete document. It means success that no exception has been thrown - * */ - DeleteDocumentResp deletedResp = coze.datasets().documents().delete(DeleteDocumentReq.builder().documentIDs(Collections.singletonList(documentIDs.get(0))).build()); - System.out.println(deletedResp); + Long datasetID = Long.parseLong(System.getenv("DATASET_ID")); + /* + * create document in to specific dataset + * */ + CreateDocumentReq createReq = + CreateDocumentReq.builder() + .datasetID(datasetID) + .documentBases( + Arrays.asList( + DocumentBase.buildWebPage("web doc example", "https://bytedance.com"), + DocumentBase.buildLocalFile("file doc example", "your file content", "txt"))) + .build(); + CreateDocumentResp creatResp = coze.datasets().documents().create(createReq); + System.out.println(creatResp); + List documentIDs = new ArrayList<>(); + for (Document documentBase : creatResp.getDocumentInfos()) { + documentIDs.add(Long.parseLong(documentBase.getDocumentID())); } + /* + * update document. It means success that no exception has been thrown + * */ + UpdateDocumentReq updateReq = + UpdateDocumentReq.builder().documentID(documentIDs.get(0)).documentName("new name").build(); + UpdateDocumentResp uploadFileResp = coze.datasets().documents().update(updateReq); + System.out.println(uploadFileResp); - + /* + * delete document. It means success that no exception has been thrown + * */ + DeleteDocumentResp deletedResp = + coze.datasets() + .documents() + .delete( + DeleteDocumentReq.builder() + .documentIDs(Collections.singletonList(documentIDs.get(0))) + .build()); + System.out.println(deletedResp); + } } diff --git a/example/src/main/java/example/datasets/document/DocumentListExample.java b/example/src/main/java/example/datasets/document/DocumentListExample.java index 45d816b9..0525eccf 100644 --- a/example/src/main/java/example/datasets/document/DocumentListExample.java +++ b/example/src/main/java/example/datasets/document/DocumentListExample.java @@ -1,45 +1,44 @@ +/* (C)2024 */ package example.datasets.document; +import java.util.Iterator; + import com.coze.openapi.client.common.pagination.PageResp; import com.coze.openapi.client.dataset.document.ListDocumentReq; import com.coze.openapi.client.dataset.document.model.Document; import com.coze.openapi.service.auth.TokenAuth; import com.coze.openapi.service.service.CozeAPI; -import java.util.Iterator; - public class DocumentListExample { - public static void main(String[] args) { - // Get an access_token through personal access token or oauth. - String token = System.getenv("COZE_API_TOKEN"); - TokenAuth authCli = new TokenAuth(token); - - // Init the Coze client through the access_token. - CozeAPI coze = new CozeAPI.Builder() - .baseURL(System.getenv("COZE_API_BASE")) - .auth(authCli) - .readTimeout(10000) - .build();; - - Long datasetID = Long.parseLong(System.getenv("DATASET_ID")); - - ListDocumentReq req = ListDocumentReq.builder() - .size(2) - .datasetID(datasetID) - .page(1) - .build(); - - // you can use iterator to automatically retrieve next page - PageResp documents = coze.datasets().documents().list(req); - Iterator iter = documents.getIterator(); - iter.forEachRemaining(System.out::println); - - // the page result will return followed information - System.out.println("total: " + documents.getTotal()); - System.out.println("has_more: " + documents.getHasMore()); - System.out.println("logID: " + documents.getLogID()); - for (Document item : documents.getItems()) { - System.out.println(item); - } + public static void main(String[] args) { + // Get an access_token through personal access token or oauth. + String token = System.getenv("COZE_API_TOKEN"); + TokenAuth authCli = new TokenAuth(token); + + // Init the Coze client through the access_token. + CozeAPI coze = + new CozeAPI.Builder() + .baseURL(System.getenv("COZE_API_BASE")) + .auth(authCli) + .readTimeout(10000) + .build(); + ; + + Long datasetID = Long.parseLong(System.getenv("DATASET_ID")); + + ListDocumentReq req = ListDocumentReq.builder().size(2).datasetID(datasetID).page(1).build(); + + // you can use iterator to automatically retrieve next page + PageResp documents = coze.datasets().documents().list(req); + Iterator iter = documents.getIterator(); + iter.forEachRemaining(System.out::println); + + // the page result will return followed information + System.out.println("total: " + documents.getTotal()); + System.out.println("has_more: " + documents.getHasMore()); + System.out.println("logID: " + documents.getLogID()); + for (Document item : documents.getItems()) { + System.out.println(item); } + } } diff --git a/example/src/main/java/example/file/FileExample.java b/example/src/main/java/example/file/FileExample.java index 296fe488..1d6f8c9f 100644 --- a/example/src/main/java/example/file/FileExample.java +++ b/example/src/main/java/example/file/FileExample.java @@ -1,34 +1,38 @@ +/* (C)2024 */ package example.file; -import com.coze.openapi.client.files.model.FileInfo; import com.coze.openapi.client.files.RetrieveFileReq; import com.coze.openapi.client.files.UploadFileReq; -import com.coze.openapi.service.service.CozeAPI; +import com.coze.openapi.client.files.model.FileInfo; import com.coze.openapi.service.auth.TokenAuth; +import com.coze.openapi.service.service.CozeAPI; public class FileExample { - public static void main(String[] args) { - String token = System.getenv("COZE_API_TOKEN"); - TokenAuth authCli = new TokenAuth(token); - CozeAPI coze = new CozeAPI.Builder() - .baseURL(System.getenv("COZE_API_BASE")) - .auth(authCli) - .readTimeout(10000) - .build();; - String filePath = System.getenv("FILE_PATH"); - - //*** 上传文件 ***// - FileInfo fileInfo = coze.files().upload(UploadFileReq.of(filePath)).getFileInfo(); + public static void main(String[] args) { + String token = System.getenv("COZE_API_TOKEN"); + TokenAuth authCli = new TokenAuth(token); + CozeAPI coze = + new CozeAPI.Builder() + .baseURL(System.getenv("COZE_API_BASE")) + .auth(authCli) + .readTimeout(10000) + .build(); + ; + String filePath = System.getenv("FILE_PATH"); - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } + // *** 上传文件 ***// + FileInfo fileInfo = coze.files().upload(UploadFileReq.of(filePath)).getFileInfo(); - //*** 获取文件 ***// - FileInfo retrievedInfo = coze.files().retrieve(RetrieveFileReq.of(fileInfo.getID())).getFileInfo(); - System.out.println(retrievedInfo); + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); } -} \ No newline at end of file + + // *** 获取文件 ***// + FileInfo retrievedInfo = + coze.files().retrieve(RetrieveFileReq.of(fileInfo.getID())).getFileInfo(); + System.out.println(retrievedInfo); + } +} diff --git a/example/src/main/java/example/service/GetLogExample.java b/example/src/main/java/example/service/GetLogExample.java index 51f04ace..b282cbef 100644 --- a/example/src/main/java/example/service/GetLogExample.java +++ b/example/src/main/java/example/service/GetLogExample.java @@ -1,37 +1,38 @@ +/* (C)2024 */ package example.service; import com.coze.openapi.client.bots.RetrieveBotReq; import com.coze.openapi.client.bots.RetrieveBotResp; import com.coze.openapi.client.exception.CozeApiExcetion; -import com.coze.openapi.client.workspace.ListWorkspaceReq; import com.coze.openapi.service.auth.TokenAuth; import com.coze.openapi.service.service.CozeAPI; /* - * For all SDK methods that request the OpenAPI, the request logID is encapsulated + * For all SDK methods that request the OpenAPI, the request logID is encapsulated * and returned to developers. Developers can directly call the getLogID method to obtain it. */ public class GetLogExample { - public static void main(String[] args) { - - String token = System.getenv("COZE_API_TOKEN"); - TokenAuth authCli = new TokenAuth(token); + public static void main(String[] args) { - // Init the Coze client through the access_token. - CozeAPI coze = new CozeAPI.Builder() - .baseURL(System.getenv("COZE_API_BASE")) - .auth(authCli) - .readTimeout(10000) - .build(); + String token = System.getenv("COZE_API_TOKEN"); + TokenAuth authCli = new TokenAuth(token); - try { - RetrieveBotResp resp = coze.bots().retrieve(RetrieveBotReq.of("botID")); - /* - * For all response objects, you can get the request logID by calling the getLogID method. - */ - System.out.println(resp.getLogID()); - } catch (CozeApiExcetion e) { - System.out.println(e.getLogID()); - } + // Init the Coze client through the access_token. + CozeAPI coze = + new CozeAPI.Builder() + .baseURL(System.getenv("COZE_API_BASE")) + .auth(authCli) + .readTimeout(10000) + .build(); + + try { + RetrieveBotResp resp = coze.bots().retrieve(RetrieveBotReq.of("botID")); + /* + * For all response objects, you can get the request logID by calling the getLogID method. + */ + System.out.println(resp.getLogID()); + } catch (CozeApiExcetion e) { + System.out.println(e.getLogID()); } + } } diff --git a/example/src/main/java/example/service/HandlerExceptionExample.java b/example/src/main/java/example/service/HandlerExceptionExample.java index d5babc70..1b9a4da9 100644 --- a/example/src/main/java/example/service/HandlerExceptionExample.java +++ b/example/src/main/java/example/service/HandlerExceptionExample.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package example.service; import com.coze.openapi.client.exception.CozeApiExcetion; @@ -7,35 +8,36 @@ import com.coze.openapi.service.service.CozeAPI; public class HandlerExceptionExample { - public static void main(String[] args) { + public static void main(String[] args) { - // Using the request to get workspace list as an example + // Using the request to get workspace list as an example - String token = System.getenv("COZE_API_TOKEN"); - TokenAuth authCli = new TokenAuth(token); + String token = System.getenv("COZE_API_TOKEN"); + TokenAuth authCli = new TokenAuth(token); - // Init the Coze client through the access_token. - CozeAPI coze = new CozeAPI.Builder() - .baseURL(System.getenv("COZE_API_BASE")) - .auth(authCli) - .readTimeout(10000) - .build(); + // Init the Coze client through the access_token. + CozeAPI coze = + new CozeAPI.Builder() + .baseURL(System.getenv("COZE_API_BASE")) + .auth(authCli) + .readTimeout(10000) + .build(); - try { - coze.workspaces().list(ListWorkspaceReq.of(1, 10)); - } catch (CozeApiExcetion e) { - /* - * You can locate error information based on the code in the exception, see the meaning of codes at: - * cn: https://www.coze.cn/docs/developer_guides/coze_error_codes - * en: https://www.coze.com/docs/developer_guides/coze_error_codes - */ - System.out.println(e.getMessage()); - /* - * you can get request log id by getLogID() method - */ - System.out.println(e.getLogID()); - } catch (CozeAuthException e){ + try { + coze.workspaces().list(ListWorkspaceReq.of(1, 10)); + } catch (CozeApiExcetion e) { + /* + * You can locate error information based on the code in the exception, see the meaning of codes at: + * cn: https://www.coze.cn/docs/developer_guides/coze_error_codes + * en: https://www.coze.com/docs/developer_guides/coze_error_codes + */ + System.out.println(e.getMessage()); + /* + * you can get request log id by getLogID() method + */ + System.out.println(e.getLogID()); + } catch (CozeAuthException e) { - } } + } } diff --git a/example/src/main/java/example/service/InitClientExample.java b/example/src/main/java/example/service/InitClientExample.java index 147ee117..4dcdb6c0 100644 --- a/example/src/main/java/example/service/InitClientExample.java +++ b/example/src/main/java/example/service/InitClientExample.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package example.service; import org.slf4j.LoggerFactory; @@ -9,64 +10,67 @@ import okhttp3.OkHttpClient; public class InitClientExample { - public static void main(String[] args) { - // Get an access_token through personal access token or oauth. - String token = System.getenv("COZE_API_TOKEN"); - TokenAuth authCli = new TokenAuth(token); + public static void main(String[] args) { + // Get an access_token through personal access token or oauth. + String token = System.getenv("COZE_API_TOKEN"); + TokenAuth authCli = new TokenAuth(token); - /* - * Build with custom okhttp client - * - * Coze client built on okhttp, and supports passing a custom okhttp client. when initialzing Coze. - * Even if you pass a custom okhttp client, the Coze client will still use the a default interceptor - * to pass the access token to the server. - */ - CozeAPI coze = new CozeAPI.Builder() - .baseURL(System.getenv("COZE_API_BASE")) - .auth(authCli) - .client(new OkHttpClient.Builder().build()) - .build(); - - /* - * set custom timeout - * - * You can set the read timeout, write timeout, and connection timeout for the Coze client. - * You can directly set the timeout when initializing the Coze client, set it by your okhttp client - */ - coze = new CozeAPI.Builder() - .baseURL(System.getenv("COZE_API_BASE")) - .auth(authCli) - .readTimeout(10000) - .connectTimeout(10000) - .build(); + /* + * Build with custom okhttp client + * + * Coze client built on okhttp, and supports passing a custom okhttp client. when initialzing Coze. + * Even if you pass a custom okhttp client, the Coze client will still use the a default interceptor + * to pass the access token to the server. + */ + CozeAPI coze = + new CozeAPI.Builder() + .baseURL(System.getenv("COZE_API_BASE")) + .auth(authCli) + .client(new OkHttpClient.Builder().build()) + .build(); - /* - * set custom logger - * - * Coze client built on retrofit, and uses slf4j as the logging framework. - * You can set a custom logger when initializing the Coze client. - */ + /* + * set custom timeout + * + * You can set the read timeout, write timeout, and connection timeout for the Coze client. + * You can directly set the timeout when initializing the Coze client, set it by your okhttp client + */ + coze = + new CozeAPI.Builder() + .baseURL(System.getenv("COZE_API_BASE")) + .auth(authCli) + .readTimeout(10000) + .connectTimeout(10000) + .build(); - coze = new CozeAPI.Builder() - .baseURL(System.getenv("COZE_API_BASE")) - .auth(authCli) - .readTimeout(10000) - .connectTimeout(10000) - .logger(LoggerFactory.getLogger(CozeAPI.class)) - .build(); - - /* - * set base url - * - * Coze client will request www.coze.com by default. - * If you want to request the cn environment, you can set the base url to https://www.coze.cn. - */ - coze = new CozeAPI.Builder() - .baseURL(Consts.COZE_CN_BASE_URL) - .auth(authCli) - .readTimeout(10000) - .connectTimeout(10000) - .build(); - } - + /* + * set custom logger + * + * Coze client built on retrofit, and uses slf4j as the logging framework. + * You can set a custom logger when initializing the Coze client. + */ + + coze = + new CozeAPI.Builder() + .baseURL(System.getenv("COZE_API_BASE")) + .auth(authCli) + .readTimeout(10000) + .connectTimeout(10000) + .logger(LoggerFactory.getLogger(CozeAPI.class)) + .build(); + + /* + * set base url + * + * Coze client will request www.coze.com by default. + * If you want to request the cn environment, you can set the base url to https://www.coze.cn. + */ + coze = + new CozeAPI.Builder() + .baseURL(Consts.COZE_CN_BASE_URL) + .auth(authCli) + .readTimeout(10000) + .connectTimeout(10000) + .build(); + } } diff --git a/example/src/main/java/example/service/SetRequestTimeoutExample.java b/example/src/main/java/example/service/SetRequestTimeoutExample.java index 20e94107..c023e491 100644 --- a/example/src/main/java/example/service/SetRequestTimeoutExample.java +++ b/example/src/main/java/example/service/SetRequestTimeoutExample.java @@ -1,6 +1,6 @@ +/* (C)2024 */ package example.service; - import com.coze.openapi.client.bots.RetrieveBotReq; import com.coze.openapi.client.bots.RetrieveBotResp; import com.coze.openapi.client.bots.model.Bot; @@ -8,36 +8,35 @@ import com.coze.openapi.service.service.CozeAPI; public class SetRequestTimeoutExample { - public static void main(String[] args) { - String token = System.getenv("COZE_API_TOKEN"); - TokenAuth authCli = new TokenAuth(token); - - CozeAPI coze = new CozeAPI.Builder() - .baseURL(System.getenv("COZE_API_BASE")) - .auth(authCli) - // the developer able to set global request timeout when initializing the client - .readTimeout(1000) - .connectTimeout(2000) - .build(); - - - String botID = System.getenv("COZE_BOT_ID"); - - /* - * retrieve a bot - * */ - RetrieveBotReq req = RetrieveBotReq - .builder() - .botID(botID) - // when the developer want to request, they are able to sent request timout for any request - .connectTimeout(1000) - .readTimeout(3000) - .build(); - RetrieveBotResp botInfo = coze.bots().retrieve(req); - Bot bot = botInfo.getBot(); - System.out.println(bot); - System.out.println(botInfo.getLogID()); - - - } + public static void main(String[] args) { + String token = System.getenv("COZE_API_TOKEN"); + TokenAuth authCli = new TokenAuth(token); + + CozeAPI coze = + new CozeAPI.Builder() + .baseURL(System.getenv("COZE_API_BASE")) + .auth(authCli) + // the developer able to set global request timeout when initializing the client + .readTimeout(1000) + .connectTimeout(2000) + .build(); + + String botID = System.getenv("COZE_BOT_ID"); + + /* + * retrieve a bot + * */ + RetrieveBotReq req = + RetrieveBotReq.builder() + .botID(botID) + // when the developer want to request, they are able to sent request timout for any + // request + .connectTimeout(1000) + .readTimeout(3000) + .build(); + RetrieveBotResp botInfo = coze.bots().retrieve(req); + Bot bot = botInfo.getBot(); + System.out.println(bot); + System.out.println(botInfo.getLogID()); + } } diff --git a/example/src/main/java/example/workflow/AsyncRunWorkflowExample.java b/example/src/main/java/example/workflow/AsyncRunWorkflowExample.java index 4e70d038..ef9c870e 100644 --- a/example/src/main/java/example/workflow/AsyncRunWorkflowExample.java +++ b/example/src/main/java/example/workflow/AsyncRunWorkflowExample.java @@ -1,5 +1,10 @@ +/* (C)2024 */ package example.workflow; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; + import com.coze.openapi.client.workflows.run.RetrieveRunHistoryReq; import com.coze.openapi.client.workflows.run.RetrieveRunHistoryResp; import com.coze.openapi.client.workflows.run.RunWorkflowReq; @@ -9,66 +14,69 @@ import com.coze.openapi.service.auth.TokenAuth; import com.coze.openapi.service.service.CozeAPI; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.TimeUnit; - public class AsyncRunWorkflowExample { - public static void main(String[] args) { - // Get an access_token through personal access token or oauth. - String token = System.getenv("COZE_API_TOKEN"); - TokenAuth authCli = new TokenAuth(token); + public static void main(String[] args) { + // Get an access_token through personal access token or oauth. + String token = System.getenv("COZE_API_TOKEN"); + TokenAuth authCli = new TokenAuth(token); - // Init the Coze client through the access_token. - CozeAPI coze = new CozeAPI.Builder() - .baseURL(System.getenv("COZE_API_BASE")) - .auth(authCli) - .readTimeout(10000) - .build();; + // Init the Coze client through the access_token. + CozeAPI coze = + new CozeAPI.Builder() + .baseURL(System.getenv("COZE_API_BASE")) + .auth(authCli) + .readTimeout(10000) + .build(); + ; - String workflowID = System.getenv("WORKFLOW_ID"); + String workflowID = System.getenv("WORKFLOW_ID"); - // if your workflow need input params, you can send them by map - Map data = new HashMap<>(); - data.put("param name", "param values"); + // if your workflow need input params, you can send them by map + Map data = new HashMap<>(); + data.put("param name", "param values"); - RunWorkflowReq req = RunWorkflowReq.builder() - .workflowID(workflowID) - .parameters(data) - // if you want the workflow run asynchronously, you must set isAsync to true. - .isAsync(true) - .build(); + RunWorkflowReq req = + RunWorkflowReq.builder() + .workflowID(workflowID) + .parameters(data) + // if you want the workflow run asynchronously, you must set isAsync to true. + .isAsync(true) + .build(); - /* - Call the coze.workflows().runs().run() method to create a workflow run. The create method - is a non-streaming chat and will return a WorkflowRunResult class. - * */ - RunWorkflowResp resp = coze.workflows().runs().create(req); - System.out.println("Start async workflow run:" + resp.getExecuteID()); + /* + Call the coze.workflows().runs().run() method to create a workflow run. The create method + is a non-streaming chat and will return a WorkflowRunResult class. + * */ + RunWorkflowResp resp = coze.workflows().runs().create(req); + System.out.println("Start async workflow run:" + resp.getExecuteID()); - String executeID = resp.getExecuteID(); - boolean isFinished = false; + String executeID = resp.getExecuteID(); + boolean isFinished = false; - while(!isFinished){ - RetrieveRunHistoryResp historyResp = coze.workflows().runs().histories().retrieve(RetrieveRunHistoryReq.of(workflowID, executeID)); - System.out.println(historyResp); - WorkflowRunHistory history = historyResp.getHistories().get(0); - if (history.getExecuteStatus().equals(WorkflowExecuteStatus.FAIL)) { - System.out.println("Workflow run failed, reason:" + history.getErrorMessage()); - isFinished = true; - break; - } else if (history.getExecuteStatus().equals(WorkflowExecuteStatus.RUNNING)) { - System.out.println("Workflow run is running"); - try { - TimeUnit.SECONDS.sleep(1); - } catch (Exception e) { - e.printStackTrace(); - } - } else { - System.out.println("Workflow run success" + history.getOutput()); - isFinished = true; - break; - } + while (!isFinished) { + RetrieveRunHistoryResp historyResp = + coze.workflows() + .runs() + .histories() + .retrieve(RetrieveRunHistoryReq.of(workflowID, executeID)); + System.out.println(historyResp); + WorkflowRunHistory history = historyResp.getHistories().get(0); + if (history.getExecuteStatus().equals(WorkflowExecuteStatus.FAIL)) { + System.out.println("Workflow run failed, reason:" + history.getErrorMessage()); + isFinished = true; + break; + } else if (history.getExecuteStatus().equals(WorkflowExecuteStatus.RUNNING)) { + System.out.println("Workflow run is running"); + try { + TimeUnit.SECONDS.sleep(1); + } catch (Exception e) { + e.printStackTrace(); } + } else { + System.out.println("Workflow run success" + history.getOutput()); + isFinished = true; + break; + } } + } } diff --git a/example/src/main/java/example/workflow/RunWorkflowExample.java b/example/src/main/java/example/workflow/RunWorkflowExample.java index 602bb1c7..17816347 100644 --- a/example/src/main/java/example/workflow/RunWorkflowExample.java +++ b/example/src/main/java/example/workflow/RunWorkflowExample.java @@ -1,40 +1,41 @@ +/* (C)2024 */ package example.workflow; -import com.coze.openapi.client.workflows.run.RunWorkflowReq; -import com.coze.openapi.client.workflows.run.RunWorkflowResp; -import com.coze.openapi.service.service.CozeAPI; -import com.coze.openapi.service.auth.TokenAuth; - import java.util.HashMap; import java.util.Map; +import com.coze.openapi.client.workflows.run.RunWorkflowReq; +import com.coze.openapi.client.workflows.run.RunWorkflowResp; +import com.coze.openapi.service.auth.TokenAuth; +import com.coze.openapi.service.service.CozeAPI; /* This example describes how to use the workflow interface to chat. * */ public class RunWorkflowExample { - public static void main(String[] args) { - // Get an access_token through personal access token or oauth. - String token = System.getenv("COZE_API_TOKEN"); - TokenAuth authCli = new TokenAuth(token); - - // Init the Coze client through the access_token. - CozeAPI coze = new CozeAPI.Builder() - .baseURL(System.getenv("COZE_API_BASE")) - .auth(authCli) - .readTimeout(10000) - .build();; - - String workflowID = System.getenv("WORKFLOW_ID"); - - // if your workflow need input params, you can send them by map - Map data = new HashMap<>(); - data.put("param name", "param values"); - RunWorkflowReq req = RunWorkflowReq.builder().workflowID(workflowID).parameters(data).build(); - - RunWorkflowResp resp = coze.workflows().runs().create(req); - System.out.println(resp); - - } -} \ No newline at end of file + public static void main(String[] args) { + // Get an access_token through personal access token or oauth. + String token = System.getenv("COZE_API_TOKEN"); + TokenAuth authCli = new TokenAuth(token); + + // Init the Coze client through the access_token. + CozeAPI coze = + new CozeAPI.Builder() + .baseURL(System.getenv("COZE_API_BASE")) + .auth(authCli) + .readTimeout(10000) + .build(); + ; + + String workflowID = System.getenv("WORKFLOW_ID"); + + // if your workflow need input params, you can send them by map + Map data = new HashMap<>(); + data.put("param name", "param values"); + RunWorkflowReq req = RunWorkflowReq.builder().workflowID(workflowID).parameters(data).build(); + + RunWorkflowResp resp = coze.workflows().runs().create(req); + System.out.println(resp); + } +} diff --git a/example/src/main/java/example/workflow/StreamWorkflowExample.java b/example/src/main/java/example/workflow/StreamWorkflowExample.java index 68672dd1..22a26182 100644 --- a/example/src/main/java/example/workflow/StreamWorkflowExample.java +++ b/example/src/main/java/example/workflow/StreamWorkflowExample.java @@ -1,70 +1,78 @@ +/* (C)2024 */ package example.workflow; +import java.util.HashMap; +import java.util.Map; + import com.coze.openapi.client.workflows.run.ResumeRunReq; import com.coze.openapi.client.workflows.run.RunWorkflowReq; import com.coze.openapi.client.workflows.run.model.WorkflowEvent; import com.coze.openapi.client.workflows.run.model.WorkflowEventType; import com.coze.openapi.service.auth.TokenAuth; import com.coze.openapi.service.service.CozeAPI; -import io.reactivex.Flowable; -import java.util.HashMap; -import java.util.Map; +import io.reactivex.Flowable; /* This example describes how to use the workflow interface to stream chat. */ public class StreamWorkflowExample { - public static void main(String[] args) { - // Get an access_token through personal access token or oauth. - String token = System.getenv("COZE_API_TOKEN"); - TokenAuth authCli = new TokenAuth(token); + public static void main(String[] args) { + // Get an access_token through personal access token or oauth. + String token = System.getenv("COZE_API_TOKEN"); + TokenAuth authCli = new TokenAuth(token); - // Init the Coze client through the access_token. - CozeAPI coze = new CozeAPI.Builder() - .baseURL(System.getenv("COZE_API_BASE")) - .auth(authCli) - .readTimeout(10000) - .build(); + // Init the Coze client through the access_token. + CozeAPI coze = + new CozeAPI.Builder() + .baseURL(System.getenv("COZE_API_BASE")) + .auth(authCli) + .readTimeout(10000) + .build(); - String workflowID = System.getenv("WORKFLOW_ID"); + String workflowID = System.getenv("WORKFLOW_ID"); - // if your workflow need input params, you can send them by map - Map data = new HashMap<>(); - data.put("A", "param values"); + // if your workflow need input params, you can send them by map + Map data = new HashMap<>(); + data.put("A", "param values"); - RunWorkflowReq req = RunWorkflowReq.builder().workflowID(workflowID).parameters(data).build(); + RunWorkflowReq req = RunWorkflowReq.builder().workflowID(workflowID).parameters(data).build(); - Flowable flowable = coze.workflows().runs().stream(req); - handleEvent(flowable, coze, workflowID); - } + Flowable flowable = coze.workflows().runs().stream(req); + handleEvent(flowable, coze, workflowID); + } - /* - * The stream interface will return an iterator of WorkflowEvent. Developers should iterate - * through this iterator to obtain WorkflowEvent and handle them separately according to - * the type of WorkflowEvent. - */ - private static void handleEvent(Flowable events, CozeAPI coze, String workflowID){ - events.subscribe(event -> { - if (event.getEvent().equals(WorkflowEventType.MESSAGE)) { - System.out.println("Got message" + event.getMessage()); - } else if (event.getEvent().equals(WorkflowEventType.ERROR)) { - System.out.println("Got error" + event.getError()); - } else if (event.getEvent().equals(WorkflowEventType.DONE)) { - System.out.println("Got message" + event.getMessage()); - } else if (event.getEvent().equals(WorkflowEventType.INTERRUPT)) { - handleEvent(coze.workflows().runs().resume( + /* + * The stream interface will return an iterator of WorkflowEvent. Developers should iterate + * through this iterator to obtain WorkflowEvent and handle them separately according to + * the type of WorkflowEvent. + */ + private static void handleEvent(Flowable events, CozeAPI coze, String workflowID) { + events.subscribe( + event -> { + if (event.getEvent().equals(WorkflowEventType.MESSAGE)) { + System.out.println("Got message" + event.getMessage()); + } else if (event.getEvent().equals(WorkflowEventType.ERROR)) { + System.out.println("Got error" + event.getError()); + } else if (event.getEvent().equals(WorkflowEventType.DONE)) { + System.out.println("Got message" + event.getMessage()); + } else if (event.getEvent().equals(WorkflowEventType.INTERRUPT)) { + handleEvent( + coze.workflows() + .runs() + .resume( ResumeRunReq.builder() - .workflowID(workflowID) - .eventID(event.getInterrupt().getInterruptData().getEventID()) - .resumeData("your data") - .interruptType(event.getInterrupt().getInterruptData().getType()) - .build()), coze, workflowID); - } - }, Throwable::printStackTrace); - coze.shutdownExecutor(); - } - + .workflowID(workflowID) + .eventID(event.getInterrupt().getInterruptData().getEventID()) + .resumeData("your data") + .interruptType(event.getInterrupt().getInterruptData().getType()) + .build()), + coze, + workflowID); + } + }, + Throwable::printStackTrace); + coze.shutdownExecutor(); + } } - diff --git a/example/src/main/java/example/workspace/WorkspaceListExample.java b/example/src/main/java/example/workspace/WorkspaceListExample.java index c4ba983b..96256935 100644 --- a/example/src/main/java/example/workspace/WorkspaceListExample.java +++ b/example/src/main/java/example/workspace/WorkspaceListExample.java @@ -1,3 +1,4 @@ +/* (C)2024 */ package example.workspace; import java.util.Iterator; @@ -5,34 +6,35 @@ import com.coze.openapi.client.common.pagination.PageResp; import com.coze.openapi.client.workspace.ListWorkspaceReq; import com.coze.openapi.client.workspace.model.Workspace; -import com.coze.openapi.service.service.CozeAPI; import com.coze.openapi.service.auth.TokenAuth; +import com.coze.openapi.service.service.CozeAPI; public class WorkspaceListExample { - public static void main(String[] args) { - // Get an access_token through personal access token or oauth. - String token = System.getenv("COZE_API_TOKEN"); - TokenAuth authCli = new TokenAuth(token); + public static void main(String[] args) { + // Get an access_token through personal access token or oauth. + String token = System.getenv("COZE_API_TOKEN"); + TokenAuth authCli = new TokenAuth(token); - // Init the Coze client through the access_token. - CozeAPI coze = new CozeAPI.Builder() - .baseURL(System.getenv("COZE_API_BASE")) - .auth(authCli) - .readTimeout(10000) - .build(); + // Init the Coze client through the access_token. + CozeAPI coze = + new CozeAPI.Builder() + .baseURL(System.getenv("COZE_API_BASE")) + .auth(authCli) + .readTimeout(10000) + .build(); - // you can use iterator to automatically retrieve next page - PageResp workspaces = coze.workspaces().list(new ListWorkspaceReq()); - Iterator iter = workspaces.getIterator(); - iter.forEachRemaining(System.out::println); + // you can use iterator to automatically retrieve next page + PageResp workspaces = coze.workspaces().list(new ListWorkspaceReq()); + Iterator iter = workspaces.getIterator(); + iter.forEachRemaining(System.out::println); - // the page result will return followed information - System.out.println("total: " + workspaces.getTotal()); - System.out.println("has_more: " + workspaces.getHasMore()); - System.out.println("logID: " + workspaces.getLogID()); - for (Workspace item : workspaces.getItems()) { - System.out.println(item); - } + // the page result will return followed information + System.out.println("total: " + workspaces.getTotal()); + System.out.println("has_more: " + workspaces.getHasMore()); + System.out.println("logID: " + workspaces.getLogID()); + for (Workspace item : workspaces.getItems()) { + System.out.println(item); } -} \ No newline at end of file + } +} From ed8931806290986148b46c35fcc144d3e7c301f9 Mon Sep 17 00:00:00 2001 From: gouqinggan Date: Thu, 12 Dec 2024 15:52:09 +0800 Subject: [PATCH 2/8] fix checkstyle Change-Id: I84f97a74cd2550947d90f471931c508be4bd0441 --- config/checkstyle/checkstyle.xml | 71 ++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 config/checkstyle/checkstyle.xml diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml new file mode 100644 index 00000000..c925e078 --- /dev/null +++ b/config/checkstyle/checkstyle.xml @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file From ff9fa4a679c0690e4e93543cd90cc7f6e9452168 Mon Sep 17 00:00:00 2001 From: gouqinggan Date: Thu, 12 Dec 2024 16:11:57 +0800 Subject: [PATCH 3/8] fix checkstyle Change-Id: I7144fc1ad31f41636e261760dfce740476ea84a0 --- .github/workflows/ci.yml | 5 +++-- README.md | 12 ++++++------ config/checkstyle/checkstyle.xml | 9 +++++++++ 3 files changed, 18 insertions(+), 8 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 87a17635..0b0de0d2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,9 +2,10 @@ name: CI on: push: - branches: [ main, master ] + branches: + - main pull_request: - branches: [ main, master ] + merge_group: jobs: build: diff --git a/README.md b/README.md index e1e91013..1a0b9425 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ Please store it in a secure environment to prevent this personal access token from being disclosed. ```java -public voic example() { +public void example() { // Get an access_token through personal access token or oauth. String token = System.getenv("COZE_API_TOKEN"); TokenAuth authCli = new TokenAuth(token); @@ -85,7 +85,7 @@ polling, and obtaining the messages of the chat. Developers can use createAndPol simplify the process. ```java -public voic example() throws Exception { +public void example() throws Exception { String token = System.getenv("COZE_API_TOKEN"); String botID = System.getenv("PUBLISHED_BOT_ID"); String uid = System.getenv("USER_ID"); @@ -119,7 +119,7 @@ chat event and handle them. ```java -public voic example() { +public void example() { String token = System.getenv("COZE_API_TOKEN"); String botID = System.getenv("PUBLISHED_BOT_ID"); String userID = System.getenv("USER_ID"); @@ -151,7 +151,7 @@ public voic example() { You can create, update, publish and get the list of bots via api. ```java -public voic example() { +public void example() { // Get an access_token through personal access token or oauth. String token = System.getenv("COZE_API_TOKEN"); TokenAuth authCli = new TokenAuth(token); @@ -218,7 +218,7 @@ etc. on conversations. ```java -public voic example() { +public void example() { // Get an access_token through personal access token or oauth. String token = System.getenv("COZE_API_TOKEN"); TokenAuth authCli = new TokenAuth(token); @@ -291,7 +291,7 @@ Coze enables users to upload pictures and files. The uploaded pictures and files can be utilized in the bot avatar and multimodal conversations. ```java -public voic example() { +public void example() { String token = System.getenv("COZE_API_TOKEN"); TokenAuth authCli = new TokenAuth(token); CozeAPI coze = new CozeAPI.Builder() diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml index c925e078..a8698545 100644 --- a/config/checkstyle/checkstyle.xml +++ b/config/checkstyle/checkstyle.xml @@ -13,6 +13,10 @@ + + + + @@ -67,5 +71,10 @@ + + + + + \ No newline at end of file From 8c32b790f24ac8a635024afa9e708e178d6ef111 Mon Sep 17 00:00:00 2001 From: gouqinggan Date: Thu, 12 Dec 2024 16:15:16 +0800 Subject: [PATCH 4/8] remove checkstyle Change-Id: Iaa9ebe1af2e712356ee5522cea36a30d24fd13a8 --- .github/workflows/ci.yml | 1 - build.gradle | 7 --- config/checkstyle/checkstyle.xml | 80 -------------------------------- 3 files changed, 88 deletions(-) delete mode 100644 config/checkstyle/checkstyle.xml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0b0de0d2..69833fbc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -27,7 +27,6 @@ jobs: - name: Code style check run: | ./gradlew spotlessCheck - ./gradlew checkstyleMain - name: Build and Test run: ./gradlew build test diff --git a/build.gradle b/build.gradle index fbf43cf9..fa65fef5 100644 --- a/build.gradle +++ b/build.gradle @@ -32,7 +32,6 @@ subprojects { options.compilerArgs << "-Xlint:deprecation" } apply plugin: 'com.diffplug.spotless' - apply plugin: 'checkstyle' spotless { java { @@ -45,12 +44,6 @@ subprojects { } } - checkstyle { - toolVersion = '8.45.1' // 使用支持 Java 8 的版本 - configFile = file("${rootDir}/config/checkstyle/checkstyle.xml") - maxWarnings = 0 - } - jacocoTestReport { reports { xml.required = true // 生成 XML 报告供 Codecov 使用 diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml deleted file mode 100644 index a8698545..00000000 --- a/config/checkstyle/checkstyle.xml +++ /dev/null @@ -1,80 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file From 8c3d8e0e2b1051bceb6d9546c4d3d68b27ef6460 Mon Sep 17 00:00:00 2001 From: gouqinggan Date: Thu, 12 Dec 2024 16:23:40 +0800 Subject: [PATCH 5/8] fix test error Change-Id: I947be72f9eb67508b5172999f1a696c46798f7b3 --- api/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/build.gradle b/api/build.gradle index a0438b77..db25ef71 100644 --- a/api/build.gradle +++ b/api/build.gradle @@ -25,7 +25,7 @@ dependencies { testImplementation 'org.mockito:mockito-junit-jupiter:4.11.0' testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.2' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.2' - testImplementation 'ch.qos.logback:logback-classic:1.4.11' + testImplementation 'ch.qos.logback:logback-classic:1.2.3' testImplementation 'com.squareup.retrofit2:retrofit-mock:2.9.0' } From 05c624ac75433031298e2be96fac2c214fb44f2f Mon Sep 17 00:00:00 2001 From: gouqinggan Date: Thu, 12 Dec 2024 16:24:45 +0800 Subject: [PATCH 6/8] fix test error Change-Id: I3ef141a97eb5b2c25b07d5f2f7ad2f87cdaf86de --- README.md | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 1a0b9425..42ff5665 100644 --- a/README.md +++ b/README.md @@ -19,10 +19,10 @@ your projects. | Example | File | |-------------------------------|-------------------------------------------------------------------------------------------------------------| | pat auth | [TokenAuthExample.java](example/src/main/java/example/auth/TokenAuthExample.java) | -| oauth by web code | [WebOAuthExample.java](example/src/main/java/example/auth/WebOAuthExample.java) | -| oauth by jwt flow | [JWTsOauthExample.java](example/src/main/java/example/auth/JWTOAuthExample.java) | -| oauth by pkce flow | [PKCEOauthExample.java](example/src/main/java/example/auth/PKCEOAuthExample.java) | -| oauth by device flow | [DevicesOAuthExample.java](example/src/main/java/example/auth/DevicesOAuthExample.java) | +| oAuth by web code | [WebOAuthExample.java](example/src/main/java/example/auth/WebOAuthExample.java) | +| oAuth by jwt flow | [JWTsOauthExample.java](example/src/main/java/example/auth/JWTOAuthExample.java) | +| oAuth by pkce flow | [PKCEOauthExample.java](example/src/main/java/example/auth/PKCEOAuthExample.java) | +| oAuth by device flow | [DevicesOAuthExample.java](example/src/main/java/example/auth/DevicesOAuthExample.java) | | handle auth exception | [HandlerExceptionExample.java](example/src/main/java/example/auth/HandlerExceptionExample.java) | | bot create, publish and chat | [PublishBotExample.java](example/src/main/java/example/bot/PublishBotExample.java) | | get bot and bot list | [GetBotExample.java](example/src/main/java/example/bot/GetBotExample.java) | @@ -455,7 +455,7 @@ to avoid leakage. cozeAPIBase = Consts.COZE_COM_BASE_URL; } - WebOAuthClient oauth = new WebOAuthClient.WebOAuthBuilder() + WebOAuthClient oAuth = new WebOAuthClient.WebOAuthBuilder() .clientID(clientID) .clientSecret(clientSecret) .baseURL(cozeAPIBase) @@ -530,23 +530,23 @@ keep it securely to avoid leakage. String jwtOauthPrivateKey = System.getenv("COZE_JWT_OAUTH_PRIVATE_KEY"); String jwtOauthPrivateKeyFilePath = System.getenv("COZE_JWT_OAUTH_PRIVATE_KEY_FILE_PATH"); String jwtOauthPublicKeyID = System.getenv("COZE_JWT_OAUTH_PUBLIC_KEY_ID"); - JWTOAuthClient oauth = null; + JWTOAuthClient oAuth = null; try { jwtOauthPrivateKey = new String(Files.readAllBytes(Paths.get(jwtOauthPrivateKeyFilePath)), StandardCharsets.UTF_8); } catch (IOException e) { e.printStackTrace(); } /* - The jwt oauth type requires using private to be able to issue a jwt token, and through + The jwt oAuth type requires using private to be able to issue a jwt token, and through the jwt token, apply for an access_token from the coze service. The sdk encapsulates this procedure, and only needs to use get_access_token to obtain the access_token under - the jwt oauth process. + the jwt oAuth process. Generate the authorization token The default ttl is 900s, and developers can customize the expiration time, which can be set up to 24 hours at most. * */ try { - oauth = new JWTOAuthClient.JWTOAuthBuilder() + oAuth = new JWTOAuthClient.JWTOAuthBuilder() .clientID(jwtOauthClientID) .privateKey(jwtOauthPrivateKey) .publicKey(jwtOauthPublicKeyID) @@ -559,11 +559,11 @@ keep it securely to avoid leakage. } ``` -The jwt oauth type requires using private to be able to issue a jwt token, and through +The jwt oAuth type requires using private to be able to issue a jwt token, and through the jwt token, apply for an access_token from the coze service. The sdk encapsulates this procedure, and only needs to use get_access_token to obtain -the access_token under the jwt oauth process. +the access_token under the jwt oAuth process. ```java # The jwt process does not require any other operations, you can directly apply for a token @@ -606,14 +606,14 @@ After the creation is completed, three parameters, namely the client ID can be o if(cozeAPIBase==null|| cozeAPIBase.isEmpty()){ cozeAPIBase = Consts.COZE_COM_BASE_URL; } - PKCEOAuthClient oauth = new PKCEOAuthClient.PKCEOAuthBuilder() + PKCEOAuthClient oAuth = new PKCEOAuthClient.PKCEOAuthBuilder() .clientID(clientID) .baseURL(cozeAPIBase) .build(); } ``` -In the pkce oauth process, first, need to select a suitable code_challenge_method. +In the pkce oAuth process, first, need to select a suitable code_challenge_method. Coze supports two types: plain and s256. Then, based on the selected code_challenge_method type, hash the code_verifier into @@ -683,14 +683,14 @@ After the creation is completed, three parameters, namely the client ID can be o if(cozeAPIBase==null|| cozeAPIBase.isEmpty()){ cozeAPIBase = Consts.COZE_COM_BASE_URL; } - DeviceOAuthClient oauth = new DeviceOAuthClient.DeviceOAuthBuilder() + DeviceOAuthClient oAuth = new DeviceOAuthClient.DeviceOAuthBuilder() .clientID(clientID) .baseURL(cozeAPIBase) .build(); } ``` -In the device oauth authorization process, developers need to first call the interface +In the device oAuth authorization process, developers need to first call the interface of Coze to generate the device code to obtain the user_code and device_code. Then generate the authorization link through the user_code, guide the user to open the From 689aaefbc356c19f655af2a08e6a4b620b52971c Mon Sep 17 00:00:00 2001 From: gouqinggan Date: Thu, 12 Dec 2024 17:07:08 +0800 Subject: [PATCH 7/8] fix code conv Change-Id: I4fa412928110521a3267207888e48f53f62a6148 --- api/build.gradle | 16 ++++++++++++++++ build.gradle | 15 ++------------- 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/api/build.gradle b/api/build.gradle index db25ef71..096a1f51 100644 --- a/api/build.gradle +++ b/api/build.gradle @@ -1,5 +1,6 @@ plugins { id 'java-library' + id 'jacoco' } dependencies { @@ -29,6 +30,21 @@ dependencies { testImplementation 'com.squareup.retrofit2:retrofit-mock:2.9.0' } +jacoco { + toolVersion = "0.8.7" +} + +jacocoTestReport { + reports { + xml.required = true + csv.required = true + } +} + +test { + finalizedBy jacocoTestReport // 测试完成后自动生成报告 +} + test { useJUnitPlatform() } diff --git a/build.gradle b/build.gradle index fa65fef5..9a56bf93 100644 --- a/build.gradle +++ b/build.gradle @@ -1,6 +1,5 @@ plugins { id 'com.diffplug.spotless' version '6.11.0' apply false - id 'jacoco' } allprojects { @@ -13,6 +12,7 @@ allprojects { mavenCentral() gradlePluginPortal() } + } @@ -43,15 +43,4 @@ subprojects { licenseHeader '/* (C)$YEAR */' } } - - jacocoTestReport { - reports { - xml.required = true // 生成 XML 报告供 Codecov 使用 - html.required = true // 可选:生成 HTML 报告便于本地查看 - } - } - - test { - finalizedBy jacocoTestReport // 测试完成后自动生成报告 - } -} \ No newline at end of file +} From 6f872716a67adbf368c549cd5ee7302ef0b045a1 Mon Sep 17 00:00:00 2001 From: gouqinggan Date: Thu, 12 Dec 2024 17:37:38 +0800 Subject: [PATCH 8/8] fix ci conf Change-Id: Idcf71d0d7326c9a0a373f6e6f8a3cc0638720fe0 --- .github/workflows/ci.yml | 25 ++++++++++++++++--------- .github/workflows/required-labels.yml | 25 +++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 9 deletions(-) create mode 100644 .github/workflows/required-labels.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 69833fbc..821a2c5b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -8,18 +8,25 @@ on: merge_group: jobs: - build: - runs-on: ubuntu-latest + test: + runs-on: ${{ matrix.os }} + name: test (Java ${{ matrix.java-version }} on ${{ matrix.os-label }}) + strategy: + fail-fast: false + matrix: + java-version: [ "8", "11", "17" ] + os: [ "ubuntu-latest" ] + os-label: [ "Ubuntu" ] + include: + - { java-version: "11", os: "windows-latest", os-label: "Windows" } + - { java-version: "11", os: "macos-latest", os-label: "macOS" } steps: - - uses: actions/checkout@v3 - - - name: Set up JDK - uses: actions/setup-java@v3 + - uses: actions/checkout@v2 + - name: Set up JDK ${{ matrix.java-version }} + uses: actions/setup-java@v1 with: - java-version: '8' - distribution: 'temurin' - cache: gradle + java-version: ${{ matrix.java-version }} - name: Grant execute permission for gradlew run: chmod +x gradlew diff --git a/.github/workflows/required-labels.yml b/.github/workflows/required-labels.yml new file mode 100644 index 00000000..c0329e02 --- /dev/null +++ b/.github/workflows/required-labels.yml @@ -0,0 +1,25 @@ +name: Required Labels +on: + pull_request: + types: [opened, labeled, unlabeled, synchronize] +jobs: + label: + runs-on: ubuntu-latest + permissions: + issues: write + pull-requests: write + steps: + - uses: mheap/github-action-required-labels@v5 + with: + mode: minimum + count: 1 + labels: | + feature + enhancement + fix + bugfix + bug + chore + documentation + add_comment: true + message: "Requires label: feature, enhancement, fix, bugfix, bug, chore, documentation." \ No newline at end of file