Skip to main content

AI Services

LangChain4j offers low-level components such as ChatModel, ChatMessage and ChatMemory. Working at this level is very flexible and gives you total freedom, but it also forces you to write a lot of boilerplate code. Since LLM-powered applications usually require not just a single component but multiple components working together (e.g., prompt templates, chat memory, LLMs, output parsers, RAG components: embedding models and stores) and often involve multiple interactions, orchestrating them all becomes even more cumbersome.

We want you to focus on business logic, not on low-level implementation details. AI Services, the high-level API of LangChain4j, help with that. The older Chains are described at the end of this page.

AI Services​

AI Services are tailored for Java. The idea is to hide the complexities of interacting with LLMs and other components behind a simple API.

This approach is very similar to Spring Data JPA or Retrofit: you declaratively define an interface with the desired API, and LangChain4j provides an object (proxy) that implements this interface. You can think of AI Service as a component of the service layer in your application. It provides AI services. Hence the name.

AI Services handle the most common operations:

  • Formatting inputs for the LLM
  • Parsing outputs from the LLM

They also support more advanced features:

  • Chat memory
  • Tools
  • RAG

AI Services can be used to build stateful chatbots that facilitate back-and-forth interactions, as well as to automate processes where each call to the LLM is isolated.

Let's take a look at the simplest possible AI Service. After that, we will explore more complex examples.

Simplest AI Service​

First, we define an interface with a single method, chat, which takes a String as input and returns a String.

interface Assistant {

String chat(String userMessage);
}

Then, we create our low-level components. These components will be used under the hood of our AI Service. In this case, we just need the ChatModel:

ChatModel model = OpenAiChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName(GPT_4_O_MINI)
.build();

Finally, we can use the AiServices class to create an instance of our AI Service:

Assistant assistant = AiServices.create(Assistant.class, model);
note

In Quarkus and Spring Boot applications, the autoconfiguration handles creating an Assistant bean. This means you do not need to call AiServices.create(...), you can simply inject/autowire the Assistant wherever it is needed.

Now we can use Assistant:

String answer = assistant.chat("Hello");
System.out.println(answer); // Hello, how can I help you?

How does it work?​

You provide the Class of your interface to AiServices along with the low-level components, and AiServices creates a proxy object implementing this interface. Currently, it uses reflection, but we are considering alternatives as well. This proxy object handles all the conversions for inputs and outputs. In this case, the input is a single String, but we are using a ChatModel which takes ChatMessage as input. So, AiService will automatically convert it into a UserMessage and invoke ChatModel. Since the output type of the chat method is a String, after ChatModel returns AiMessage, it will be converted into a String before being returned from the chat method.

AI Services in Quarkus Application​

LangChain4j Quarkus extension greatly simplifies using AI Services in Quarkus applications.

More information can be found here.

AI Services in Spring Boot Application​

LangChain4j Spring Boot starter greatly simplifies using AI Services in Spring Boot applications.

@SystemMessage​

Now, let's look at a more complicated example. We'll force the LLM reply using slang 😉

This is usually achieved by providing instructions in the SystemMessage.

interface Friend {

@SystemMessage("You are a good friend of mine. Answer using slang.")
String chat(String userMessage);
}

Friend friend = AiServices.create(Friend.class, model);

String answer = friend.chat("Hello"); // Hey! What's up?

In this example, we have added the @SystemMessage annotation with a system prompt template we want to use. This will be converted into a SystemMessage behind the scenes and sent to the LLM along with the UserMessage.

@SystemMessage can also load a prompt template from resources: @SystemMessage(fromResource = "my-prompt-template.txt")

@SystemMessage can also be declared on the AI Service interface, in which case it applies to all methods exposed by that AI Service, including inherited ones:

@SystemMessage("You are a good friend of mine. Answer using slang.")
interface Friend {

String chat(String userMessage);

String chatAgain(String userMessage);
}

A @SystemMessage declared on a method takes precedence over one declared on the interface. A @SystemMessage declared only on a parent interface is not inherited by a child AI Service interface.

System Message Provider​

System messages can also be defined dynamically with the system message provider:

Friend friend = AiServices.builder(Friend.class)
.chatModel(model)
.systemMessageProvider(chatMemoryId -> "You are a good friend of mine. Answer using slang.")
.build();

As you can see, you can provide different system messages based on a chat memory ID (user or conversation).

System Message Transformer​

A system message transformer allows you to dynamically modify the system message on every invocation, after it has been resolved from @SystemMessage or systemMessageProvider, but before the chatRequestTransformer runs. This is useful when you need to append or prepend content to the system message regardless of how it was originally configured.

Friend friend = AiServices.builder(Friend.class)
.chatModel(model)
.systemMessageProvider(chatMemoryId -> "You are a good friend of mine. Answer using slang.")
.systemMessageTransformer(systemMessage -> systemMessage + " Today's date is " + LocalDate.now() + ".")
.build();

If no system message was configured, the transformer receives null.

When you also need access to the invocation context (e.g., the method name or its arguments), use the two-argument overload that accepts an InvocationContext:

Friend friend = AiServices.builder(Friend.class)
.chatModel(model)
.systemMessageProvider(chatMemoryId -> "You are a good friend of mine. Answer using slang.")
.systemMessageTransformer((systemMessage, context) ->
systemMessage + " Tenant: " + context.invocationParameters().get("tenant") + ".")
.build();

@UserMessage​

Now, let's assume the model we use does not support system messages, or maybe we just want to use UserMessage for that purpose.

interface Friend {

@UserMessage("You are a good friend of mine. Answer using slang. {{it}}")
String chat(String userMessage);
}

Friend friend = AiServices.create(Friend.class, model);

String answer = friend.chat("Hello"); // Hey! What's shakin'?

We have replaced the @SystemMessage annotation with @UserMessage and specified a prompt template containing the variable it that refers to the only method argument.

It's also possible to annotate the String userMessage with @V and assign a custom name to the prompt template variable:

interface Friend {

@UserMessage("You are a good friend of mine. Answer using slang. {{message}}")
String chat(@V("message") String userMessage);
}
note

Please note that using @V is not necessary when using LangChain4j with Quarkus or Spring Boot. This annotation is necessary only when the -parameters option is not enabled during Java compilation.

@UserMessage can also load a prompt template from resources: @UserMessage(fromResource = "my-prompt-template.txt")

Programmatic ChatRequest rewriting​

In some circumstances it can be useful to modify the ChatRequest before it is sent to the LLM. For instance, it may be necessary to append some additional context to the user message or modify the system message based on some external conditions.

It is possible to do so by configuring the AI Service with a UnaryOperator<ChatRequest> implementing the transformation that be applied to the ChatRequest:

Assistant assistant = AiServices.builder(Assistant.class)
.chatModel(model)
.chatRequestTransformer(transformingFunction) // Configures the transformation function to be applied to the ChatRequest
.build();

In case it is needed to also access the ChatMemory to implement the required ChatRequest transformation, it is also possible to configure the chatRequestTransformer method with a BiFunction<ChatRequest, Object, ChatRequest>, where the second parameter passed to this function is the memory ID.

ChatRequestParameters​

Another degree of freedom is the possibility to configure parameters (e.g., temperature, toolsChoice, maximum tokens, etc.) on a per-call basis. For example, you might want some requests to be more “creative” (higher temperature) and others to be more deterministic (lower temperature).

To achieve this, you can create an AI Service method that also accepts an argument of type ChatRequestParameters (or any provider-specific type like OpenAiChatRequestParameters). This tells LangChain4j to accept and merge these parameters during each invocation.

note

Note that toolSpecifications and responseFormat specified in the ChatRequestParameters will override those generated by AI Service.

Define your interface with a second parameter:

interface AssistantWithChatParams {

String chat(@UserMessage String userMessage, ChatRequestParameters params);
}

Build the AI Service:

AssistantWithChatParams assistant = AiServices.builder(AssistantWithChatParams.class)
.chatModel(openAiChatModel) // or whichever model
.build();

Call it with any per-call parameters:

ChatRequestParameters customParams = ChatRequestParameters.builder()
.temperature(0.85)
.build();

String answer = assistant.chat("Hi there!", customParams);

The ChatRequestParameters passed as an argument to the AI Service method is also propagated to the chatRequestTransformer discussed in the former section, so it can be also accessed and modified there if necessary.

Examples of valid AI Service methods​

Below are some examples of valid AI service methods.

UserMessage
String chat(String userMessage);

String chat(@UserMessage String userMessage);

String chat(@UserMessage String userMessage, ChatRequestParameters parameters);

String chat(@UserMessage String userMessage, @V("country") String country); // userMessage contains "{{country}}" template variable

String chat(@UserMessage String userMessage, @UserMessage Content content); // content can be one of: TextContent, ImageContent, AudioContent, VideoContent, PdfFileContent

String chat(@UserMessage String userMessage, @UserMessage ImageContent image); // second argument can be one of: TextContent, ImageContent, AudioContent, VideoContent, PdfFileContent

String chat(@UserMessage String userMessage, @UserMessage List<Content> contents);

String chat(@UserMessage String userMessage, @UserMessage List<ImageContent> images);

@UserMessage("What is the capital of Germany?")
String chat();

@UserMessage("What is the capital of {{it}}?")
String chat(String country);

@UserMessage("What is the capital of {{country}}?")
String chat(@V("country") String country);

@UserMessage("What is the {{something}} of {{country}}?")
String chat(@V("something") String something, @V("country") String country);

@UserMessage("What is the capital of {{country}}?")
String chat(String country); // this works only in Quarkus and Spring Boot applications
SystemMessage and UserMessage
@SystemMessage("Given a name of a country, answer with a name of it's capital")
String chat(String userMessage);

@SystemMessage("Given a name of a country, answer with a name of it's capital")
String chat(@UserMessage String userMessage);

@SystemMessage("Given a name of a country, {{answerInstructions}}")
String chat(@V("answerInstructions") String answerInstructions, @UserMessage String userMessage);

@SystemMessage("Given a name of a country, answer with a name of it's capital")
String chat(@UserMessage String userMessage, @V("country") String country); // userMessage contains "{{country}}" template variable

@SystemMessage("Given a name of a country, {{answerInstructions}}")
String chat(@V("answerInstructions") String answerInstructions, @UserMessage String userMessage, @V("country") String country); // userMessage contains "{{country}}" template variable

@SystemMessage("Given a name of a country, answer with a name of it's capital")
@UserMessage("Germany")
String chat();

@SystemMessage("Given a name of a country, {{answerInstructions}}")
@UserMessage("Germany")
String chat(@V("answerInstructions") String answerInstructions);

@SystemMessage("Given a name of a country, answer with a name of it's capital")
@UserMessage("{{it}}")
String chat(String country);

@SystemMessage("Given a name of a country, answer with a name of it's capital")
@UserMessage("{{country}}")
String chat(@V("country") String country);

@SystemMessage("Given a name of a country, {{answerInstructions}}")
@UserMessage("{{country}}")
String chat(@V("answerInstructions") String answerInstructions, @V("country") String country);

Multimodality​

Additionally to, or instead of, text content, AI Service method can accept one or multiple Content or List<Content> arguments:

String chat(@UserMessage String userMessage, @UserMessage Content content);

String chat(@UserMessage String userMessage, @UserMessage ImageContent image);

String chat(@UserMessage String userMessage, @UserMessage ImageContent image, @UserMessage AudioContent audio);

String chat(@UserMessage String userMessage, @UserMessage List<Content> contents);

String chat(@UserMessage String userMessage, @UserMessage List<ImageContent> images);

String chat(Content content);

String chat(AudioContent content);

String chat(List<Content> contents);

String chat(List<AudioContent> contents);

String chat(@UserMessage Content content1, @UserMessage Content content2);

String chat(@UserMessage AudioContent audio, @UserMessage ImageContent image);

AI Service will put all contents into the final UserMessage in the order of parameter declaration.

Please check Content API for more details on the available content types.

Return Types​

AI Service method can return one of the following types:

  • String - in this case LLM-generated output is returned without any processing/parsing
  • AiMessage or ChatResponse - in this case the LLM response is returned as-is, without any processing/parsing. ChatResponse also carries metadata, such as TokenUsage and FinishReason. If AI service did multiple calls to the LLM (e.g., because tools were executed), the TokenUsage is the sum of all calls
  • Any type supported by Structured Outputs - in this case AI service will parse LLM-generated output into a desired type before returning
  • TokenStream - to receive the response as it is generated
  • CompletableFuture<T> / CompletionStage<T> or Flow.Publisher<...> - to run the interaction without blocking the calling thread (experimental)

Any type can be additionally wrapped into a Result<T> to get extra metadata about AI Service invocation:

  • TokenUsage - total number of tokens used during AI service invocation. If AI service did multiple calls to the LLM (e.g., because tools were executed), it will sum token usages of all calls.
  • Sources - Contents retrieved during RAG retrieval
  • All tools executed during AI Service invocation (both requests and results)
  • FinishReason of the final chat response
  • All intermediate ChatResponses
  • The final ChatResponse

An example:

interface Assistant {

@UserMessage("Generate an outline for the article on the following topic: {{it}}")
Result<List<String>> generateOutlineFor(String topic);
}

Result<List<String>> result = assistant.generateOutlineFor("Java");

List<String> outline = result.content();
TokenUsage tokenUsage = result.tokenUsage();
List<Content> sources = result.sources();
List<ToolExecution> toolExecutions = result.toolExecutions();
FinishReason finishReason = result.finishReason();
note

T in Result<T> is the content the LLM produces, so it has to be a type the LLM can actually generate: a String, an enum, a POJO, a collection of those, etc. LangChain4j's own types, such as ChatResponse, ChatMessage, TextSegment, Embedding or TokenUsage, cannot be used as T (nor as an element of a List<T>/Set<T> return type): the AI Service will fail with an IllegalConfigurationException when it is created. Everything the final ChatResponse carries is already available on Result<T> itself, for example:

ChatResponse chatResponse = result.finalResponse();

Structured Outputs​

If you want to receive a structured output (e.g., a complex Java object, as opposed to an unstructured text inside the String) from the LLM, you can change the return type of your AI Service method from String to some other type.

note

More info on Structured Outputs can be found here.

A few examples:

boolean as return type​

interface SentimentAnalyzer {

@UserMessage("Does {{it}} has a positive sentiment?")
boolean isPositive(String text);

}

SentimentAnalyzer sentimentAnalyzer = AiServices.create(SentimentAnalyzer.class, model);

boolean positive = sentimentAnalyzer.isPositive("It's wonderful!");
// true

Enum as return type​

enum Priority {
CRITICAL, HIGH, LOW
}

interface PriorityAnalyzer {

@UserMessage("Analyze the priority of the following issue: {{it}}")
Priority analyzePriority(String issueDescription);