Get Started
This guide takes you from an empty Java project to an AI Service that remembers the conversation and calls your own Java code.
Quarkus, Spring Boot, Helidon and Micronaut have their own integrations: see Quarkus, Spring Boot, Helidon and Micronaut. The concepts on this page (AI Services, tools, chat memory) are the same everywhere. The setup is different: the framework integration brings the dependencies, creates the models from your configuration and wires the AI Services, so follow its guide for those parts.
Prerequisites
- Java 17 or newer.
- An OpenAI API key. If you prefer a model that runs on your own machine, see Use a local model below.
1. Add the dependencies
LangChain4j offers integrations with many LLM providers,
embedding (vector) stores and more.
Each integration has its own dependency. This guide uses OpenAI (langchain4j-open-ai).
The langchain4j dependency adds the high-level AI Services API.
- Maven
- Gradle
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-open-ai</artifactId>
<version>1.24.1</version>
</dependency>
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j</artifactId>
<version>1.24.1</version>
</dependency>
implementation 'dev.langchain4j:langchain4j-open-ai:1.24.1'
implementation 'dev.langchain4j:langchain4j:1.24.1'
Bill of Materials (BOM)
When you use several LangChain4j modules, import the BOM and leave out the versions of the single modules. For Maven:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-bom</artifactId>
<version>1.24.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-open-ai</artifactId>
</dependency>
</dependencies>
For Gradle:
implementation platform('dev.langchain4j:langchain4j-bom:1.24.1')
implementation 'dev.langchain4j:langchain4j-open-ai'
Community integrations (artifacts named langchain4j-community-*) have their own langchain4j-community-bom.
langchain4j-bom always contains the latest versions of all LangChain4j modules.
While the langchain4j-bom version is 1.24.1,
many of the modules still have version 1.24.1-beta34,
so there might be some breaking changes for these modules in the future.
SNAPSHOT dependencies (newest features)
If you'd like to test the newest features before their official release,
you can use the most recent SNAPSHOT dependency:
<repositories>
<repository>
<name>Central Portal Snapshots</name>
<id>central-portal-snapshots</id>
<url>https://central.sonatype.com/repository/maven-snapshots/</url>
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j</artifactId>
<version>1.25.0-SNAPSHOT</version>
</dependency>
</dependencies>
2. Chat with a model
Store your OpenAI API key in an environment variable rather than in your code, so that it is not exposed by accident:
String apiKey = System.getenv("OPENAI_API_KEY");
Create a ChatModel, here an OpenAiChatModel:
ChatModel model = OpenAiChatModel.builder()
.apiKey(apiKey)
.modelName("gpt-6-luna")
.reasoningEffort("none")
.build();
reasoningEffort("none") turns off the model's reasoning, which makes answers faster and cheaper.
You need it for the tools in step 4: with this model, the OpenAI API that OpenAiChatModel uses
(Chat Completions) accepts tools only without reasoning.
Now it is time to chat:
String answer = model.chat("Say 'Hello World'");
System.out.println(answer); // Hello World
ChatModel is the low-level API: you control every message yourself.
Most applications use the high-level API instead, AI Services.
3. Create an AI Service
Describe what you need as a Java interface. LangChain4j implements it for you:
interface Assistant {
@SystemMessage("You are a friendly support agent of an online shop.")
String chat(String userMessage);
}
Assistant assistant = AiServices.create(Assistant.class, model);
String answer = assistant.chat("Hello! How can you help me?");
When you call chat, LangChain4j sends the system message and your message to the model and returns its answer.
AiServices.create(...) is a shortcut: the next steps use AiServices.builder(...), which lets you add tools,
chat memory and more.
Methods of an AI Service can also take several parameters, use prompt templates,
and return your own classes and records instead of a String:
see AI Services and Structured Outputs.
4. Give the model a tool
Tools let the model call your Java code. Annotate a method with @Tool and describe what it does,
then build the assistant with the tool instead of the one from step 3:
class OrderTools {
@Tool("Returns the delivery status of an order")
String getOrderStatus(String orderId) {
return "Order " + orderId + ": shipped, arrives tomorrow";
}
}
Assistant assistant = AiServices.builder(Assistant.class)
.chatModel(model)
.tools(new OrderTools())
.build();
String answer = assistant.chat("Where is my order 12345?");
// Your order 12345 has shipped and is expected to arrive tomorrow.
The model decides when it needs the tool. LangChain4j runs getOrderStatus with the order ID chosen by the model,
sends the result back to the model, and returns the model's final answer.
The user can influence which arguments the model passes, so treat them like user input: in a real application,
check for example that the order belongs to the current user.
Compile your code with the -parameters option, so that the model sees the real parameter names
(orderId instead of arg0): see Parameter Name.
See Tools for more, and MCP to use the tools of MCP servers.
5. Remember the conversation
By default, each call is independent: the model does not see your earlier messages.
Add a chat memory to keep the conversation, again instead of the assistant from the previous step:
Assistant assistant = AiServices.builder(Assistant.class)
.chatModel(model)
.tools(new OrderTools())
.chatMemory(MessageWindowChatMemory.withMaxMessages(10))
.build();
assistant.chat("Where is my order 12345?");
String answer = assistant.chat("And when will it arrive?");
// It is expected to arrive tomorrow.
MessageWindowChatMemory keeps up to 10 messages, including the system message, tool calls and tool results,
and sends them to the model with each new message.
This assistant has one conversation, shared by everyone who calls it. In an application with several users,
give each user their own memory with @MemoryId and a chatMemoryProvider
(see Chat Memory in AI Services); otherwise users see each other's messages.
To store conversations in a database, see Chat Memory.
Complete code
All steps in one file, ready to run:
import dev.langchain4j.agent.tool.Tool;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.service.SystemMessage;
public class GetStarted {
interface Assistant {
@SystemMessage("You are a friendly support agent of an online shop.")
String chat(String userMessage);
}
static class OrderTools {
@Tool("Returns the delivery status of an order")
String getOrderStatus(String orderId) {
return "Order " + orderId + ": shipped, arrives tomorrow";
}
}
public static void main(String[] args) {
ChatModel model = OpenAiChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName("gpt-6-luna")
.reasoningEffort("none")
.build();
Assistant assistant = AiServices.builder(Assistant.class)
.chatModel(model)
.tools(new OrderTools())
.chatMemory(MessageWindowChatMemory.withMaxMessages(10))
.build();
System.out.println(assistant.chat("Where is my order 12345?"));
System.out.println(assistant.chat("And when will it arrive?"));
}
}
Use a local model
To run a model on your own machine, install Ollama, download a model
(for example ollama pull llama3.2), and add the Ollama dependency:
- Maven
- Gradle
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-ollama</artifactId>
<version>1.24.1</version>
</dependency>
implementation 'dev.langchain4j:langchain4j-ollama:1.24.1'
Then create an OllamaChatModel instead of the OpenAiChatModel:
ChatModel model = OllamaChatModel.builder()
.baseUrl("http://localhost:11434")
.modelName("llama3.2")
.build();
The rest of the code stays the same. This is how you switch between the supported LLM providers. The model and its integration need to support the features you use: for example, tools need a model with tool calling (see the Tools column of the comparison table).
Next steps
- AI Services: everything an AI Service can do.
- RAG (Retrieval-Augmented Generation): answer questions from your own documents.
- Agents: combine several AI Services and tools into workflows and agents.
- Guardrails and tool guardrails: check what goes into the model and what comes out, and the calls and the results of tools.
- Observability and Testing: get ready for production.
- Quarkus, Spring Boot, Helidon and Micronaut: use LangChain4j in your framework.
- Examples: complete applications in plain Java and with frameworks, and the Quarkus LangChain4j samples.