Calling a large language model from Java used to mean writing HTTP clients, parsing JSON by hand and wiring retries yourself. LangChain4j removes most of that plumbing. In this article we build the smallest useful program: a Java 21 application that creates a Claude chat model with LangChain4j and sends a single prompt. The code is small on purpose, so every line has a clear job, and the structure is the same one you will reuse for tools, memory, retrieval and agents later.
The complete source is in github.com/josesaid/01-chatmodel-anthropic, and a project page with the diagrams is available at josesaid.github.io/01-chatmodel-anthropic.
What you will build
The application does four things:
- Reads the Anthropic API key from an environment variable.
- Builds an
AnthropicChatModelwith the builder pattern. - Sends one question with
chat(String). - Prints the question and the answer.
The flow looks like this:
Your Java app -> AnthropicChatModel (LangChain4j) -> Claude API
chat(prompt) HTTPS request answer text
Nothing here is specific to one vendor. The concepts, a model object, a builder and a text in and text out call, appear in every LangChain4j integration. Once you understand them for Claude, switching providers is mostly a matter of changing the builder.
Prerequisites
- JDK 21 (the project sets
maven.compiler.releaseto 21). - Maven 3.9 or later.
- An Anthropic API key. Create one in the Anthropic console and keep it out of your source code.
Project setup
The Maven project depends on the Anthropic module of LangChain4j:
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-anthropic</artifactId>
<version>1.24.1</version>
</dependency>
The module brings in the core LangChain4j types, so you do not need to add them separately. The exec-maven-plugin lets you run the class with mvn exec:java without building a fat jar, which keeps the first experience short.
The code
Here is the whole main class:
package com.mx.development.jose.said;
import dev.langchain4j.model.anthropic.AnthropicChatModel;
/**
* Example 01 - ChatModel.
*
* Creates a Claude chat model with LangChain4J and sends one prompt.
* The API key is read from the ANTHROPIC_API_KEY environment variable.
*/
public class ChatModelExample {
// Change this constant to try another Claude model.
static final String MODEL_NAME = "claude-haiku-5-5";
public static void main(String[] args) {
String apiKey = System.getenv("ANTHROPIC_API_KEY");
if (apiKey == null || apiKey.isBlank()) {
throw new IllegalStateException("Set the ANTHROPIC_API_KEY environment variable first.");
}
AnthropicChatModel model = AnthropicChatModel.builder()
.apiKey(apiKey)
.modelName(MODEL_NAME)
.temperature(0.2)
.maxTokens(512)
.build();
String question = "In two sentences, what is a ChatModel in LangChain4J?";
String answer = model.chat(question);
System.out.println("Question: " + question);
System.out.println("Answer: " + answer);
}
}
Let us go through the important parts.
Fail fast on a missing key
The first check stops the program before any network call. A missing key would otherwise surface as an authentication error from the API, which is harder to read. A clear message at startup saves time when you run the project on a new machine.
The builder
AnthropicChatModel.builder() returns a builder whose methods mirror the settings you care about:
-
apiKeyauthenticates each request. -
modelNameselects the Claude model. Keeping it in a constant makes the example easy to change. -
temperaturecontrols randomness. A low value such as 0.2 favors consistent answers, which is what you want for a first test. -
maxTokenscaps the length of the response. It also caps cost, so set it deliberately.
build() returns an object that implements the ChatModel abstraction. Your application code can depend on that abstraction later, which makes it easier to test with a fake model.
One call, one answer
model.chat(question) sends the text and returns the answer as a String. The method hides the HTTP request, the JSON payload, the headers and the parsing of the response. For many first experiments, that single call is all you need.
Run it
Export the key in your shell and run the project from its root folder:
export ANTHROPIC_API_KEY=your-key-here
mvn -q compile exec:java
The output looks like this, with the wording varying from run to run:
Question: In two sentences, what is a ChatModel in LangChain4J?
Answer: A ChatModel is the LangChain4J abstraction for a language model that takes messages or text and returns a response. It hides provider-specific details so the same application code can work with different models.
If you see an authentication error, check that the variable is set in the same shell where you run Maven.
Best practices from the first example
Even a tiny program benefits from a few habits that scale to real systems.
Keep secrets out of the repository. Read the key from the environment, or from a secret manager in production. Add environment files and local secrets to .gitignore before the first commit. Never paste a key into an issue, a README or a screenshot.
Name your configuration. Constants such as MODEL_NAME make the choice visible and reviewable. When you move to Spring Boot later, the same values become application.yml properties.
Choose the temperature for the task. Factual or structured tasks usually need low values. Creative drafts can use higher values. Make the choice explicit in the code rather than relying on defaults you do not remember.
Budget tokens. maxTokens is a ceiling on output, but input size matters too. Long prompts cost more and respond more slowly. Measure with real examples before you scale.
Handle failures on purpose. A production call needs timeouts, retries with backoff for transient errors, and logging that never records the key or the full user data. The example omits these to stay readable, but you should add them before any real traffic.
Test the boundary, not the vendor. Because the application depends on ChatModel, unit tests can use a stub that returns fixed text. Reserve the real API for a smaller set of integration tests that run on demand.
Mapping the code to LangChain4j concepts
It helps to name the pieces once, because the same vocabulary returns in every later example.
| In the code | Concept | Why it matters |
|---|---|---|
AnthropicChatModel |
Chat model integration | Adapts one provider to the common LangChain4j API. |
builder() and build()
|
Builder pattern | Makes optional settings explicit and readable. |
modelName, temperature, maxTokens
|
Model parameters | Control which model answers, how varied the answer is, and how long it can be. |
chat(String) |
Convenience method | Sends one user message and returns the text of the reply. |
MODEL_NAME constant |
Configuration | Keeps the model choice in one place that is easy to review. |
Later examples work with richer inputs. A conversation is a list of messages, the response carries metadata about tokens and the reason the generation stopped, and tools are declared with descriptions the model can read. Those are extensions of the same idea: a model object that takes input and returns output through a stable interface.
Why the example reads the key from the environment
Hard-coding a key feels faster during a demo, but it creates three problems. The key ends up in version control, where it is copied to every clone and every backup. It must be changed in code when it rotates. And it is easy to paste into a chat or a ticket by accident.
An environment variable avoids all three. The application code stays identical across machines, each developer uses a personal key, and a leaked file does not expose a secret. The same rule applies to other settings that change between environments, such as the model name when you compare two versions of Claude.
Testing without calling the API every time
Calling a paid API from every test run is slow, costs money and makes results hard to reproduce. A simple refactoring solves most of this. Put the question-and-answer logic in a method that receives the model as a parameter:
static String ask(dev.langchain4j.model.chat.ChatModel model, String question) {
if (question == null || question.isBlank()) {
throw new IllegalArgumentException("The question must not be blank.");
}
return model.chat(question);
}
A unit test can then pass a stub that returns a fixed string, and verify that blank questions are rejected before any model call happens. The real AnthropicChatModel stays in one integration test that runs only when the key is present, which keeps the everyday build fast and offline. This is the practical benefit of depending on an interface rather than on a provider class.
Troubleshooting the first run
Most first-run problems fall into a few groups.
-
The program stops with the message about the environment variable. The variable is not visible to the process. Run
echo $ANTHROPIC_API_KEYin the same terminal, and remember that a variable exported in one terminal tab is not available in another. - Authentication errors from the API. The key is wrong, revoked, or copied with extra spaces. Create a new key, paste it again, and avoid quotes that become part of the value.
-
The model name is rejected. Model identifiers change over time. Check the current list in the Anthropic documentation and update
MODEL_NAME. Keeping the constant in one place makes this a one-line fix. -
Maven cannot find the dependency. Confirm the version in
pom.xmland that your network allows access to Maven Central. A corporate proxy may need explicit configuration. -
The compiler uses an older Java version. The project targets Java 21. Run
java -versionandmvn -v, and make sure both point to a JDK 21 installation. -
The answer is empty or truncated. The response reached
maxTokens. Raise the limit for this experiment, or ask for a shorter answer in the prompt.
Cost and latency
Every call has a cost in input and output tokens, and every call takes time while the model generates text. For a classroom example, the numbers are negligible. In a real product they add up quickly, so it is worth making three habits automatic: log the token usage the API returns, keep prompts short and specific, and set a sensible limit on output length for each use case.
Latency matters as much as cost. A user waiting for a page to render will not tolerate a long blocking call on a request thread. When you move beyond this example, consider asynchronous calls, streaming responses where the user interface supports them, and a clear timeout that tells the user what happened.
Writing better prompts from the start
A single question is enough to test the connection, but the quality of the answer depends heavily on how you ask. A few habits make a large difference even in a one-line prompt.
State the audience and the format. Compare "What is a ChatModel?" with "Explain a ChatModel in two sentences for a Java developer who has not used LangChain4j." The second prompt tells the model who is reading and how long the answer should be, so there is less guessing.
Give the model the facts it needs. If the answer depends on your own data, put that data in the prompt. The model cannot see your files, your database or the code in your project unless you send it.
Ask for one thing at a time. Long prompts that mix three tasks produce answers that do only part of each. Split them into separate calls, and combine the results in your code. This also makes failures easier to diagnose.
Ask for a structure you can check. When your code needs to read the answer, ask for a fixed format, such as a numbered list or a JSON object with named fields. Later in the series you will see how LangChain4j turns that requirement into typed Java objects, which removes most of the manual parsing.
Keep the prompt in code, not in a string scattered through the project. A constant or a template file makes prompts reviewable and testable, and it lets you change wording without touching the logic around it.
Reading the response beyond the text
The chat(String) method returns only the text, which is the right choice for this first example. Under the hood, the provider also reports information that matters in production: how many input and output tokens the call used, and why the generation stopped. When you need those details, the chat model offers a method that returns a richer response object. Use it when you start tracking cost per feature, or when you need to know whether an answer was cut off at the token limit.
Treat that metadata as part of the contract of your code. Log it with a request identifier, never with the full user content, and watch it over time. A sudden rise in output tokens often points to a prompt change that you did not intend.
Moving this example toward Spring Boot
Many Java teams will not keep a main method for long. The natural next step is to expose the same call through a REST endpoint. The model object becomes a bean, the key moves to application.yml or to an environment variable mapped by Spring, and the question arrives as a request parameter. The logic inside the method does not change, which is the reason to keep it small and explicit now.
The security rules also stay the same. Validate the input length before it reaches the model, limit the rate of calls per user, and never return the raw provider error to the client, because it can reveal details about your configuration. Those are the same concerns you would have for any external service, and they apply to language models in exactly the same way.
Common questions
Do I need a paid plan to try this? You need an Anthropic account with API access and enough credit for the requests you send. Check the current pricing page before you run loops of many calls.
Can I use another model with the same code? Yes, by changing the model name, provided it is available to your account. Be aware that different models have different limits, prices and behaviors, so results will vary.
Is it safe to commit the pom.xml? Yes. The file contains dependency versions and build settings, not secrets. The key is the only value that must stay private.
Why not call the HTTP API directly? You can, and it is a good exercise once. LangChain4j is worth using because it gives you the same interface for many providers, shared types for messages and responses, and higher-level tools that you would otherwise write yourself.
Where this leads
The same structure grows naturally. Adding a system message gives the model a role. Chat memory keeps the conversation history. Tools let the model call your Java methods. Retrieval connects the model to your documents. Each step adds one concept on top of the ChatModel you have just used, so it pays to get this first example right.
LangChain4j also offers higher-level building blocks, such as AI Services, which turn an interface into an assistant. You will see them in later examples in the same series. For now, the explicit version above is the best way to understand what those abstractions do underneath.
Summary
- A LangChain4j chat model is a small object you configure with a builder.
-
AnthropicChatModelconnects that object to Claude, so the callchat(String)returns the answer. - The API key belongs in the environment, not in the code.
- Model name, temperature and token limits are explicit choices, and they deserve a conscious decision.
The full project is public, and it is the starting point for the rest of the series. Clone it, set your key, run it, then change the question and watch how the answer changes.
Sources
- Source code: github.com/josesaid/01-chatmodel-anthropic
- Project page with diagrams: josesaid.github.io/01-chatmodel-anthropic
- LangChain4j documentation: docs.langchain4j.dev
Top comments (0)