Anthropic Java SDK 提供從 Java 應用程式便捷存取 Anthropic REST API 的方式。它使用「builder pattern」(建構器模式)來建立請求,並同時支援同步與非同步操作。
如需包含程式碼範例的 API 功能文件,請參閱 API 參考。本頁面涵蓋 Java 專屬的 SDK 功能與設定。
此函式庫需要 Java 8 或更高版本。
此 SDK 支援 Java 8 及更高版本。本文件中的程式碼範例以 JDK 25 精簡原始檔撰寫,使用簡單的 void main() 進入點和 IO.println() 進行輸出。API 呼叫本身在每個支援的 JDK 上都是相同的;若要在較早版本上編譯範例,請將 IO.println(...) 替換為 System.out.println(...),並將主體放在類別內的 public static void main(String[] args) 中。
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;
// 使用 `anthropic.apiKey`、`anthropic.authToken` 和 `anthropic.baseUrl` 系統屬性進行設定
// 或使用 `ANTHROPIC_API_KEY`、`ANTHROPIC_AUTH_TOKEN` 和 `ANTHROPIC_BASE_URL` 環境變數進行設定
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
MessageCreateParams params = MessageCreateParams.builder()
.maxTokens(1024L)
.addUserMessage("Hello, Claude")
.model(Model.CLAUDE_OPUS_4_8)
.build();
Message message = client.messages().create(params);使用系統屬性或環境變數來設定用戶端:
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
// 使用 `anthropic.apiKey`、`anthropic.authToken` 和 `anthropic.baseUrl` 系統屬性進行設定
// 或使用 `ANTHROPIC_API_KEY`、`ANTHROPIC_AUTH_TOKEN` 和 `ANTHROPIC_BASE_URL` 環境變數進行設定
AnthropicClient client = AnthropicOkHttpClient.fromEnv();或手動設定:
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
AnthropicClient client = AnthropicOkHttpClient.builder()
.apiKey("my-anthropic-api-key")
.build();或結合使用兩種方法:
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
AnthropicClient client = AnthropicOkHttpClient.builder()
// 使用系統屬性或環境變數進行設定
.fromEnv()
.apiKey("my-anthropic-api-key")
.build();如需了解包含「Workload Identity Federation」(工作負載身分聯合)在內的驗證選項,請參閱驗證。
| Setter | 系統屬性 | 環境變數 | 必填 | 預設值 |
|---|---|---|---|---|
apiKey | anthropic.apiKey | ANTHROPIC_API_KEY | false | - |
authToken | anthropic.authToken | ANTHROPIC_AUTH_TOKEN | false | - |
baseUrl | anthropic.baseUrl | ANTHROPIC_BASE_URL | true |
系統屬性的優先順序高於環境變數。
請勿在同一個應用程式中建立多個用戶端。每個用戶端都有連線池和執行緒池,在請求之間共用會更有效率。
若要暫時使用修改過的用戶端設定,同時重複使用相同的連線池和執行緒池,請在任何用戶端或服務上呼叫 withOptions():
import com.anthropic.client.AnthropicClient;
AnthropicClient clientWithOptions = client.withOptions(optionsBuilder -> {
optionsBuilder.baseUrl("https://example.com");
optionsBuilder.maxRetries(42);
});withOptions() 方法不會影響原始的用戶端或服務。
預設用戶端是同步的。若要切換到非同步執行,請呼叫 async() 方法:
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;
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
MessageCreateParams params = MessageCreateParams.builder()
.maxTokens(1024L)
.addUserMessage("Hello, Claude")
.model(Model.CLAUDE_OPUS_4_8)
.build();
CompletableFuture<Message> message = client.async().messages().create(params);或從一開始就建立非同步用戶端:
import com.anthropic.client.AnthropicClientAsync;
import com.anthropic.client.okhttp.AnthropicOkHttpClientAsync;
import com.anthropic.models.messages.Message;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.Model;
AnthropicClientAsync client = AnthropicOkHttpClientAsync.fromEnv();
MessageCreateParams params = MessageCreateParams.builder()
.maxTokens(1024L)
.addUserMessage("Hello, Claude")
.model(Model.CLAUDE_OPUS_4_8)
.build();
CompletableFuture<Message> message = client.messages().create(params);非同步用戶端支援與同步用戶端相同的選項,但大多數方法會回傳 CompletableFuture。
SDK 定義了回傳回應「chunk」(區塊)串流的方法,每個區塊可以在到達時立即個別處理,而無需等待完整回應。
這些串流方法會為同步用戶端回傳 StreamResponse:
import com.anthropic.core.http.StreamResponse;
import com.anthropic.models.messages.RawMessageStreamEvent;
try (StreamResponse<RawMessageStreamEvent> streamResponse = client.messages().createStreaming(params)) {
streamResponse.stream().forEach(chunk -> {
IO.println(chunk);
});
IO.println("No more chunks!");
}對於非同步用戶端,此方法會回傳 AsyncStreamResponse:
import com.anthropic.core.http.AsyncStreamResponse;
import com.anthropic.models.messages.RawMessageStreamEvent;
client.async().messages().createStreaming(params).subscribe(chunk -> {
IO.println(chunk);
});
// 如果您需要處理錯誤或串流的完成
client.async().messages().createStreaming(params).subscribe(new AsyncStreamResponse.Handler<>() {
@Override
public void onNext(RawMessageStreamEvent chunk) {
IO.println(chunk);
}
@Override
public void onComplete(Optional<Throwable> error) {
if (error.isPresent()) {
IO.println("Something went wrong!");
throw new RuntimeException(error.get());
} else {
IO.println("No more chunks!");
}
}
});
// 或使用 futures
client.async().messages().createStreaming(params)
.subscribe(chunk -> {
IO.println(chunk);
})
.onCompleteFuture()
.whenComplete((unused, error) -> {
if (error != null) {
IO.println("Something went wrong!");
throw new RuntimeException(error);
} else {
IO.println("No more chunks!");
}
});非同步串流使用專屬的每用戶端快取執行緒池 Executor 來進行串流,而不會阻塞目前的執行緒。若要使用不同的 Executor:
Executor executor = Executors.newFixedThreadPool(4);
client.async().messages().createStreaming(params).subscribe(
chunk -> IO.println(chunk), executor
);或使用 streamHandlerExecutor 方法全域設定用戶端:
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
AnthropicClient client = AnthropicOkHttpClient.builder()
.fromEnv()
.streamHandlerExecutor(Executors.newFixedThreadPool(4))
.build();MessageAccumulator 可以在處理回應中的事件串流時記錄這些事件,並累積成一個 Message 物件,類似於非串流 API 所回傳的內容。
對於同步回應,在串流管線中加入 Stream.peek() 呼叫以累積每個事件:
import com.anthropic.core.http.StreamResponse;
import com.anthropic.helpers.MessageAccumulator;
import com.anthropic.models.messages.Message;
import com.anthropic.models.messages.RawMessageStreamEvent;
MessageAccumulator messageAccumulator = MessageAccumulator.create();
try (StreamResponse<RawMessageStreamEvent> streamResponse =
client.messages().createStreaming(createParams)) {
streamResponse.stream()
.peek(messageAccumulator::accumulate)
.flatMap(event -> event.contentBlockDelta().stream())
.flatMap(deltaEvent -> deltaEvent.delta().text().stream())
.forEach(textDelta -> IO.print(textDelta.text()));
}
Message message = messageAccumulator.message();對於非同步回應,將 MessageAccumulator 加入 subscribe() 呼叫中:
import com.anthropic.helpers.MessageAccumulator;
import com.anthropic.models.messages.Message;
MessageAccumulator messageAccumulator = MessageAccumulator.create();
client.async().messages()
.createStreaming(createParams)
.subscribe(event -> messageAccumulator.accumulate(event).contentBlockDelta().stream()
.flatMap(deltaEvent -> deltaEvent.delta().text().stream())
.forEach(textDelta -> IO.print(textDelta.text())))
.onCompleteFuture()
.join();
Message message = messageAccumulator.message();另外也提供 BetaMessageAccumulator 用於累積 BetaMessage 物件。其使用方式與 MessageAccumulator 相同。
如需完整的結構化輸出文件(包含 Java 範例),請參閱結構化輸出。
Claude 的工具使用讓您可以將外部工具和函式直接整合到 AI 模型的回應中。模型不會產生純文字,而是在適當時輸出呼叫工具或函式的指令(含參數)。您為工具定義 JSON 結構描述,模型會使用這些結構描述來判斷何時以及如何使用這些工具。
工具使用功能支援「strict」(嚴格)模式,可保證 AI 模型的 JSON 輸出符合您在輸入參數中提供的 JSON 結構描述。
SDK 可以從任意 Java 類別的結構自動衍生出工具及其參數:類別的名稱(轉換為蛇形命名法)提供工具名稱,而類別的欄位定義工具的參數。
請將您的工具類別宣告為頂層類別或 static 巢狀類別。此要求來自 Jackson Databind 函式庫(com.fasterxml.jackson.databind),SDK 使用該函式庫將工具輸入反序列化為您的類別實例,而該函式庫無法實例化非靜態的內部類別。
import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
enum Unit {
CELSIUS,
FAHRENHEIT;
public String toString() {
switch (this) {
case CELSIUS:
return "C";
case FAHRENHEIT:
default:
return "F";
}
}
public double fromKelvin(double temperatureK) {
switch (this) {
case CELSIUS:
return temperatureK - 273.15;
case FAHRENHEIT:
default:
return (temperatureK - 273.15) * 1.8 + 32.0;
}
}
}
@JsonClassDescription("Get the weather in a given location")
static class GetWeather {
@JsonPropertyDescription("The city and state, e.g. San Francisco, CA")
public String location;
@JsonPropertyDescription("The unit of temperature")
public Unit unit;
public Weather execute() {
double temperatureK;
switch (location) {
case "San Francisco, CA":
temperatureK = 300.0;
break;
case "New York, NY":
temperatureK = 310.0;
break;
case "Dallas, TX":
temperatureK = 305.0;
break;
default:
temperatureK = 295;
break;
}
return new Weather(String.format("%.0f%s", unit.fromKelvin(temperatureK), unit));
}
}
static class Weather {
public String temperature;
public Weather(String temperature) {
this.temperature = temperature;
}
}定義好工具類別後,使用 MessageCreateParams.Builder.addTool(Class<T>) 將它們加入訊息參數中,然後在 AI 模型的回應中要求時呼叫它們。BetaToolUseBlock.input(Class<T>) 可用於將 JSON 形式的工具參數解析為您定義工具的類別實例。
呼叫工具後,使用 BetaToolResultBlockParam.Builder.contentAsJson(Object) 將工具的結果傳回給 AI 模型:
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.models.beta.messages.*;
import com.anthropic.models.messages.Model;
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
MessageCreateParams.Builder createParamsBuilder = MessageCreateParams.builder()
.model(Model.CLAUDE_OPUS_4_8)
.maxTokens(2048)
.addTool(GetWeather.class)
.addUserMessage("What's the temperature in New York?");
client.beta().messages().create(createParamsBuilder.build()).content().stream()
.flatMap(contentBlock -> contentBlock.toolUse().stream())
.forEach(toolUseBlock -> createParamsBuilder
// 新增一則訊息,表示已請求工具使用。
.addAssistantMessageOfBetaContentBlockParams(
List.of(BetaContentBlockParam.ofToolUse(BetaToolUseBlockParam.builder()
.name(toolUseBlock.name())
.id(toolUseBlock.id())
.input(toolUseBlock._input())
.build())))
// 新增一則訊息,包含所請求工具使用的結果。
.addUserMessageOfBetaContentBlockParams(
List.of(BetaContentBlockParam.ofToolResult(BetaToolResultBlockParam.builder()
.toolUseId(toolUseBlock.id())
.contentAsJson(callTool(toolUseBlock))
.build()))));
client.beta().messages().create(createParamsBuilder.build()).content().stream()
.flatMap(contentBlock -> contentBlock.text().stream())
.forEach(textBlock -> IO.println(textBlock.text()));
private static Object callTool(BetaToolUseBlock toolUseBlock) {
if (!"get_weather".equals(toolUseBlock.name())) {
throw new IllegalArgumentException("Unknown tool: " + toolUseBlock.name());
}
GetWeather tool = toolUseBlock.input(GetWeather.class);
return tool != null ? tool.execute() : new Weather("unknown");
}工具名稱衍生自駝峰式命名的工具類別名稱(例如 GetWeather),並轉換為蛇形命名法(例如 get_weather)。單字邊界的判定條件為:目前字元不是第一個字元、是大寫,且前一個字元是小寫,或後一個字元是小寫。例如,MyJSONParser 會變成 my_json_parser,而 ParseJSON 會變成 parse_json。此轉換可以使用 @JsonTypeName 註解來覆寫。
您可以執行本機驗證,以檢查從您的工具類別衍生的 JSON 結構描述是否符合 Anthropic 的限制。本機驗證預設為啟用,但可以停用:
MessageCreateParams.Builder createParamsBuilder = MessageCreateParams.builder()
.model(Model.CLAUDE_OPUS_4_8)
.maxTokens(2048)
.addTool(GetWeather.class, JsonSchemaLocalValidation.NO)
.addUserMessage("What's the temperature in New York?");您可以使用註解為 JSON 結構描述加入更多關於工具的資訊:
@JsonClassDescription - 為工具類別加入描述,詳細說明何時以及如何使用該工具。@JsonTypeName - 將工具名稱設定為類別簡單名稱轉換為蛇形命名法以外的其他名稱。@JsonPropertyDescription - 為工具參數加入詳細描述。@JsonIgnore - 從為工具參數產生的 JSON 結構描述中排除 public 欄位或 getter 方法。@JsonProperty - 在為工具參數產生的 JSON 結構描述中包含非 public 欄位或 getter 方法。SDK 在 client.messages().batches() 命名空間下提供對批次處理的支援。請參閱分頁以了解如何列出批次並進行分頁。
SDK 定義了透過 MultipartField 類別接受檔案的方法:
import com.anthropic.core.MultipartField;
import com.anthropic.models.beta.files.FileMetadata;
import com.anthropic.models.beta.files.FileUploadParams;
FileUploadParams params = FileUploadParams.builder()
.file(
MultipartField.<InputStream>builder()
.value(Files.newInputStream(Paths.get("/path/to/file.pdf")))
.contentType("application/pdf")
.build()
)
.build();
FileMetadata fileMetadata = client.beta().files().upload(params);或從 InputStream:
import com.anthropic.core.MultipartField;
import com.anthropic.models.beta.files.FileMetadata;
import com.anthropic.models.beta.files.FileUploadParams;
FileUploadParams params = FileUploadParams.builder()
.file(
MultipartField.<InputStream>builder()
.value(new URL("https://example.com/path/to/file").openStream())
.filename("document.pdf")
.contentType("application/pdf")
.build()
)
.build();
FileMetadata fileMetadata = client.beta().files().upload(params);或從記憶體中的位元組:
import com.anthropic.core.MultipartField;
import com.anthropic.models.beta.files.FileMetadata;
import com.anthropic.models.beta.files.FileUploadParams;
FileUploadParams params = FileUploadParams.builder()
.file(
MultipartField.<InputStream>builder()
.value(new ByteArrayInputStream("content".getBytes()))
.filename("document.txt")
.contentType("text/plain")
.build()
)
.build();
FileMetadata fileMetadata = client.beta().files().upload(params);SDK 定義了針對不一定解析為 JSON 的 API 回應回傳二進位回應的方法:
import com.anthropic.core.http.HttpResponse;
HttpResponse response = client.beta().files().download("file_id");若要將回應內容儲存到檔案:
import com.anthropic.core.http.HttpResponse;
try (HttpResponse response = client.beta().files().download(params)) {
Files.copy(
response.body(),
Paths.get(path),
StandardCopyOption.REPLACE_EXISTING
);
} catch (Exception e) {
IO.println("Something went wrong!");
throw new RuntimeException(e);
}或將回應內容傳輸到任何 OutputStream:
import com.anthropic.core.http.HttpResponse;
try (HttpResponse response = client.beta().files().download(params)) {
response.body().transferTo(Files.newOutputStream(Paths.get(path)));
} catch (Exception e) {
IO.println("Something went wrong!");
throw new RuntimeException(e);
}SDK 會拋出自訂的非檢查例外類型:
AnthropicServiceException - HTTP 錯誤的基礎類別。AnthropicIoException - I/O 網路錯誤。AnthropicRetryableException - 表示可重試失敗的通用錯誤。AnthropicInvalidDataException - 無法解讀已成功解析的資料(例如,存取應為必填但 API 意外省略的屬性時)。AnthropicException - 所有例外的基礎類別。| 狀態 | 例外 |
|---|---|
| 400 | BadRequestException |
| 401 | UnauthorizedException |
| 403 | PermissionDeniedException |
| 404 | NotFoundException |
| 422 | UnprocessableEntityException |
| 429 | RateLimitException |
| 5xx | InternalServerException |
| 其他 | UnexpectedStatusCodeException |
在成功的初始 HTTP 回應之後,若在 SSE 串流期間遇到錯誤,會拋出 SseException。
import com.anthropic.errors.*;
try {
Message message = client.messages().create(params);
} catch (RateLimitException e) {
IO.println("Rate limited, retry after: " + e.headers());
} catch (UnauthorizedException e) {
IO.println("Invalid API key");
} catch (AnthropicServiceException e) {
IO.println("API error: " + e.statusCode());
} catch (AnthropicIoException e) {
IO.println("Network error: " + e.getMessage());
}使用原始回應時,您可以使用 requestId() 方法存取 request-id 回應標頭:
import com.anthropic.core.http.HttpResponseFor;
import com.anthropic.models.messages.Message;
HttpResponseFor<Message> message = client.messages().withRawResponse().create(params);
Optional<String> requestId = message.requestId();這可用於快速記錄失敗的請求並回報給 Anthropic。如需有關偵錯請求的更多資訊,請參閱請求 ID。
SDK 預設會自動重試 2 次,並在請求之間使用短暫的指數退避。
只有以下錯誤類型會被重試:
API 也可能明確指示 SDK 重試或不重試某個請求。
若要設定自訂的重試次數,請使用 maxRetries 方法設定用戶端:
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
AnthropicClient client = AnthropicOkHttpClient.builder().fromEnv().maxRetries(4).build();請求預設在 10 分鐘後逾時。
然而,對於接受 maxTokens 的方法,如果您指定較大的 maxTokens 值並且正在使用串流,則預設逾時將使用以下公式動態計算:
Duration.ofSeconds(
Math.min(
60 * 60, // 1 hour max
Math.max(
10 * 60, // 10 minute minimum
60 * 60 * maxTokens / 128_000
)
)
)這會產生最長 60 分鐘的逾時,依 maxTokens 參數縮放,除非被覆寫。
對於非串流請求,動態逾時會根據 maxTokens 從最少 30 秒縮放到最多 10 分鐘。
若要為每個請求設定自訂逾時:
import com.anthropic.models.messages.Message;
Message message = client
.messages()
.create(params, RequestOptions.builder().timeout(Duration.ofSeconds(30)).build());或在用戶端層級為所有方法呼叫設定預設值:
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
AnthropicClient client = AnthropicOkHttpClient.builder()
.fromEnv()
.timeout(Duration.ofSeconds(30))
.build();對於執行時間較長的請求,請考慮使用串流。
避免在不使用串流的情況下設定較大的 maxTokens 值。某些網路可能會在一段時間後中斷閒置連線,這可能導致請求失敗或逾時而未收到 Anthropic 的回應。SDK 會定期 ping API 以保持連線存活,並減少這些網路的影響。
如果預期非串流請求會花費超過 10 分鐘,SDK 會拋出錯誤。使用串流方法或在用戶端或請求層級覆寫逾時可停用此錯誤。
SDK 提供便捷的方式來存取分頁結果,可以一次一頁,或逐項跨所有頁面存取。
若要遍歷所有頁面的所有結果,請使用 autoPager() 方法,該方法會在需要時自動擷取更多頁面。
import com.anthropic.models.messages.batches.BatchListPage;
import com.anthropic.models.messages.batches.MessageBatch;
BatchListPage page = client.messages().batches().list();
// 作為 Iterable 處理
for (MessageBatch batch : page.autoPager()) {
IO.println(batch);
}
// 作為 Stream 處理
page.autoPager()
.stream()
.limit(50)
.forEach(batch -> IO.println(batch));使用非同步用戶端時,此方法會回傳 AsyncStreamResponse:
import com.anthropic.core.http.AsyncStreamResponse;
import com.anthropic.models.messages.batches.BatchListPageAsync;
import com.anthropic.models.messages.batches.MessageBatch;
CompletableFuture<BatchListPageAsync> pageFuture = client.async().messages().batches().list();
pageFuture.thenAccept(page -> page.autoPager().subscribe(batch -> {
IO.println(batch);
}));
// 如果您需要處理錯誤或串流完成
pageFuture.thenAccept(page -> page.autoPager().subscribe(new AsyncStreamResponse.Handler<>() {
@Override
public void onNext(MessageBatch batch) {
IO.println(batch);
}
@Override
public void onComplete(Optional<Throwable> error) {
if (error.isPresent()) {
IO.println("Something went wrong!");
throw new RuntimeException(error.get());
} else {
IO.println("No more!");
}
}
}));
// 或使用 futures
pageFuture.thenAccept(page -> page.autoPager()
.subscribe(batch -> {
IO.println(batch);
})
.onCompleteFuture()
.whenComplete((unused, error) -> {
if (error != null) {
IO.println("Something went wrong!");
throw new RuntimeException(error);
} else {
IO.println("No more!");
}
}));若要存取個別頁面項目並手動請求下一頁:
import com.anthropic.models.messages.batches.BatchListPage;
import com.anthropic.models.messages.batches.MessageBatch;
BatchListPage page = client.messages().batches().list();
while (true) {
for (MessageBatch batch : page.items()) {
IO.println(batch);
}
if (!page.hasNextPage()) {
break;
}
page = page.nextPage();
}SDK 中的每個類別都有一個相關聯的建構器用於建構它。每個類別一旦建構完成即為不可變。如果類別有相關聯的建構器,則它會有一個 toBuilder() 方法,可用於將其轉換回建構器以製作修改過的副本。
MessageCreateParams params = MessageCreateParams.builder()
.maxTokens(1024L)
.addUserMessage("Hello, Claude")
.model(Model.CLAUDE_OPUS_4_8)
.build();
// 使用 toBuilder() 建立修改後的副本
MessageCreateParams modified = params.toBuilder().maxTokens(2048L).build();由於每個類別都是不可變的,建構器的修改永遠不會影響已建構的類別實例。
若要向 Claude API 傳送請求,請建構某個 Params 類別的實例並將其傳遞給對應的用戶端方法。收到回應時,它會被反序列化為 Java 類別的實例。
例如,client.messages().create(...) 應使用 MessageCreateParams 的實例來呼叫,並會回傳 Message 的實例。
若要設定未記載的參數,請在任何 Params 類別上呼叫 putAdditionalHeader、putAdditionalQueryParam 或 putAdditionalBodyProperty 方法:
import com.anthropic.core.JsonValue;
import com.anthropic.models.messages.MessageCreateParams;
MessageCreateParams params = MessageCreateParams.builder()
.putAdditionalHeader("Secret-Header", "42")
.putAdditionalQueryParam("secret_query_param", "42")
.putAdditionalBodyProperty("secretProperty", JsonValue.from("42"))
.build();這些可以稍後在已建構的物件上使用 _additionalHeaders()、_additionalQueryParams() 和 _additionalBodyProperties() 方法來存取。
傳遞給這些方法的值會覆寫傳遞給先前方法的值。基於安全考量,請確保這些方法僅與受信任的輸入資料一起使用。
若要在巢狀的標頭、查詢參數或主體類別上設定未記載的參數:
import com.anthropic.core.JsonValue;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.Metadata;
MessageCreateParams params = MessageCreateParams.builder()
.metadata(
Metadata.builder().putAdditionalProperty("secretProperty", JsonValue.from("42")).build()
)
.build();這些屬性可以稍後在巢狀的已建構物件上使用 _additionalProperties() 方法來存取。
若要將已記載的參數或屬性設定為未記載或尚未支援的值,請將 JsonValue 物件傳遞給其 setter:
import com.anthropic.core.JsonValue;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.Model;
MessageCreateParams params = MessageCreateParams.builder()
.maxTokens(JsonValue.from(3.14))
.addUserMessage("Hello, Claude")
.model(Model.CLAUDE_OPUS_4_8)
.build();建立 JsonValue 最直接的方式是使用其 from(...) 方法:
import com.anthropic.core.JsonValue;
// 建立基本 JSON 值
JsonValue nullValue = JsonValue.from(null);
JsonValue booleanValue = JsonValue.from(true);
JsonValue numberValue = JsonValue.from(42);
JsonValue stringValue = JsonValue.from("Hello World!");
// 建立等同於 `["Hello", "World"]` 的 JSON 陣列值
JsonValue arrayValue = JsonValue.from(List.of("Hello", "World"));
// 建立等同於 `{ "a": 1, "b": 2 }` 的 JSON 物件值
JsonValue objectValue = JsonValue.from(Map.of("a", 1, "b", 2));
// 建立任意巢狀的 JSON,等同於:
// { "a": [1, 2], "b": [3, 4] }
JsonValue complexValue = JsonValue.from(Map.of("a", List.of(1, 2), "b", List.of(3, 4)));通常,如果有任何必填參數或屬性未設定,Builder 類別的 build 方法會拋出 IllegalStateException。若要強制省略必填參數或屬性,請傳遞 JsonMissing:
import com.anthropic.core.JsonMissing;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.Model;
MessageCreateParams params = MessageCreateParams.builder()
.addUserMessage("Hello, world")
.model(Model.CLAUDE_OPUS_4_8)
.maxTokens(JsonMissing.of())
.build();若要存取未記載的回應屬性,請呼叫 _additionalProperties() 方法:
import com.anthropic.core.JsonValue;
Map<String, JsonValue> additionalProperties = client
.messages()
.create(params)
._additionalProperties();
JsonValue secretPropertyValue = additionalProperties.get("secretProperty");
String result = secretPropertyValue.accept(new JsonValue.Visitor<>() {
@Override
public String visitNull() {
return "It's null!";
}
@Override
public String visitBoolean(boolean value) {
return "It's a boolean!";
}
@Override
public String visitNumber(Number value) {
return "It's a number!";
}
// 其他方法包括 `visitMissing`、`visitString`、`visitArray` 和 `visitObject`
// 每個未實作方法的預設實作都會委派給 `visitDefault`,
// 該方法預設會拋出例外,但也可以被覆寫
});若要存取屬性的原始 JSON 值,請呼叫其帶有 _ 前綴的方法:
import com.anthropic.core.JsonField;
import com.anthropic.models.messages.StopReason;
JsonField<StopReason> stopReason = client.messages().create(params)._stopReason();
if (stopReason.isMissing()) {
// JSON 回應中不存在該屬性
} else if (stopReason.isNull()) {
// 該屬性被設為字面值 null
} else {
// 檢查值是否以字串形式提供
// 其他方法包括 `asNumber()`、`asBoolean()` 等
Optional<String> jsonString = stopReason.asString();
// 嘗試反序列化為自訂型別
MyClass myObject = stopReason.asUnknown().orElseThrow().convert(MyClass.class);
}預設情況下,當 API 回傳的回應不符合預期型別時,SDK 不會拋出例外。只有在您直接存取該屬性時,才會拋出 AnthropicInvalidDataException。
若要預先檢查回應是否完全符合型別,請呼叫 validate():
import com.anthropic.models.messages.Message;
Message message = client.messages().create(params).validate();或為每個請求設定:
import com.anthropic.models.messages.Message;
Message message = client
.messages()
.create(params, RequestOptions.builder().responseValidation(true).build());或在用戶端層級為所有方法呼叫設定預設值:
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
AnthropicClient client = AnthropicOkHttpClient.builder()
.fromEnv()
.responseValidation(true)
.build();import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import java.net.Proxy;
AnthropicClient client = AnthropicOkHttpClient.builder()
.fromEnv()
.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("https://example.com", 8080)))
.build();大多數應用程式不應呼叫這些方法,而應使用系統預設值。預設值包含特殊最佳化,如果修改實作可能會遺失這些最佳化。
import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
AnthropicClient client = AnthropicOkHttpClient.builder()
.fromEnv()
.sslSocketFactory(yourSSLSocketFactory)
.trustManager(yourTrustManager)
.hostnameVerifier(yourHostnameVerifier)
.build();SDK 由三個構件組成:
anthropic-java-core - 包含核心 SDK 邏輯,不依賴 OkHttp。公開 AnthropicClient、AnthropicClientAsync 及其實作類別,所有這些都可以與任何 HTTP 用戶端搭配使用。anthropic-java-client-okhttp - 依賴 OkHttp。公開 AnthropicOkHttpClient 和 AnthropicOkHttpClientAsync。anthropic-java - 依賴並公開 anthropic-java-core 和 anthropic-java-client-okhttp 兩者的 API。本身沒有自己的邏輯。此結構允許替換 SDK 的預設 HTTP 用戶端,而無需引入不必要的相依性。
在替換預設用戶端之前,請先嘗試可用的網路選項。
若要使用自訂的 OkHttpClient:
anthropic-java 相依性替換為 anthropic-java-core。anthropic-java-client-okhttp 的 OkHttpClient 類別複製到您的程式碼中並進行自訂。AnthropicClientImpl 或 AnthropicClientAsyncImpl。若要使用完全自訂的 HTTP 用戶端:
anthropic-java 相依性替換為 anthropic-java-core。HttpClient 介面的類別。AnthropicClientImpl 或 AnthropicClientAsyncImpl。如需包含程式碼範例的詳細平台設定指南,請參閱:
Java SDK 透過提供平台專屬 Backend 實作的獨立相依性來支援以下平台:
com.anthropic:anthropic-java-bedrock:對於 Messages-API Bedrock 端點,使用 BedrockMantleBackend.fromEnv() 或 BedrockMantleBackend.builder();或使用 BedrockBackend.fromEnv() / BedrockBackend.builder()(bedrock-runtime 路徑)。com.anthropic:anthropic-java-vertex:使用 VertexBackend.fromEnv() 或 VertexBackend.builder()。com.anthropic:anthropic-java-foundry:使用 FoundryBackend.fromEnv() 或 FoundryBackend.builder()。com.anthropic:anthropic-java-aws:使用 (讀取 和 AWS 預設區域/憑證鏈)或 。目前為測試版。新專案請使用 BedrockMantleBackend;BedrockBackend 保留給使用 Bedrock InvokeModel API 的現有應用程式。
每個 Backend 實作都透過 AnthropicOkHttpClient.builder() 上的 .backend() 傳遞給用戶端。每個雲端後端都會將其各自的雲端平台 SDK 類別作為遞移相依性引入。
若要存取 HTTP 標頭、狀態碼和原始回應主體,請在任何 HTTP 方法呼叫前加上 withRawResponse():
import com.anthropic.core.http.Headers;
import com.anthropic.core.http.HttpResponseFor;
import com.anthropic.models.messages.Message;
import com.anthropic.models.messages.MessageCreateParams;
import com.anthropic.models.messages.Model;
MessageCreateParams params = MessageCreateParams.builder()
.maxTokens(1024L)
.addUserMessage("Hello, Claude")
.model(Model.CLAUDE_OPUS_4_8)
.build();
HttpResponseFor<Message> message = client.messages().withRawResponse().create(params);
int statusCode = message.statusCode();
Headers headers = message.headers();如有需要,您仍然可以將回應反序列化為 Java 類別的實例:
import com.anthropic.models.messages.Message;
Message parsedMessage = message.parse();SDK 使用標準的 OkHttp 記錄攔截器。
透過將 ANTHROPIC_LOG 環境變數設定為 info 來啟用記錄:
export ANTHROPIC_LOG=info或設定為 debug 以取得更詳細的記錄:
export ANTHROPIC_LOG=debugSDK 的型別設計是為了方便使用已記載的 API。然而,它也支援使用 API 中未記載或尚未支援的部分。
若要設定未記載的請求參數,請使用未記載的參數中所述的 putAdditionalHeader、putAdditionalQueryParam 或 putAdditionalBodyProperty 方法。
若要存取未記載的回應屬性,請使用回應屬性中所述的 _additionalProperties() 方法。
SDK 中類似列舉的類別(例如 Model 和 AnthropicBeta)並非封閉的 Java enum 型別。每個類別都提供一個接受任何字串的 of(String) 工廠方法,因此您可以使用尚未加入 SDK 的值,例如在您的 SDK 版本之後發佈的模型或測試版標頭:
import com.anthropic.models.beta.AnthropicBeta;
import com.anthropic.models.messages.Model;
Model model = Model.of("some-new-model");
AnthropicBeta beta = AnthropicBeta.of("some-new-beta-2026-01-01");接受這些型別的建構器方法通常也提供 String 多載,會為您呼叫 of(...):
import com.anthropic.models.messages.MessageCreateParams;
MessageCreateParams params = MessageCreateParams.builder()
.model("some-new-model") // same as .model(Model.of("some-new-model"))
.maxTokens(1024L)
.addUserMessage("Hello, Claude")
.build();建議優先使用具有良好型別的常數(例如 Model.CLAUDE_OPUS_4_7),以便獲得自動完成和棄用警告。String 多載和 of(...) 主要用於在等待包含該值的 SDK 版本發佈期間,將欄位設定為未記載或尚未支援的值。
測試版功能在正式發佈之前提供,以便獲得早期回饋並測試新功能。您可以在使用 Claude 建構概覽中查看 Claude 所有功能和工具的可用性。
您可以透過用戶端上的 beta() 方法存取大多數測試版 API 功能。若要啟用特定的測試版功能,請在建構訊息參數時使用 .addBeta() 加入適當的測試版標頭。
例如,若要使用 Files API:
import com.anthropic.models.beta.AnthropicBeta;
import com.anthropic.models.beta.messages.BetaContentBlockParam;
import com.anthropic.models.beta.messages.BetaMessage;
import com.anthropic.models.beta.messages.BetaRequestDocumentBlock;
import com.anthropic.models.beta.messages.BetaTextBlockParam;
import com.anthropic.models.beta.messages.MessageCreateParams;
void main() {
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
BetaMessage message = client.beta().messages().create(
MessageCreateParams.builder()
.model(Model.CLAUDE_OPUS_4_8)
.maxTokens(1024L)
.addBeta(AnthropicBeta.FILES_API_2025_04_14)
.addUserMessageOfBetaContentBlockParams(List.of(
BetaContentBlockParam.ofText(
BetaTextBlockParam.builder()
.text("Please summarize this document for me.")
.build()),
BetaContentBlockParam.ofDocument(
BetaRequestDocumentBlock.builder()
.fileSource("file_abc123")
.build())))
.build());
}此套件通常遵循 SemVer 慣例,但某些向後不相容的變更可能會作為次要版本發佈:
Was this page helpful?
"https://api.anthropic.com"AwsBackend.fromEnv()ANTHROPIC_AWS_WORKSPACE_IDAwsBackend.builder()