CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-dev-langchain4j--langchain4j-anthropic

This package provides an integration layer between the LangChain4j framework and Anthropic's Claude language models, enabling Java developers to seamlessly incorporate Anthropic's AI capabilities into their applications.

Overview
Eval results
Files

model-catalog.mddocs/

Model Catalog

The AnthropicModelCatalog class dynamically discovers available Claude models using the Anthropic Models API.

Capabilities

Creating a Model Catalog

Build an AnthropicModelCatalog using the builder pattern.

package dev.langchain4j.model.anthropic;

import dev.langchain4j.model.catalog.ModelCatalog;
import dev.langchain4j.model.catalog.ModelDescription;
import dev.langchain4j.model.ModelProvider;
import java.util.List;

/**
 * Catalog for discovering available Anthropic models dynamically.
 * Makes HTTP request to Anthropic's models API.
 * Thread-safe after construction.
 *
 * @since 1.0.0
 */
public class AnthropicModelCatalog implements ModelCatalog {
    /**
     * Creates new builder for model catalog.
     *
     * @return new builder instance, never null
     */
    public static Builder builder();

    /**
     * Lists all models available for the configured API key.
     * Makes synchronous HTTP request to models endpoint.
     * Results are not cached; each call queries the API.
     *
     * @return list of model descriptions, never null (may be empty)
     * @throws RuntimeException if API call fails, times out, or auth invalid
     */
    public List<ModelDescription> listModels();

    /**
     * Returns model provider (always ANTHROPIC).
     *
     * @return ANTHROPIC constant, never null
     */
    public ModelProvider provider();
}

Builder Configuration

Configure the model catalog.

package dev.langchain4j.model.anthropic;

import dev.langchain4j.http.client.HttpClientBuilder;
import org.slf4j.Logger;
import java.time.Duration;

/**
 * Builder for AnthropicModelCatalog.
 */
public static class Builder {
    /**
     * Sets API key for authentication.
     *
     * @param apiKey the API key, must not be null or empty
     * @return this builder, never null
     * @throws IllegalArgumentException if apiKey is null or empty
     * @default no default - REQUIRED parameter
     */
    public Builder apiKey(String apiKey);

    /**
     * Sets base URL for Anthropic API.
     *
     * @param baseUrl the base URL, must not be null
     * @return this builder, never null
     * @default "https://api.anthropic.com/v1/"
     */
    public Builder baseUrl(String baseUrl);

    /**
     * Sets API version header.
     *
     * @param version the API version, must not be null
     * @return this builder, never null
     * @default "2023-06-01"
     */
    public Builder version(String version);

    /**
     * Sets custom HTTP client builder.
     *
     * @param httpClientBuilder HTTP client builder, must not be null
     * @return this builder, never null
     * @default platform default
     */
    public Builder httpClientBuilder(HttpClientBuilder httpClientBuilder);

    /**
     * Sets request timeout.
     *
     * @param timeout timeout duration, must not be null, must be positive
     * @return this builder, never null
     * @throws IllegalArgumentException if timeout invalid
     * @default 30 seconds
     */
    public Builder timeout(Duration timeout);

    /**
     * Enables request logging.
     *
     * @param logRequests whether to log requests, may be null
     * @return this builder, never null
     * @default false
     */
    public Builder logRequests(Boolean logRequests);

    /**
     * Enables response logging.
     *
     * @param logResponses whether to log responses, may be null
     * @return this builder, never null
     * @default false
     */
    public Builder logResponses(Boolean logResponses);

    /**
     * Sets custom SLF4J logger.
     *
     * @param logger custom logger instance, may be null
     * @return this builder, never null
     * @default logger named after AnthropicModelCatalog class
     */
    public Builder logger(Logger logger);

    /**
     * Builds the model catalog.
     * Thread-safe after construction.
     *
     * @return configured catalog, never null
     * @throws IllegalStateException if apiKey missing
     */
    public AnthropicModelCatalog build();
}

Basic Usage

List available Claude models.

import dev.langchain4j.model.anthropic.AnthropicModelCatalog;
import dev.langchain4j.model.catalog.ModelDescription;
import java.util.List;

AnthropicModelCatalog catalog = AnthropicModelCatalog.builder()
    .apiKey(System.getenv("ANTHROPIC_API_KEY"))
    .build();

List<ModelDescription> models = catalog.listModels();

for (ModelDescription model : models) {
    System.out.println("Model: " + model.name());
    System.out.println("  Display name: " + model.displayName());
    System.out.println("  Created: " + model.createdAt());
    System.out.println("  Provider: " + model.provider());
    System.out.println();
}

Error Handling:

  • RuntimeException: API call fails (network, timeout, auth)
  • RuntimeException: Invalid API key
  • RuntimeException: Rate limit exceeded
  • Empty list returned if no models available (not an error)

Performance Notes:

  • Each listModels() call makes HTTP request (~200-500ms)
  • Results NOT cached; consider caching in application
  • Suitable for startup/initialization, not hot path

Configuration Options

Full configuration example.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Duration;

Logger customLogger = LoggerFactory.getLogger("ModelCatalog");

AnthropicModelCatalog catalog = AnthropicModelCatalog.builder()
    .apiKey(System.getenv("ANTHROPIC_API_KEY"))  // Required
    .baseUrl("https://api.anthropic.com/v1/")    // Optional, default shown
    .version("2023-06-01")                        // Optional, default shown
    .timeout(Duration.ofSeconds(30))              // Optional
    .logRequests(true)                            // Optional, default false
    .logResponses(true)                           // Optional, default false
    .logger(customLogger)                         // Optional custom logger
    .build();

Error Handling:

  • IllegalStateException: apiKey not set when calling build()
  • IllegalArgumentException: Invalid timeout (null or not positive)
  • RuntimeException: HTTP/network errors at listModels() time (not build time)

Thread Safety:

  • Builder NOT thread-safe
  • Built catalog IS thread-safe
  • Safe to reuse catalog across threads

Common Pitfalls:

❌ DON'T call listModels() in request path

// Called on every request - slow!
List<ModelDescription> models = catalog.listModels();

✅ DO cache results

// Cache at startup
private static final List<ModelDescription> MODELS = catalog.listModels();

Filtering Models

Find specific models or filter by criteria.

import dev.langchain4j.model.catalog.ModelDescription;

List<ModelDescription> models = catalog.listModels();

// Find a specific model
ModelDescription sonnet = models.stream()
    .filter(m -> m.name().contains("sonnet-4-5"))
    .findFirst()
    .orElse(null);

if (sonnet != null) {
    System.out.println("Found: " + sonnet.name());
}

// Filter by creation date
List<ModelDescription> recentModels = models.stream()
    .filter(m -> m.createdAt() != null)
    .filter(m -> m.createdAt().isAfter(Instant.parse("2025-01-01T00:00:00Z")))
    .toList();

System.out.println("Recent models: " + recentModels.size());

Error Handling:

  • createdAt() may be null if parsing fails
  • name() never null
  • displayName() may be null
  • Handle Optional properly for findFirst()

Common Pitfalls:

❌ DON'T assume createdAt always present

m.createdAt().isAfter(date)  // NullPointerException if null

✅ DO check for null

m.createdAt() != null && m.createdAt().isAfter(date)

Null Safety:

  • name() never null
  • provider() never null
  • displayName() may be null
  • createdAt() may be null

[Content continues with dynamic model selection, checking availability, displaying info, grouping by family, usage patterns, types definitions, and comprehensive notes...]

Install with Tessl CLI

npx tessl i tessl/maven-dev-langchain4j--langchain4j-anthropic@1.11.0

docs

chat-model.md

content-types.md

index.md

model-catalog.md

model-names.md

response-metadata.md

streaming-chat-model.md

token-count-estimator.md

tools.md

tile.json