Claude SDK for Java

repository·main·Indexed 43 days ago

https://github.com/anthropics/anthropic-sdk-java

A type-safe Java SDK for interacting with the Claude API. Supports Java 8+, provides an AnthropicClient for message creation, and includes comprehensive tools for managing deployments and deployment runs. Version 2.63.0 available via Gradle and Maven.

Tokens
6.5K
Snippets
20
Records
24
Agent score
54%

What's inside Claude SDK for Java

  1. Suppress detekt rule findings

    main

    There are two ways to handle detekt rule violations depending on whether the exemption is intentional or pre-existing:

    Permanent Exemptions

    For intentional, permanent exemptions (such as reflection contracts), use the @Suppress("RuleId") annotation directly on the code declaration. This keeps the reasoning for the suppression adjacent to the code.

    Pre-existing Violations

    For existing violations that you intend to fix later, use the detekt baseline files (config/detekt/baseline-*.xml). Do not hand-edit these files; instead, regenerate them using the provided scripts.

  2. Iterate on custom detekt rules

    main

    When developing or modifying custom detekt rules for the Anthropic Java SDK, use the following commands to run tests, regenerate baselines, or run the full linting suite:

    • Unit tests: Run only the unit tests for the rules module.
    • Regenerate baseline: Use this after editing rule code to update the violation baseline files.
    • Full lint: Runs ktfmt formatting followed by detektMain and detektTest.

    Always run ./scripts/detekt-baseline after rule changes to ensure the baseline matches the new rule logic.

    ./gradlew :anthropic-java-detekt-rules:test   # unit tests
    ./scripts/detekt-baseline                     # regenerate config/detekt/baseline-*.xml
    ./scripts/lint                                # ktfmt + detektMain + detektTest
  3. Get started with the Claude SDK

    main

    To use the SDK, initialize an AnthropicClient (using the OkHttp implementation) and use the messages() interface to create new messages. By default, AnthropicOkHttpClient.fromEnv() looks for the ANTHROPIC_API_KEY environment variable.

    import com.anthropic.client.AnthropicClient;
    import com.anthropic.client.okhttp.AnthropicOkHttpClient;
    import com.anthropic.models.messages.Message;
    import com.anthropic.models.messages.MessageCreateParams;
    import com.anthropic.models.messages.Model;
    
    // Configures using the `ANTHROPIC_API_KEY` environment variable
    AnthropicClient client = AnthropicOkHttpClient.fromEnv();
    
    MessageCreateParams params = MessageCreateParams.builder()
        .maxTokens(1024L)
        .addUserMessage("Hello, Claude")
        .model(Model.CLAUDE_OPUS_5)
        .build();
    Message message = client.messages().create(params);
  4. Add a new custom detekt rule

    main

    To implement a new custom detekt rule, follow these five steps in order:

    1. Create the rule class: Define your logic in src/main/kotlin/com/anthropic/detekt/YourRule.kt.
    2. Register the rule: Add the rule to AnthropicRuleSetProvider.kt (ensure entries are kept in alphabetical order).
    3. Set default configuration: Add an entry with active: true to src/main/resources/config/config.yml (alphabetical order).
    4. Enable in detekt: Enable the rule under the anthropic: section in config/detekt/detekt.yml, optionally adding excludes.
    5. Write a test: Create a test in AnthropicRulesTest.kt. If your rule requires type resolution, use compileAndLintWithContext(env, ...).

    Finally, run ./scripts/detekt-baseline to update the baselines and commit the changes.

  5. Paginate through Deployment Runs

    main

    When listing deployment runs using DeploymentRunService.list, the SDK returns a DeploymentRunListPage. This object represents a single page of results and provides several ways to navigate through the full set of deployment runs.

    1. Manual Pagination: Use hasNextPage() to check for more results and nextPage() to fetch the next DeploymentRunListPage.
    2. Automatic Pagination: Use autoPager() to obtain an AutoPager instance. This is the recommended way to iterate through all pages of results without manually managing cursors or page parameters.
    3. Accessing Data: Use items() or data() to retrieve the list of BetaManagedAgentsDeploymentRun objects contained in the current page.

    Key Methods

    • items(): List<BetaManagedAgentsDeploymentRun>: Returns the list of deployment runs on the current page.
    • hasNextPage(): Boolean: Returns true if there is a subsequent page available.
    • nextPage(): DeploymentRunListPage: Fetches the next page of results.
    • autoPager(): AutoPager<BetaManagedAgentsDeploymentRun>: Returns an abstraction for iterating over all pages automatically.
    // Example of manual pagination
    DeploymentRunListPage page = service.list(params);
    while (page.hasNextPage()) {
        System.out.println(page.items());
        page = page.nextPage();
    }
    
    // Example of automatic pagination
    page.autoPager().forEach(run -> {
        System.out.println(run);
    });
  6. Configure Beta Dream model parameters

    main

    Use BetaDreamModelConfigParam to specify the model identifier and inference speed for Beta Dream pipelines.

    Required fields:

    • id: The model identifier (e.g., "claude-opus-5"). Must be 1-256 characters.

    Optional fields:

    • speed: The inference speed mode. Speed.FAST provides significantly faster output token generation at premium pricing, but not all models support it.

    You can construct this object using the builder() or the of(id) convenience method.

    // Using the builder
    BetaDreamModelConfigParam config = BetaDreamModelConfigParam.builder()
        .id("claude-opus-5")
        .speed(BetaDreamModelConfigParam.Speed.FAST)
        .build();
    
    // Using the shorthand for required fields only
    BetaDreamModelConfigParam simpleConfig = BetaDreamModelConfigParam.of("claude-opus-5");
  7. Configure parameters for pausing a deployment

    main

    Use DeploymentPauseParams to specify the configuration required to pause an existing deployment. You can construct this object using the DeploymentPauseParams.builder() or by using DeploymentPauseParams.none() for an empty configuration.

    Key Parameters

    • deploymentId(String?): The unique identifier of the deployment to pause.
    • betas(List<AnthropicBeta>?): A list of beta versions to include in the request headers.
    • workspaceId(String?): The ID of the workspace associated with the deployment.

    Customizing the Request

    The builder allows for adding arbitrary metadata to the request:

    • Headers: Use putAdditionalHeader(name, value) to add custom HTTP headers.
    • Query Parameters: Use putAdditionalQueryParam(key, value) to add custom URL query parameters.
    • Body Properties: Use putAdditionalBodyProperty(key, value) to add extra JSON properties to the request body.
    val params = DeploymentPauseParams.builder()
        .deploymentId("dep_123")
        .workspaceId("ws_456")
        .addBeta(AnthropicBeta.of("some-beta-version"))
        .putAdditionalHeader("X-Custom-Header", "value")
        .build()
  8. Configure parameters for archiving a deployment

    main

    Use DeploymentArchiveParams.Builder to construct the parameters required for the deployment archive beta endpoint. You can specify the deployment ID, workspace ID, and any beta versions you wish to use via headers.

    Key fields include:

    • deploymentId: The unique identifier for the deployment.
    • betas: A list of AnthropicBeta constants to specify which beta features to enable.
    • workspaceId: The ID of the workspace associated with the request.

    You can also include custom headers, query parameters, and additional body properties using the builder's put or add methods.

    val params = DeploymentArchiveParams.builder()
        .deploymentId("deploy_123")
        .workspaceId("ws_456")
        .addBeta(AnthropicBeta.valueOf("some-beta-version"))
        .putAdditionalHeader("X-Custom-Header", "value")
        .build()
  9. Add custom headers and query parameters to deployment run requests

    main

    When building DeploymentRunListParams, you can inject additional headers or query parameters that are not explicitly covered by the standard API parameters.

    Additional Headers

    Use putAdditionalHeader(name, value), putAllAdditionalHeaders(map), or additionalHeaders(map) to add custom headers to the request.

    Additional Query Parameters

    Use putAdditionalQueryParam(key, value), putAllAdditionalQueryParams(map), or additionalQueryParams(map) to add custom query parameters to the request.

    val params = DeploymentRunListParams.builder()
        .putAdditionalHeader("X-Custom-Header", "value")
        .putAdditionalQueryParam("custom_filter", "active")
        .build()