AWS Builder Center

Integrating Amazon Bedrock in Java Applications with LangChain4j

Learn how to connect your Java applications to Amazon Bedrock's generative AI models seamlessly using the LangChain4j framework.

Backend Developer

Introduction

Adding Generative AI capabilities to Java ecosystems historically required writing complex HTTP clients and manually handling JSON payloads. With LangChain4j and Amazon Bedrock, you can connect your Java microservices to state-of-the-art foundation models—such as Anthropic Claude, Meta Llama, and Amazon Titan—with just a few lines of code.

Prerequisites

  • JDK 17 or higher
  • An AWS account with model access enabled in Amazon Bedrock
  • AWS credentials configured locally ( ~/.aws/credentials )

Dependency Configuration

Add the LangChain4j Amazon Bedrock dependency to your  pom.xml :
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-bedrock</artifactId>
<version>0.31.0</version>
</dependency>

Implementation Example

Below is a complete example initializing Claude 3 Sonnet on Amazon Bedrock to run a prompt:
import dev.langchain4j.model.bedrock.BedrockAnthropicContentBlockChatModel;
public class BedrockJavaExample {
public static void main(String[] args) {
var model = BedrockAnthropicContentBlockChatModel.builder()
.modelId("anthropic.claude-3-sonnet-20240229-v1:0")
.region(software.amazon.awssdk.regions.Region.US_EAST_1)
.temperature(0.7)
.build();
String response = model.generate("Explain the main difference between SQS and SNS in two sentences.");
System.out.println("AI Response: " + response);
}
}

Key Benefits

  • Enterprise-Grade Security: Data remains within your VPC via PrivateLink and is not used to train public foundation models.
  • Unified Abstraction: LangChain4j lets you swap AI providers with minimal code changes.
  • Low Latency: Managed infrastructure ensures predictable response times at scale.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article