Coze Java API SDK

repository·main·Indexed 42 days ago

https://github.com/coze-dev/coze-java

A Java library for integrating Coze's open APIs into applications. It supports synchronous and asynchronous calls, real-time streaming via RxJava Flowable, and optimized pagination. Key capabilities include bot lifecycle management (create, update, publish), conversation and message handling, workflow execution, dataset and document management, and file uploads.

Tokens
10.1K
Snippets
21
Records
22
Agent score
3%

What's inside Coze

  1. Key features of the Coze Java API SDK

    main

    The Coze Java API SDK is designed for seamless integration with Coze's open APIs. Key capabilities include:

    • Full API Support: Covers both open APIs and authentication APIs.
    • Execution Modes: Supports both synchronous and asynchronous SDK calls.
    • Optimized Streaming: Uses Stream object returns for streaming APIs.
    • Optimized Pagination: Uses Iterator Page object returns for list APIs.
    • Developer Experience: Simple and intuitive API design.
  2. Iterate over paginated results

    main

    All list interfaces in the SDK return a PageResult<T> object, which supports two ways of handling pagination:

    1. Manual Pagination: Check botList.getHasMore() and manually increment the pageNum in your request object to fetch the next page.
    2. Automatic Iterator: Use botList.getIterator() to get an Iterator<T>. This encapsulates the pagination logic, allowing you to iterate through all items across all pages automatically using standard iterator methods like hasNext() and next().
    // 1. Manual Pagination
    while (botList.getHasMore()) {
        pageNum++;
        listBotReq.setPageNum(pageNum);
        botList = coze.bots().list(listBotReq);
    }
    
    // 2. Automatic Iterator
    Iterator<SimpleBot> iterator = botList.getIterator();
    while (iterator.hasNext()) {
        iterator.forEachRemaining(System.out::println);
    }
  3. Install the Coze Java API SDK

    main

    To use the Coze Java API SDK in your project, add the com.coze:coze-api dependency using either Gradle or Maven. This SDK provides full support for Coze open APIs, authentication, and supports both synchronous and asynchronous calls, as well as optimized streaming and list APIs.

    ### Gradle
    ```groovy
    dependencies {
        implementation 'com.coze:coze-api:+'
    }

    Maven

    <dependency>
        <groupId>com.coze</groupId>
        <artifactId>coze-api</artifactId>
        <version>version</version>
    </dependency>
  4. Configure JWT OAuth Authentication

    main

    For Service applications, use JWT OAuth to issue a JWT token and exchange it for an access_token. You must provide a clientID, privateKey, and publicKeyID. If you have a custom JWT generation logic, you can implement the jwtBuilder interface and pass it to the JWTOAuthBuilder.

    To use the resulting token, pass it to a TokenAuth object when building your CozeAPI client.

    // 1. Initialize the JWT OAuth client
    JWTOAuthClient oauth = (new JWTOAuthClient.JWTOAuthBuilder())
                  .privateKey(config.getPrivateKey())
                  .publicKey(config.getPublicKeyId())
                  .clientID(config.getClientId())
                  .baseURL(config.getCozeApiBase())
                  .jwtBuilder(new ExampleJWTBuilder()) // custom builder if needed
                  .build();
    
    // 2. Get the access token (TTL can be up to 24 hours)
    OAuthToken resp = oauth.getAccessToken(3600);
    
    // 3. Initialize the Coze client with the token
    CozeAPI coze = new CozeAPI.Builder()
        .auth(new TokenAuth(resp.getAccessToken()))
        .baseURL(cozeAPIBase)
        .build();
  5. Configure PKCE OAuth Authentication

    main

    PKCE (Proof Key for Code Exchange) is used for public clients like mobile or single-page applications. The SDK automatically handles the code_challenge generation (supporting plain and s256 methods).

    Workflow:

    1. Initialize PKCEOAuthClient with your clientID.
    2. Generate an authorization URL using genOAuthURL.
    3. After the user consents and is redirected back to your redirectURI with a code, exchange that code for an access_token using getAccessToken.
    // 1. Initialize PKCE client
    PKCEOAuthClient oauth = new PKCEOAuthClient.PKCEOAuthBuilder()
            .clientID(clientID)
            .baseURL(cozeAPIBase)
            .build();
    
    // 2. Generate the authorization link
    PKCEAuthParam oauthURL = oauth.genOAuthURL(redirectURI, "state", PKCEOAuthClient.CodeChallengeMethod.S256);
    
    // 3. Exchange the code received from the redirect for a token
    OAuthToken resp = oauth.getAccessToken(code, redirectURI, "");
    
    // 4. Initialize Coze client
    CozeAPI coze = new CozeAPI.Builder()
        .auth(new TokenAuth(resp.getAccessToken()))
        .baseURL(cozeAPIBase)
        .build();
    
    // 5. Refresh token when expired
    resp = oauth.refreshToken(resp.getRefreshToken());
  6. Initialize the Coze Client

    main

    To use the SDK, you must first obtain a personal access token from the Coze dashboard (Global or CN). Use the CozeAPI.Builder to configure the client with your token, base URL, and an HTTP client (like OkHttp).

    Note: The default base URL is api.coze.com. If you are using the Chinese environment, you must explicitly set the baseURL to api.coze.cn.

    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);
        /*
         * The default access is api.coze.com, but if you need to access api.coze.cn
         * please use baseUrl to configure the API endpoint to access
         */
        String baseUrl = System.getenv("COZE_API_BASE");
        CozeAPI coze = new CozeAPI.Builder()
                .baseURL(baseUrl)
                .auth(authCli)
                .client(new OkHttpClient.Builder().build()) 
                .build();
    }
  7. Manage Bots (Create, Update, and Publish)

    main

    The SDK allows full lifecycle management of bots. The typical workflow involves:

    1. Uploading assets: Use coze.files().upload(path) to get a FileInfo object (e.g., for bot avatars).
    2. Creating a bot: Use coze.bots().create(CreateBotReq) with BotPromptInfo and BotOnboardingInfo to initialize a bot in draft status.
    3. Publishing: Use coze.bots().publish(PublishBotReq) to make the bot available on the API channel.
    4. Updating: Use coze.bots().update(UpdateBotReq) to modify configurations like the icon or prompt, then republish.
    public void example() {
        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)
                .build();
    
        String workspaceID = System.getenv("WORKSPACE_ID");
        BotPromptInfo promptInfo = new BotPromptInfo("your prompt");
        BotOnboardingInfo onboardingInfo = BotOnboardingInfo.builder()
                .prologue("the prologue of your bot")
                .suggestedQuestions(Arrays.asList("question 1", "question 2"))
                .build();
    
        String avatarPath = "/path/avatar.jpg";
        FileInfo avatarInfo = coze.files().upload(avatarPath);
    
        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();
    
        String botID = coze.bots().create(createReq).getBotID();
    
        PublishBotResult updateResp = coze.bots().publish(PublishBotReq.of(botID));
    
        String newAvatarPath = "/path/new_avatar.jpg";
        FileInfo newAvatarInfo = coze.files().upload(newAvatarPath);
    
        UpdateBotReq updateReq = UpdateBotReq.builder()
                .botID(botID)
                .iconFileID(newAvatarInfo.getID())
                .build();
    
        coze.bots().update(updateReq);
        updateResp = coze.bots().publish(PublishBotReq.of(botID));
    }
  8. Clean up WebSocket clients and executors

    main

    WebSocket clients and the Coze client's executor should be properly closed to prevent resource leaks. Always use a try-finally block to ensure client.close() is called and coze.shutdownExecutor() is executed.

    try {
        // Use the client...
    } finally {
        if (client != null) {
            client.close();
        }
        coze.shutdownExecutor();
    }
  9. Configure Device Flow OAuth Authentication

    main

    The Device Flow is intended for IoT devices, CLI tools, or devices with limited input capabilities.

    Workflow:

    1. Initialize DeviceOAuthClient.
    2. Call getDeviceCode() to receive a device_code and a verification_url.
    3. Guide the user to the verification_url to enter the user_code.
    4. Poll for the token using getAccessToken(deviceCode). The SDK handles the polling and error handling internally.

    Common CozeAuthException codes:

    • AccessDenied: User rejected authorization.
    • ExpiredToken: The token has expired.
    // 1. Initialize Device client
    DeviceOAuthClient oauth = new DeviceOAuthClient.DeviceOAuthBuilder()
        .clientID(clientID)
        .baseURL(cozeAPIBase)
        .build();
    
    // 2. Get device code and verification URL
    DeviceAuthCode codeResp = oauth.getDeviceCode();
    // Guide user to: codeResp.getDeviceCode().getVerificationUrl()
    
    // 3. Poll for access token
    try {
        OAuthToken resp = oauth.getAccessToken(codeResp.getDeviceCode());
        CozeAPI coze = new CozeAPI.Builder()
            .auth(new TokenAuth(resp.getAccessToken()))
            .baseURL(cozeAPIBase)
            .build();
    } catch (CozeAuthException e) {
        if (e.getCode() == AccessDenied) {
            // Handle rejection
        }
    }
  10. Manage Conversations and Messages

    main

    You can manage the lifecycle of a conversation and its messages using the coze.conversations() service. This includes creating conversations, retrieving them, appending messages (including text, images, and files), updating, deleting, and listing messages. The SDK provides a PageResult wrapper for paginated lists, which includes an Iterator for easy traversal.

    Key operations:

    • Create Conversation: coze.conversations().create(CreateConversationReq)
    • Append Message: coze.conversations().messages().create(CreateMessageReq)
    • List Messages: coze.conversations().messages().list(ListMessageReq)
    • Clear Conversation: coze.conversations().clear(ClearConversationReq)
    // Create conversation
    Conversation resp = coze.conversations().create(new CreateConversationReq());
    String conversationID = resp.getId();
    
    // Append message with multimodal content
    Message msgs = coze.conversations().messages().create(CreateMessageReq.builder()
            .conversationID(conversationID)
            .objectContent(Arrays.asList(
                    MessageObjectString.buildText("hello"),
                    MessageObjectString.buildImageByURL("https://example.com/image.png"),
                    MessageObjectString.buildFileByURL("https://example.com/file.pdf")))
            .build());
    
    // List messages with pagination
    PageResult<Message> messages = coze.conversations().messages().list(ListMessageReq.builder()
            .conversationID(conversationID)
            .limit(10)
            .build());
    Iterator<Message> iter = messages.getIterator();
    iter.forEachRemaining(System.out::println);
  11. Upload and Retrieve Files

    main

    The SDK supports uploading files and images, which can be used for bot avatars or multimodal conversations. You can upload files using a file path or a byte array. Once uploaded, you can retrieve file information using the file ID.

    // Upload file via path
    FileInfo fileInfo = coze.files().upload("/path/to/file.png");
    
    // Upload file via byte array
    FileInfo fileInfoBytes = coze.files().upload(new byte[1024]);
    
    // Retrieve file info
    FileInfo retrievedInfo = coze.files().retrieve(fileInfo.getID());
  12. Run Workflows (Non-stream and Stream)

    main

    You can directly invoke Coze workflows.

    1. Non-stream run: Use coze.workflows().runs().run(RunWorkflowReq) for standard execution. If the workflow requires input parameters, pass them as a Map<String, Object> via the parameters field.
    2. Stream run: Use coze.workflows().runs().stream(RunWorkflowReq) to receive a Flowable<WorkflowEvent>. This is useful for real-time updates. If a workflow contains question-and-answer nodes, the stream will emit an INTERRUPT event, requiring you to call the resume interface to continue.
    // Non-stream workflow run
    Map<String, Object> data = new HashMap<>();
    data.put("param_name", "value");
    RunWorkflowResp resp = coze.workflows().runs().run(RunWorkflowReq.builder()
        .workflowID("your_workflow_id")
        .parameters(data)
        .build());
    
    // Stream workflow run
    Flowable<WorkflowEvent> flowable = coze.workflows().runs().stream(RunWorkflowReq.builder()
        .workflowID("your_workflow_id")
        .parameters(data)
        .build());