### Build Coze Java Project with Maven Source: https://github.com/coze-dev/coze-java/blob/main/CONTRIBUTING.md This command cleans the project and installs all dependencies and the built artifact. It is executed in the project root directory. ```shell mvn clean install ``` -------------------------------- ### Format Coze Java Code with Maven Spotless Source: https://github.com/coze-dev/coze-java/blob/main/CONTRIBUTING.md This command applies code formatting according to the project's configured style (Google Java Style). It ensures code consistency across the project. ```shell mvn spotless:apply ``` -------------------------------- ### Initialize JWTOAuthClient with Custom JWT Builder (Java) Source: https://github.com/coze-dev/coze-java/blob/main/README.md Example of initializing the JWTOAuthClient in Java, demonstrating how to set the private key, public key ID, client ID, base URL, and crucially, a custom JWT builder. This setup is essential for authenticating with the Coze API using JWT. ```java JWTOAuthClient oauth = (new JWTOAuthClient.JWTOAuthBuilder()) .privateKey(config.getPrivateKey()) .publicKey(config.getPublicKeyId()) .clientID(config.getClientId()) .baseURL(config.getCozeApiBase()) .jwtBuilder(new ExampleJWTBuilder()) // set your jwt builder .build(); ``` -------------------------------- ### Create and Publish Bot Programmatically Source: https://context7.com/coze-dev/coze-java/llms.txt This example shows how to programmatically create a new bot, including uploading an avatar, configuring its prompt and onboarding messages, and then publishing it to the API channel. It utilizes the Coze API client for these operations. ```java import com.coze.openapi.client.bots.*; import com.coze.openapi.client.bots.model.*; import com.coze.openapi.client.files.UploadFileReq; import com.coze.openapi.client.files.UploadFileResp; import com.coze.openapi.service.auth.TokenAuth; import com.coze.openapi.service.service.CozeAPI; import java.util.Arrays; public class BotCreateExample { public static void main(String[] args) { String token = System.getenv("COZE_API_TOKEN"); String workspaceID = System.getenv("WORKSPACE_ID"); CozeAPI coze = new CozeAPI.Builder() .baseURL(System.getenv("COZE_API_BASE")) .auth(new TokenAuth(token)) .readTimeout(10000) .build(); // Upload bot avatar String avatarPath = "/path/to/avatar.jpg"; UploadFileResp avatarInfo = coze.files().upload(UploadFileReq.of(avatarPath)); // Configure bot prompt and onboarding BotPromptInfo promptInfo = new BotPromptInfo( "You are a helpful assistant that provides accurate information." ); BotOnboardingInfo onboardingInfo = BotOnboardingInfo.builder() .prologue("Hello! I'm here to help you.") .suggestedQuestions(Arrays.asList( "What can you help me with?", "How does this work?" )) .build(); // Create bot request CreateBotReq createReq = CreateBotReq.builder() .spaceID(workspaceID) .name("Customer Support Bot") .description("A bot that answers customer questions") .promptInfo(promptInfo) .onboardingInfo(onboardingInfo) .iconFileID(avatarInfo.getFileInfo().getID()) .build(); // Create the bot CreateBotResp createResp = coze.bots().create(createReq); String botID = createResp.getBotID(); System.out.println("Bot created with ID: " + botID); // Publish bot to API channel PublishBotReq publishReq = PublishBotReq.builder() .botID(botID) .connectorIDs(Arrays.asList("1024")) .build(); PublishBotResp publishResp = coze.bots().publish(publishReq); System.out.println("Bot published successfully"); } } ``` -------------------------------- ### Run Tests and Generate Jacoco Report with Maven Source: https://github.com/coze-dev/coze-java/blob/main/CONTRIBUTING.md This command runs tests for the 'api' module and generates a JaCoCo code coverage report. It's a crucial step before committing to ensure code quality and test coverage. ```shell mvn -pl api test jacoco:report ``` -------------------------------- ### Iterate Bots with Coze Java SDK Paginator Source: https://github.com/coze-dev/coze-java/blob/main/README.md This example demonstrates how to list bots within a space using the Coze Java SDK's paginator functionality. It illustrates manual pagination by repeatedly calling the API and mentions the SDK's built-in iterator support. Requires COZE_API_TOKEN, COZE_API_BASE, and WORKSPACE_ID environment variables. ```java 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();; Integer pageNum = 1; String workspaceID = System.getenv("WORKSPACE_ID"); ListBotReq listBotReq = ListBotReq.builder() .spaceID(workspaceID) .pageNum(pageNum) .pageSize(10) .build(); PageResult botList = coze.bots().list(listBotReq); // the api provides two ways for developers to turn pages for all paging interfaces. // 1. The first way is to let developers manually call the API to request the next page. while (botList.getHasMore()) { pageNum++; listBotReq.setPageNum(pageNum); botList = coze.bots().list(listBotReq); } // 2. The SDK encapsulates an iterator, which can be used to turn pages backward automatically. ``` -------------------------------- ### Stream Chat Messages with Coze Java SDK Source: https://github.com/coze-dev/coze-java/blob/main/README.md This example shows how to initiate a chat session with a Coze bot in streaming mode. It handles incoming chat events, printing message deltas and completion details. Requires COZE_API_TOKEN, PUBLISHED_BOT_ID, USER_ID, and COZE_API_BASE environment variables. ```java 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. * */ ChatReq req = ChatReq.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()); } }); ``` -------------------------------- ### Manage Datasets with Coze Java SDK Source: https://github.com/coze-dev/coze-java/blob/main/README.md Provides examples for managing documents within a dataset using the Coze Java SDK. This includes creating documents from web pages or local files, updating existing documents, deleting documents, and listing documents within a dataset. It requires COZE_API_TOKEN, COZE_API_BASE, and DATASET_ID environment variables. ```java 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")); /* * create document in to specific dataset * */ CreateDocumentReq createReq = CreateDocumentReq.builder() .datasetID(datasetID) .documentBases(Arrays.asList( DocumentBase.buildWebPage("web doc example", "https://your-website.com"), //create datasets documents by web page DocumentBase.buildLocalFile("file doc example", "your file content", "txt"))) //create datasets documents by local file .build(); CreateDocumentResp creatResp = coze.datasets().documents().create(createReq); 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(); coze.datasets().documents().update(updateReq); /* * delete document. It means success that no exception has been thrown * */ coze.datasets().documents().delete(DeleteDocumentReq.builder().documentIDs(Collections.singletonList(documentIDs.get(0))).build()); /* * list documents * */ ListDocumentReq req = ListDocumentReq.builder() .size(2) .datasetID(datasetID) .page(1) .build(); // you can use iterator to automatically retrieve next page PageResult documents = coze.datasets().documents().list(req); Iterator iter = documents.getIterator(); iter.forEachRemaining(System.out::println); } ``` -------------------------------- ### Stream Workflow Execution with Coze Java SDK Source: https://github.com/coze-dev/coze-java/blob/main/README.md This example demonstrates how to execute a Coze workflow in streaming mode and handle its events. It supports sending input parameters and resuming interrupted workflows. Requires COZE_API_TOKEN, COZE_API_BASE, and WORKSPACE_ID environment variables. ```java public void streamRun() { // 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("WORKSPACE_ID"); // if your workflow need input params, you can send them by map Map data = new HashMap<>(); data.put("param name", "param values"); RunWorkflowReq.RunWorkflowReqBuilder builder = RunWorkflowReq.builder(); builder.workflowID(workflowID).parameters(data); Flowable flowable = coze.workflows().runs().stream(builder.build()); handleEvent(flowable, coze, workflowID); } private void handleEvent(Flowable events, CozeAPI coze, String workflowID) { events.subscribe(event -> { switch (event.getEvent()) { case MESSAGE: System.out.println("Got message" + event.getMessage()); break; case ERROR: System.out.println("Got error" + event.getError()); break; case 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); break; default: break; } }, Throwable::printStackTrace); } ``` -------------------------------- ### Initialize Coze Device OAuth Client in Java Source: https://github.com/coze-dev/coze-java/blob/main/README.md Initializes the Device OAuth client for Coze. It retrieves the client ID and base URL from environment variables, defaulting to coze.com if not specified. This setup is crucial before initiating the device authorization flow. ```java public void initOAuthClient() { 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; } DeviceOAuthClient oauth = new DeviceOAuthClient.DeviceOAuthBuilder() .clientID(clientID) .baseURL(cozeAPIBase) .build(); } ``` -------------------------------- ### Add Maven Dependency for Coze Java Project Source: https://github.com/coze-dev/coze-java/blob/main/CONTRIBUTING.md This XML snippet shows how to declare a new dependency in the Maven project's configuration file (likely pom.xml). Ensure you replace placeholders with actual artifact details. ```xml com.example example version ``` -------------------------------- ### Perform Stream Chat with Coze SDK Source: https://github.com/coze-dev/coze-java/blob/main/README.md Demonstrates how to perform a streaming chat operation using the Coze Java SDK. This example uses `coze.chat().stream()` to establish a streaming session and processes chat events as they arrive, including message deltas and completion notifications. ```java public void example() { 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); CozeAPI coze = new CozeAPI.Builder() .baseURL(System.getenv("COZE_API_BASE")) .auth(authCli) .build(); ChatReq req = ChatReq.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()); } }); } ``` -------------------------------- ### WebSocket Speech Synthesis with Coze in Java Source: https://github.com/coze-dev/coze-java/blob/main/README.md Enables real-time text-to-speech conversion using WebSocket. This example configures audio output parameters such as voice ID, codec, and speech rate, then sends text to be synthesized. Synthesized audio data is received via a callback. ```java WebsocketAudioSpeechClient client = coze.websocket() .audio() .speech() .create(new WebsocketAudioSpeechCreateReq(new CallbackHandler())); // Configure audio output OutputAudio outputAudio = OutputAudio.builder() .voiceId(voiceID) .codec("pcm") .speechRate(50) .pcmConfig(PCMConfig.builder().sampleRate(24000).build()) .build(); client.speechUpdate(new SpeechUpdateEventData(outputAudio)); // Send text for synthesis client.inputTextBufferAppend("Hello world!"); client.inputTextBufferComplete(); // Handle synthesized audio in callback class CallbackHandler extends WebsocketAudioSpeechCallbackHandler { @Override public void onSpeechAudioUpdate(WebsocketAudioSpeechClient client, SpeechAudioUpdateEvent event) { byte[] audioData = event.getDelta(); // Process audio data... } } ``` -------------------------------- ### WebSocket Chat with Audio Support in Java Source: https://context7.com/coze-dev/coze-java/llms.txt Enables real-time, bidirectional chat communication using WebSocket connections for low-latency interactions, including audio data transmission. It requires environment variables for the API token and bot ID. The example sets up a WebSocket client with a callback handler to process incoming messages and audio data. ```java import com.coze.openapi.client.websocket.chat.*; import com.coze.openapi.service.auth.TokenAuth; import com.coze.openapi.service.service.CozeAPI; public class WebSocketChatExample { public static void main(String[] args) { String token = System.getenv("COZE_API_TOKEN"); String botID = System.getenv("PUBLISHED_BOT_ID"); CozeAPI coze = new CozeAPI.Builder() .baseURL(System.getenv("COZE_API_BASE")) .auth(new TokenAuth(token)) .build(); // Create WebSocket chat client with callback handler WebsocketChatClient client = coze.websocket() .chat() .create(new WebsocketChatCreateReq(botID, new ChatCallbackHandler())); // Send audio data (base64 encoded) String audioData = "base64_encoded_audio_data_here"; client.inputAudioBufferAppend(audioData); client.inputAudioBufferComplete(); // Keep connection alive try { Thread.sleep(30000); // Wait for responses } catch (InterruptedException e) { e.printStackTrace(); } finally { client.close(); coze.shutdownExecutor(); } } // Callback handler for WebSocket events static class ChatCallbackHandler extends WebsocketChatCallbackHandler { @Override public void onConversationMessageDelta( WebsocketChatClient client, ConversationMessageDeltaEvent event) { System.out.print(event.getData().getContent()); } @Override public void onConversationAudioDelta( WebsocketChatClient client, ConversationAudioDeltaEvent event) { byte[] audioData = event.getData().getAudio(); System.out.println("Received audio chunk: " + audioData.length + " bytes"); // Process audio data (e.g., play or save) } @Override public void onError(WebsocketChatClient client, Throwable error) { System.err.println("WebSocket error: " + error.getMessage()); } } } ``` -------------------------------- ### Create, Update, and Publish Bots with Coze Java SDK Source: https://github.com/coze-dev/coze-java/blob/main/README.md This Java code snippet demonstrates the full lifecycle of a bot using the Coze SDK. It covers initializing the client, creating a bot with a prompt, onboarding info, and an avatar, then updating the avatar and republishing the bot. Dependencies include the Coze SDK and standard Java libraries. Inputs are environment variables for API token, base URL, workspace ID, and local file paths for avatars. Outputs include bot IDs and publish status. ```java 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); // Init the Coze client through the access_token. CozeAPI coze = new CozeAPI.Builder() .baseURL(System.getenv("COZE_API_BASE")) .auth(authCli) .build(); /* * step one, create a bot * */ String workspaceID = System.getenv("WORKSPACE_ID"); // set the prompt of your bot BotPromptInfo promptInfo = new BotPromptInfo("your prompt"); // 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 = "/path/avatar.jpg"; FileInfo avatarInfo = coze.files().upload(avatarPath); // 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.getID()) .build(); // Invoke the creation interface to create a bot in the draft status, and you can get the bot id. String botID = coze.bots().create(createReq).getBotID(); /* * step two, update the bot, you can update the bot after being created * in this example, we will update the avatar of the bot */ // Call the publishing interface to publish the bot on the api channel. PublishBotResult updateResp = coze.bots().publish(PublishBotReq.of(botID)); /* * step three, you can also modify the bot configuration and republish it. * in this example, we will update the avatar of the bot */ // set the onboarding info of your bot // Call the upload file interface to get the avatar id. String newAvatarPath = "/path/new_avatar.jpg"; FileInfo newAvatarInfo = coze.files().upload(newAvatarPath); // build the request UpdateBotReq updateReq = UpdateBotReq.builder() .botID(botID) .iconFileID(newAvatarInfo.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(PublishBotReq.of(botID)); } ``` -------------------------------- ### List Bots with Pagination Source: https://github.com/coze-dev/coze-java/blob/main/README.md Demonstrates how to initialize the Coze client, list bots with pagination, and iterate through the results. ```APIDOC ## List Bots with Pagination ### Description This endpoint allows you to retrieve a list of bots, supporting pagination for efficient data retrieval. ### Method GET ### Endpoint `/bots` ### Parameters #### Query Parameters - **pageNum** (Integer) - Required - The page number to retrieve. - **pageSize** (Integer) - Required - The number of bots per page. - **spaceID** (String) - Required - The ID of the workspace to list bots from. ### Request Example ```java 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();; Integer pageNum = 1; String workspaceID = System.getenv("WORKSPACE_ID"); ListBotReq listBotReq = ListBotReq.builder() .spaceID(workspaceID) .pageNum(pageNum) .pageSize(10) .build(); PageResult botList = coze.bots().list(listBotReq); // the api provides two ways for developers to turn pages for all paging interfaces. // 1. The first way is to let developers manually call the API to request the next page. Iterator iterator = botList.getIterator(); while (iterator.hasNext()) { iterator.forEachRemaining(System.out::println); } ``` ### Response #### Success Response (200) - **iterator** (Iterator) - An iterator to access the list of bots. #### Response Example ```json { "bots": [ { "id": "bot_id_1", "name": "Bot Name 1" }, { "id": "bot_id_2", "name": "Bot Name 2" } ] } ``` ``` -------------------------------- ### Get Access Token and Handle Coze OAuth Errors in Java Source: https://github.com/coze-dev/coze-java/blob/main/README.md Polls Coze's interface using the device code to obtain an access token. This snippet also demonstrates how to refresh the token and handle potential authentication exceptions such as 'AccessDenied' or 'ExpiredToken', guiding users to re-authorize if necessary. ```java try { OAuthToken resp = oauth.getAccessToken(codeResp.getDeviceCode()); 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) { switch (e.getCode()) { case AccessDenied: /* The user rejected the authorization. Developers need to guide the user to open the authorization link again. */ break; case ExpiredToken: /* The token has expired. Developers need to guide the user to open the authorization link again. */ default: e.printStackTrace(); break; } } catch (Exception e) { e.printStackTrace(); } ``` -------------------------------- ### Initialize PKCE OAuth Client (Java) Source: https://github.com/coze-dev/coze-java/blob/main/README.md Initializes the PKCE OAuth client using environment variables for client ID and API base URL. It supports both coze.com and coze.cn endpoints. Dependencies include the coze-java SDK. ```java public void initOAuthClient() { 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(); } ``` -------------------------------- ### Initialize JWTOAuthClient from Environment Variables (Java) Source: https://github.com/coze-dev/coze-java/blob/main/README.md Java code snippet demonstrating the initialization of the JWTOAuthClient by reading configuration values (client ID, private key, public key ID, Coze API base URL) from environment variables. It includes error handling for reading the private key from a file. ```java public void initOAuthClient() { 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(); } /* 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; } } ``` -------------------------------- ### Perform Non-Stream Chat with Coze SDK Source: https://github.com/coze-dev/coze-java/blob/main/README.md Illustrates how to perform a non-streaming chat operation using the Coze Java SDK. This example uses the `createAndPoll` method, which handles message polling automatically. It shows how to build the chat request, send it, and process the response, including token usage. ```java 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"); CozeAPI coze = new CozeAPI.Builder() .baseURL(System.getenv("COZE_API_BASE")) .auth(new TokenAuth(token)) .readTimeout(10000) .build(); ChatReq req = ChatReq.builder() .botID(botID) .userID(uid) .messages(Collections.singletonList(Message.buildUserQuestionText("What can you do?"))) .build(); ChatPoll chat = coze.chat().createAndPoll(req); for (Message message : chat.messages) { System.out.println(message.content); } if (chat.chat.status == ChatStatus.COMPLETED) { System.out.println("token usage:" + chat.chat.usage.tokenCount); } } ``` -------------------------------- ### Initialize Coze Client Source: https://context7.com/coze-dev/coze-java/llms.txt Initializes the Coze API client using Personal Access Token authentication. This is the first step to interact with the Coze API platform. ```APIDOC ## Initialize Coze Client ### Description Initializes the Coze API client with Personal Access Token authentication. This client is used to interact with the Coze API platform. ### Method N/A (Client Initialization) ### Endpoint N/A (Client Initialization) ### Parameters N/A (Client Initialization) ### Request Example ```java import com.coze.openapi.service.auth.TokenAuth; import com.coze.openapi.service.service.CozeAPI; import okhttp3.OkHttpClient; public class InitExample { public static void main(String[] args) { // Get access token from environment String token = System.getenv("COZE_API_TOKEN"); String baseUrl = System.getenv("COZE_API_BASE"); // Create authentication client TokenAuth authCli = new TokenAuth(token); // Initialize Coze API client with configuration CozeAPI coze = new CozeAPI.Builder() .baseURL(baseUrl != null ? baseUrl : "https://api.coze.com") .auth(authCli) .client(new OkHttpClient.Builder().build()) .readTimeout(10000) .build(); System.out.println("Coze client initialized successfully"); } } ``` ### Response N/A (Client Initialization returns no explicit response, but a successfully built client object) ``` -------------------------------- ### Upload Files with Coze API Java SDK Source: https://context7.com/coze-dev/coze-java/llms.txt Shows how to upload files using the Coze Java SDK, supporting uploads from file paths and byte arrays. It also demonstrates retrieving file metadata. This is useful for bot avatars and multimodal content. Requires COZE_API_TOKEN and COZE_API_BASE environment variables. ```java import com.coze.openapi.client.files.UploadFileReq; import com.coze.openapi.client.files.UploadFileResp; import com.coze.openapi.client.files.model.FileInfo; import com.coze.openapi.service.auth.TokenAuth; import com.coze.openapi.service.service.CozeAPI; public class FileUploadExample { public static void main(String[] args) { String token = System.getenv("COZE_API_TOKEN"); CozeAPI coze = new CozeAPI.Builder() .baseURL(System.getenv("COZE_API_BASE")) .auth(new TokenAuth(token)) .readTimeout(10000) .build(); // Upload file from path String filePath = "/path/to/document.pdf"; UploadFileResp uploadResp = coze.files().upload(UploadFileReq.of(filePath)); FileInfo fileInfo = uploadResp.getFileInfo(); System.out.println("File uploaded:"); System.out.println(" ID: " + fileInfo.getID()); System.out.println(" Name: " + fileInfo.getFileName()); System.out.println(" Size: " + fileInfo.getBytes() + " bytes"); // Upload from byte array byte[] fileData = new byte[1024]; // ... populate fileData ... FileInfo byteFileInfo = coze.files().upload(fileData); System.out.println("Byte array uploaded: " + byteFileInfo.getID()); // Retrieve file metadata FileInfo retrievedInfo = coze.files().retrieve(fileInfo.getID()); System.out.println("Retrieved file: " + retrievedInfo.getFileName()); } } ``` -------------------------------- ### Stream Workflow Run with Coze Java SDK Source: https://github.com/coze-dev/coze-java/blob/main/README.md Demonstrates how to initialize the Coze client and stream workflow runs. The code handles the iterator returned by the streaming interface and includes a placeholder for handling interrupt events, which occur when question-and-answer nodes are present. It requires COZE_API_TOKEN, COZE_API_BASE, and WORKSPACE_ID environment variables. ```java 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("WORKSPACE_ID"); // if your workflow need input params, you can send them by map Map data = new HashMap<>(); data.put("param name", "param values"); RunWorkflowReq.RunWorkflowReqBuilder builder = RunWorkflowReq.builder(); builder.workflowID(workflowID).parameters(data); Flowable flowable = coze.workflows().runs().stream(builder.build()); handleEvent(flowable, coze, workflowID); } ``` -------------------------------- ### Device Flow OAuth with Java Source: https://context7.com/coze-dev/coze-java/llms.txt Demonstrates how to authenticate devices with limited input capabilities using the OAuth device code and user verification flow. It requires environment variables for client ID and API base URL. The flow involves requesting a device code, prompting the user for verification, and then polling for an access token. ```java import com.coze.openapi.client.auth.DeviceAuthCode; import com.coze.openapi.client.auth.model.OAuthToken; import com.coze.openapi.client.exceptions.CozeAuthException; import com.coze.openapi.service.auth.DeviceOAuthClient; import com.coze.openapi.service.auth.TokenAuth; import com.coze.openapi.service.service.CozeAPI; public class DeviceOAuthExample { public static void main(String[] args) { String clientID = System.getenv("COZE_DEVICE_OAUTH_CLIENT_ID"); String baseURL = System.getenv("COZE_API_BASE"); // Initialize device OAuth client DeviceOAuthClient oauth = new DeviceOAuthClient.DeviceOAuthBuilder() .clientID(clientID) .baseURL(baseURL != null ? baseURL : "https://api.coze.com") .build(); // Request device code DeviceAuthCode deviceCode = oauth.getDeviceCode(); System.out.println("User verification required:"); System.out.println(" Visit: " + deviceCode.getVerificationUrl()); System.out.println(" Enter code: " + deviceCode.getUserCode()); System.out.println(" Expires in: " + deviceCode.getExpiresIn() + " seconds"); // Poll for access token (SDK handles polling automatically) try { OAuthToken token = oauth.getAccessToken(deviceCode.getDeviceCode()); System.out.println("Authorization successful!"); System.out.println("Access token: " + token.getAccessToken()); // Initialize Coze client CozeAPI coze = new CozeAPI.Builder() .auth(new TokenAuth(token.getAccessToken())) .baseURL(baseURL) .build(); // Refresh token when expired OAuthToken refreshed = oauth.refreshToken(token.getRefreshToken()); System.out.println("Token refreshed"); } catch (CozeAuthException e) { switch (e.getCode()) { case AccessDenied: System.err.println("User denied authorization"); break; case ExpiredToken: System.err.println("Device code expired, request new code"); break; default: e.printStackTrace(); } } } } ``` -------------------------------- ### Run Non-Stream Workflows in Coze using Java Source: https://github.com/coze-dev/coze-java/blob/main/README.md This Java code demonstrates how to run a non-stream Coze workflow. It shows how to initialize the Coze client, specify the workflow ID, and pass input parameters as a map. Authentication requires COZE_API_TOKEN and COZE_API_BASE environment variables, and the workflow ID is expected from the WORKSPACE_ID environment variable. ```java 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("WORKSPACE_ID"); // if your workflow need input params, you can send them by map Map data = new HashMap<>(); data.put("param name", "param values"); RunWorkflowReq.RunWorkflowReqBuilder builder = RunWorkflowReq.builder(); builder.workflowID(workflowID).parameters(data); RunWorkflowResp resp = coze.workflows().runs().run(builder.build()); System.out.println(resp); } ``` -------------------------------- ### Iterate Coze Bots using Paginator in Java Source: https://github.com/coze-dev/coze-java/blob/main/README.md Initializes the Coze client with API token and base URL, then lists bots within a specified workspace. It demonstrates iterating through the paginated results using a `while` loop and an `Iterator` to access each bot. ```java 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();; Integer pageNum = 1; String workspaceID = System.getenv("WORKSPACE_ID"); ListBotReq listBotReq = ListBotReq.builder() .spaceID(workspaceID) .pageNum(pageNum) .pageSize(10) .build(); PageResult botList = coze.bots().list(listBotReq); // the api provides two ways for developers to turn pages for all paging interfaces. // 1. The first way is to let developers manually call the API to request the next page. Iterator iterator = botList.getIterator(); while (iterator.hasNext()) { iterator.forEachRemaining(System.out::println); } ``` -------------------------------- ### Paginated List Operations with Java Source: https://context7.com/coze-dev/coze-java/llms.txt Demonstrates how to handle paginated lists of bots using the Coze Java SDK. It shows both manual pagination and automatic pagination with an iterator for efficient processing of large result sets. Requires COZE_API_TOKEN, WORKSPACE_ID, and COZE_API_BASE environment variables. ```java import com.coze.openapi.client.bots.*; import com.coze.openapi.client.bots.model.SimpleBot; import com.coze.openapi.client.common.pagination.PageResult; import com.coze.openapi.service.auth.TokenAuth; import com.coze.openapi.service.service.CozeAPI; import java.util.Iterator; public class PaginationExample { public static void main(String[] args) { String token = System.getenv("COZE_API_TOKEN"); String workspaceID = System.getenv("WORKSPACE_ID"); CozeAPI coze = new CozeAPI.Builder() .baseURL(System.getenv("COZE_API_BASE")) .auth(new TokenAuth(token)) .readTimeout(10000) .build(); // Method 1: Manual pagination Integer pageNum = 1; ListBotReq listReq = ListBotReq.builder() .spaceID(workspaceID) .pageNum(pageNum) .pageSize(10) .build(); PageResult botList = coze.bots().list(listReq); while (botList.getHasMore()) { for (SimpleBot bot : botList.getItems()) { System.out.println("Bot: " + bot.getBotName()); } pageNum++; listReq.setPageNum(pageNum); botList = coze.bots().list(listReq); } // Method 2: Automatic pagination with iterator listReq.setPageNum(1); PageResult result = coze.bots().list(listReq); Iterator iterator = result.getIterator(); // Automatically fetches next pages as needed iterator.forEachRemaining(bot -> System.out.println("Bot ID: " + bot.getBotID() + ", Name: " + bot.getBotName()) ); } } ``` -------------------------------- ### Audio Speech Synthesis using Coze Java SDK Source: https://context7.com/coze-dev/coze-java/llms.txt Demonstrates real-time text-to-speech conversion using the Coze Java SDK via WebSockets. It configures voice parameters, audio output settings (codec, speech rate, sample rate), and handles synthesized audio chunks. Requires COZE_API_TOKEN, VOICE_ID, and COZE_API_BASE environment variables. ```java import com.coze.openapi.client.websocket.audio.speech.*; import com.coze.openapi.client.audio.speech.model.*; import com.coze.openapi.service.auth.TokenAuth; import com.coze.openapi.service.service.CozeAPI; public class AudioSpeechExample { public static void main(String[] args) { String token = System.getenv("COZE_API_TOKEN"); String voiceID = System.getenv("VOICE_ID"); CozeAPI coze = new CozeAPI.Builder() .baseURL(System.getenv("COZE_API_BASE")) .auth(new TokenAuth(token)) .build(); // Create WebSocket speech synthesis client WebsocketAudioSpeechClient client = coze.websocket() .audio() .speech() .create(new WebsocketAudioSpeechCreateReq(new SpeechCallbackHandler())); // Configure audio output settings OutputAudio outputAudio = OutputAudio.builder() .voiceId(voiceID) .codec("pcm") .speechRate(50) // 0-100 scale .pcmConfig(PCMConfig.builder() .sampleRate(24000) .build()) .build(); client.speechUpdate(new SpeechUpdateEventData(outputAudio)); // Send text for synthesis String textToSpeak = "Hello! This is a test of the speech synthesis system."; client.inputTextBufferAppend(textToSpeak); client.inputTextBufferComplete(); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } finally { client.close(); coze.shutdownExecutor(); } } static class SpeechCallbackHandler extends WebsocketAudioSpeechCallbackHandler { @Override public void onSpeechAudioUpdate( WebsocketAudioSpeechClient client, SpeechAudioUpdateEvent event) { byte[] audioData = event.getDelta(); System.out.println("Synthesized audio chunk: " + audioData.length + " bytes"); // Process audio (e.g., stream to speaker) } @Override public void onError(WebsocketAudioSpeechClient client, Throwable error) { System.err.println("Speech synthesis error: " + error.getMessage()); } } } ``` -------------------------------- ### Initialize Web OAuth Client in Java Source: https://github.com/coze-dev/coze-java/blob/main/README.md Initializes the WebOAuthClient using environment variables for client ID, client secret, and the Coze API base URL. This client is essential for subsequent OAuth operations. Ensure sensitive credentials are kept secure. ```java public void initOAuthClient() { String clientSecret = System.getenv("COZE_WEB_OAUTH_CLIENT_SECRET"); String clientID = System.getenv("COZE_WEB_OAUTH_CLIENT_ID"); String cozeAPIBase = System.getenv("COZE_API_BASE"); if (cozeAPIBase == null || cozeAPIBase.isEmpty()) { cozeAPIBase = Consts.COZE_COM_BASE_URL; } WebOAuthClient oauth = new WebOAuthClient.WebOAuthBuilder() .clientID(clientID) .clientSecret(clientSecret) .baseURL(cozeAPIBase) .build(); } ``` -------------------------------- ### Audio Transcription using Coze Java SDK Source: https://context7.com/coze-dev/coze-java/llms.txt Demonstrates real-time speech-to-text conversion using the Coze Java SDK via WebSockets. It configures audio input settings (sample rate, codec, format, channel) and handles transcribed text updates. Requires COZE_API_TOKEN and COZE_API_BASE environment variables. ```java import com.coze.openapi.client.websocket.audio.transcriptions.*; import com.coze.openapi.client.audio.transcriptions.model.*; import com.coze.openapi.service.auth.TokenAuth; import com.coze.openapi.service.service.CozeAPI; public class AudioTranscriptionExample { public static void main(String[] args) { String token = System.getenv("COZE_API_TOKEN"); CozeAPI coze = new CozeAPI.Builder() .baseURL(System.getenv("COZE_API_BASE")) .auth(new TokenAuth(token)) .build(); // Create WebSocket transcription client WebsocketAudioTranscriptionsClient client = coze.websocket() .audio() .transcriptions() .create(new WebsocketAudioTranscriptionsCreateReq( new TranscriptionCallbackHandler() )); // Configure audio input settings InputAudio inputAudio = InputAudio.builder() .sampleRate(24000) .codec("pcm") .format("wav") .channel(2) .build(); client.transcriptionsUpdate(new TranscriptionsUpdateEventData(inputAudio)); // Send audio data for transcription (base64 encoded) String audioData = "base64_encoded_audio_data_here"; client.inputAudioBufferAppend(audioData); client.inputAudioBufferComplete(); try { Thread.sleep(15000); } catch (InterruptedException e) { e.printStackTrace(); } finally { client.close(); coze.shutdownExecutor(); } } static class TranscriptionCallbackHandler extends WebsocketAudioTranscriptionsCallbackHandler { @Override public void onTranscriptionsMessageUpdate( WebsocketAudioTranscriptionsClient client, TranscriptionsMessageUpdateEvent event) { String transcribedText = event.getData().getContent(); System.out.println("Transcription: " + transcribedText); } @Override public void onError( WebsocketAudioTranscriptionsClient client, Throwable error) { System.err.println("Transcription error: " + error.getMessage()); } } } ``` -------------------------------- ### Resource Cleanup Source: https://github.com/coze-dev/coze-java/blob/main/README.md Demonstrates proper resource cleanup for WebSocket clients and the Coze executor. ```APIDOC ## Resource Cleanup ### Description Ensures that all WebSocket clients and the underlying executor service are properly closed to prevent resource leaks. ### Method N/A (Code pattern) ### Endpoint N/A ### Parameters N/A ### Request Example ```java // Assume 'client' is an initialized WebSocket client (e.g., WebsocketChatClient) // Assume 'coze' is the initialized CozeAPI instance Object client = null; // Replace with your actual client variable try { // Use the client... // For example, initializing a client: // client = coze.websocket().chat().create(...); } finally { if (client != null) { // Assuming the client has a close() method // client.close(); } // Shutdown the executor service used by the Coze client if (coze != null) { coze.shutdownExecutor(); } } ``` ### Response N/A ```