Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Build LLM-powered apps with the Anthropic Claude API or SDK across Python, TypeScript, Java, Go, Ruby, C#, and PHP.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
java/claude-api/README.md
1# Claude API — Java23> **Note:** The Java SDK supports the Claude API and beta tool use with annotated classes. Agent SDK is not yet available for Java.45## Package Reference67Types are organized by package. If a class you need isn't shown in an example below, locate it via this table first — don't block on fetching SDK source over the network.89| `import` prefix | Contains |10|---|---|11| `com.anthropic.client` / `com.anthropic.client.okhttp` | `AnthropicClient`, `AnthropicOkHttpClient` |12| `com.anthropic.models.messages` | non-beta request/response types — `MessageCreateParams`, `Model`, `Message`, `TextBlockParam`, `ContentBlockParam`, `ToolUseBlockParam`, `ToolResultBlockParam`, `CacheControlEphemeral`, `Tool*` (e.g. `ToolBash20250124`, `ToolTextEditor20250728`), `StopReason`, `StructuredMessage*` |13| `com.anthropic.models.messages.batches` | Batch API — `BatchResultsParams`, `MessageBatchIndividualResponse` |14| `com.anthropic.models.beta` | `AnthropicBeta` (beta-flag constants) |15| `com.anthropic.models.beta.messages` | beta-endpoint types — `MessageCreateParams`, `BetaMessage`, `BetaStopReason`, `BetaContextManagementConfig`, `BetaMcpToolset`, `BetaRequestMcpServerUrlDefinition`, `BetaTool*` |16| `com.anthropic.core` | `JsonValue`, `JsonField`, `JsonSchemaLocalValidation`, `com.anthropic.core.http.StreamResponse` |17| `com.anthropic.errors` | typed exceptions — `AnthropicServiceException`, `RateLimitException`, `NotFoundException`, etc. (see `shared/error-codes.md`) |1819`client.messages()` uses `com.anthropic.models.messages.*`; `client.beta().messages()` uses `com.anthropic.models.beta.messages.*`. Both packages define a `MessageCreateParams` — import the one matching the client path you call.2021### Key types per feature2223Write from this table instead of `javap`/jar inspection. Endpoint column tells you whether to use `client.messages()` or `client.beta().messages()`.2425| Feature | Endpoint | Key Java types / builder calls |26|---|---|---|27| User profiles | beta | `client.beta().userProfiles().create(...)` / `.retrieve(id)` / `.list()`. Pass the returned profile id on the beta `MessageCreateParams`. Requires a beta header — check the SDK's beta-headers reference for the current flag. |28| Agent Skills | beta | `BetaContainerParams`, `BetaSkillParams`, `BetaCodeExecutionTool20250825`. `.addBeta("code-execution-2025-08-25").addBeta("skills-2025-10-02")`. Download the output via `client.beta().files().download(fileId)`. |29| Cache diagnostics | beta | `BetaDiagnosticsParam`, `BetaCacheControlEphemeral` |30| Context editing | beta | `.contextManagement(BetaContextManagementConfig.builder()…)`. The edit strategy is a `BetaClearToolUses20250919Edit` (or `BetaClearThinking20251015Edit`); its trigger is a `BetaInputTokensTrigger` built separately and passed to the edit's builder — there is no direct `.inputTokensTrigger(N)` shortcut on the edit builder. `javap` the edit and trigger classes for the exact setter names. |31| Memory tool | non-beta | `.addTool(MemoryTool20250818.builder().build())` from `com.anthropic.models.messages` |32| Programmatic tool calling | non-beta | `CodeExecutionTool20260120`, `Tool`, `ContentBlockParam` |33| Strict tool use | non-beta | `Tool`, `Tool.InputSchema` |34| Task budgets | beta | `.outputConfig(BetaOutputConfig.builder().taskBudget(BetaTokenTaskBudget.builder()...))` |35| Tool search | non-beta | `.addTool(ToolSearchToolRegex20251119.builder()...)` from `com.anthropic.models.messages` |36| Web search | non-beta | `WebSearchTool20260209` from `com.anthropic.models.messages` — the latest variant with dynamic filtering (Opus 4.8/4.7/4.6 + Sonnet 4.6). For older models or Vertex, use `WebSearchTool20250305` |3738### Discovering type and member names3940If a class or builder method you need isn't in the tables above, `jar tf <anthropic-java-core jar> | grep -i <term>` or `javap -classpath <jar> com.anthropic.models.…` is fast enough to locate names. **Do not compile and run a separate reflection program** to enumerate members — the first build is slow enough to be backgrounded in many environments, trapping you in a polling loop. Write the script with the names you found and let the compiler error (`cannot find symbol`) point at any wrong member.4142## Installation4344Maven:4546```xml47<dependency>48<groupId>com.anthropic</groupId>49<artifactId>anthropic-java</artifactId>50<version>2.34.0</version>51</dependency>52```5354Gradle:5556```groovy57implementation("com.anthropic:anthropic-java:2.34.0")58```5960## Client Initialization6162```java63import com.anthropic.client.AnthropicClient;64import com.anthropic.client.okhttp.AnthropicOkHttpClient;6566// Default (reads ANTHROPIC_API_KEY from environment)67AnthropicClient client = AnthropicOkHttpClient.fromEnv();6869// Explicit API key70AnthropicClient client = AnthropicOkHttpClient.builder()71.apiKey("your-api-key")72.build();73```7475---7677## Basic Message Request7879```java80import com.anthropic.models.messages.MessageCreateParams;81import com.anthropic.models.messages.Message;82import com.anthropic.models.messages.Model;8384MessageCreateParams params = MessageCreateParams.builder()85.model(Model.CLAUDE_OPUS_4_8)86.maxTokens(16000L)87.addUserMessage("What is the capital of France?")88.build();8990Message response = client.messages().create(params);91response.content().stream()92.flatMap(block -> block.text().stream())93.forEach(textBlock -> System.out.println(textBlock.text()));94```9596---9798## Thinking99100**Adaptive thinking is the recommended mode for Claude 4.6+ models.** Claude decides dynamically when and how much to think. The builder has a direct `.thinking(ThinkingConfigAdaptive)` overload — no manual union wrapping.101102> **Fable 5, Opus 4.8, Opus 4.7, Opus 4.6, and Sonnet 4.6:** Use adaptive thinking (below). `ThinkingConfigEnabled.builder().budgetTokens(N)` is removed on Fable 5, Opus 4.8, and 4.7 (400 if sent); deprecated on Opus 4.6 and Sonnet 4.6.103> **Older models:** Use `.thinking(ThinkingConfigEnabled.builder().budgetTokens(N).build())` (budget must be < `maxTokens`, min 1024).104105```java106import com.anthropic.models.messages.ContentBlock;107import com.anthropic.models.messages.MessageCreateParams;108import com.anthropic.models.messages.Model;109import com.anthropic.models.messages.ThinkingConfigAdaptive;110111MessageCreateParams params = MessageCreateParams.builder()112.model(Model.CLAUDE_SONNET_4_6)113.maxTokens(16000L)114.thinking(ThinkingConfigAdaptive.builder().build())115.addUserMessage("Solve this step by step: 27 * 453")116.build();117118for (ContentBlock block : client.messages().create(params).content()) {119block.thinking().ifPresent(t -> System.out.println("[thinking] " + t.thinking()));120block.text().ifPresent(t -> System.out.println(t.text()));121}122```123124`ContentBlock` narrowing: `.thinking()` / `.text()` return `Optional<T>` — use `.ifPresent(...)` or `.stream().flatMap(...)`. Alternative: `isThinking()` / `asThinking()` boolean+unwrap pairs (throws on wrong variant).125126---127128## Effort Parameter129130Effort is nested inside `OutputConfig` — there is NO `.effort()` directly on `MessageCreateParams.Builder`.131132```java133import com.anthropic.models.messages.OutputConfig;134135.outputConfig(OutputConfig.builder()136.effort(OutputConfig.Effort.HIGH) // or LOW, MEDIUM, MAX137.build())138```139140Combine with `Thinking = ThinkingConfigAdaptive` for cost-quality control.141142---143144## Prompt Caching145146System message as a list of `TextBlockParam` with `CacheControlEphemeral`. Use `.systemOfTextBlockParams(...)` — the plain `.system(String)` overload can't carry cache control. For placement patterns and the silent-invalidator audit checklist, see `shared/prompt-caching.md`.147148```java149import com.anthropic.models.messages.TextBlockParam;150import com.anthropic.models.messages.CacheControlEphemeral;151152.systemOfTextBlockParams(List.of(153TextBlockParam.builder()154.text(longSystemPrompt)155.cacheControl(CacheControlEphemeral.builder()156.ttl(CacheControlEphemeral.Ttl.TTL_1H) // optional; also TTL_5M157.build())158.build()))159```160161There's also a top-level `.cacheControl(CacheControlEphemeral)` on `MessageCreateParams.Builder` and on `Tool.builder()`.162163Verify hits via `response.usage().cacheCreationInputTokens()` / `response.usage().cacheReadInputTokens()`.164165---166167## Token Counting168169```java170import com.anthropic.models.messages.MessageCountTokensParams;171172long tokens = client.messages().countTokens(173MessageCountTokensParams.builder()174.model(Model.CLAUDE_SONNET_4_6)175.addUserMessage("Hello")176.build()177).inputTokens();178```179180---181182## PDF / Document Input183184`DocumentBlockParam` builder has source shortcuts. Wrap in `ContentBlockParam.ofDocument()` and pass via `.addUserMessageOfBlockParams()`.185186```java187import com.anthropic.models.messages.DocumentBlockParam;188import com.anthropic.models.messages.ContentBlockParam;189import com.anthropic.models.messages.TextBlockParam;190191DocumentBlockParam doc = DocumentBlockParam.builder()192.source(Base64PdfSource.builder().data(base64String).build())193// or .source(UrlPdfSource.builder().url("https://...").build())194.title("My Document") // optional195.build();196```197198For **Files API** document references, use the beta path and beta types — see `files-api.md`: `BetaRequestDocumentBlock.builder().source(BetaFileDocumentSource.builder().fileId(id).build())`.199200```java201.addUserMessageOfBlockParams(List.of(202ContentBlockParam.ofDocument(doc),203ContentBlockParam.ofText(TextBlockParam.builder().text("Summarize this").build())))204```205206---207208## Stop Details209210When `stopReason()` is `"refusal"`, the response includes structured `stopDetails()`:211212```java213response.stopDetails().ifPresent(details -> {214System.out.println("Category: " + details.category());215System.out.println("Explanation: " + details.explanation());216});217```218219**Refusal fallbacks (Claude Fable 5) — opt in by default.** Fallbacks are opt-in: without them a refused request simply stops. New `claude-fable-5` code should include the server-side `fallbacks` parameter (beta header `server-side-fallback-2026-06-01`, fallback model `claude-opus-4-8`, on the beta messages call) by default. The exact Java builder methods (and the client-side middleware for providers without server-side support) are not documented here — WebFetch the Java SDK repo's `examples/` from `shared/live-sources.md`; full semantics in `shared/model-migration.md` → Migrating to Claude Fable 5 → `refusal` stop reason.220221---222223## Error Type224225`AnthropicServiceException` exposes `.errorType()` returning `Optional<ErrorType>` for programmatic error classification:226227```java228try {229client.messages().create(params);230} catch (AnthropicServiceException e) {231e.errorType().ifPresent(type ->232System.out.println("Error type: " + type) // RATE_LIMIT_ERROR, OVERLOADED_ERROR, etc.233);234}235```236237---238239