LangChain4j
models-langchain4j adapts the Models TextGenerationModel contract to
LangChain4j’s blocking ChatModel and StreamingChatModel APIs. It uses the
same in-process tokenizer, chat template, generation loop, and selected backend
as plain Java; it does not start or call an HTTP model server.
Compatibility CI exercises LangChain4j 1.0.0, 1.13.1, and 1.17.2. The application owns the LangChain4j version because the Models adapter does not add it transitively.
Dependencies
dependencies {
implementation("dev.langchain4j:langchain4j:1.17.2")
implementation("org.modeljars:modeljars:0.1.78")
implementation(
"org.modeljars.huggingface:" +
"ggml-org.qwen3-0.6b-gguf.q4_0:" +
"3.0.0-q4_0.1"
)
implementation("com.integrallis:models-langchain4j:0.5.20")
}
Route Local And Hosted Models
RoutedChatModel and RoutedStreamingChatModel bind ordinary LangChain4j
clients to a provider-neutral ModelFleet. A fleet can contain local Models
adapters, hosted provider clients, and private gateways. The selected delegate
receives the original ChatRequest, including its tools and options. Streaming
failover occurs only before a partial response reaches the caller. See
Model Routing for configuration, feedback, and session
continuity.
Blocking Chat
The adapter maps LangChain4j system, user, assistant, and tool messages to the selected Models chat template. Framework message text remains ordinary text; only template-owned delimiters are treated as model control tokens.
import static org.modeljars.catalog.Qwen3_0_6b_Q4_0.MODEL;
import com.integrallis.models.api.SamplingOptions;
import com.integrallis.models.langchain4j.ModelsChatModel;
import java.util.List;
import org.modeljars.ModelJars;
var defaults = SamplingOptions.builder()
.temperature(0.0f)
.maxTokens(128)
.stopSequences(List.of("</answer>"))
.build();
try (var runtime = ModelJars.openRuntime(MODEL)) {
var model = new ModelsChatModel(
runtime.model(),
runtime.chatTemplate(),
defaults);
String answer = model.chat("Answer using only the supplied context.");
System.out.println(answer);
System.out.println(model.diagnostics().backend());
}
Use the template recorded by the exact ModelJar. Models does not infer a chat template from an architecture family because two instruction-tuned artifacts with the same architecture can require different role delimiters.
Token Usage
Blocking responses carry exact prompt, completion, and total counts in
LangChain4j’s TokenUsage. Prompt tokens are counted after the qualified chat
template has rendered the request; completion tokens are the non-terminal
tokens generated by the Models runtime.
var request = ChatRequest.builder()
.messages(UserMessage.from("Name one JVM language."))
.build();
ChatResponse response = model.chat(request);
System.out.printf(
"prompt=%d completion=%d total=%d%n",
response.tokenUsage().inputTokenCount(),
response.tokenUsage().outputTokenCount(),
response.tokenUsage().totalTokenCount());
Custom TextGenerationModel implementations that only invoke the legacy
TokenStream.onComplete() callback remain compatible. Their responses leave
token usage absent instead of fabricating zero counts.
Tool Calling
When a ChatRequest declares LangChain4j ToolSpecification instances, the
adapter serializes LangChain4j’s typed JsonSchemaElement tree to JSON Schema
text and renders the tools into the selected Models chat template. Model output
is scanned back into LangChain4j ToolExecutionRequest values, and the response
finish reason is set to TOOL_EXECUTION so LangChain4j’s tool loop can proceed.
GPT-OSS Harmony calls use the same path: current constrained-JSON headers and the
older recipient-before-channel form are both recognized, named tool results are
rendered back into Harmony history, and private analysis is not exposed as a final
assistant answer.
import dev.langchain4j.agent.tool.ToolSpecification;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.request.ChatRequest;
import dev.langchain4j.model.chat.request.json.JsonEnumSchema;
import dev.langchain4j.model.chat.request.json.JsonObjectSchema;
import dev.langchain4j.model.chat.response.ChatResponse;
import java.util.List;
var setModeTool = ToolSpecification.builder()
.name("set_mode")
.description("Set the HVAC mode")
.parameters(JsonObjectSchema.builder()
.addProperty("mode", JsonEnumSchema.builder()
.enumValues(List.of("cool", "heat"))
.build())
.required("mode")
.build())
.build();
var request = ChatRequest.builder()
.messages(UserMessage.from("Switch the thermostat to cooling."))
.toolSpecifications(setModeTool)
.build();
ChatResponse response = model.chat(request);
if (response.aiMessage().hasToolExecutionRequests()) {
response.aiMessage().toolExecutionRequests()
.forEach(call -> System.out.println(call.name() + " " + call.arguments()));
}
Qwen3 1.7B Q8_0 is qualified for the complete generative tool loop. The
real-weight release test uses AiServices, invokes a Java weather method with
zipcode 88252, passes its structured result back to the model, and checks the
grounded natural-language answer. It does not use a host-side result renderer.
Needle 2 is instead a compact action selector; an application using it must
render the tool result itself after executing the request.
The streaming adapter uses the same declaration and recovery path. When tools are declared, it buffers generated text until the tool call is complete and then delivers one terminal response, because LangChain4j cannot execute a partial tool request.
When the wrapped model exposes a contrastive head and more than five tools are declared, the adapter retrieves the five most relevant schemas before it renders the prompt. Schema vectors are cached in a bounded per-adapter index; subsequent requests embed the user query without re-embedding an unchanged tool catalog. The selected schemas also define the decoding constraint.
Schema-Constrained Tool Decoding
If the wrapped Models runtime implements ConstrainedTextGenerationModel, the
LangChain4j adapter compiles supported tool parameter schemas into a token
constraint and passes it into the generation loop. Sampling then admits only
tokens that keep the output on a valid tool-call string. For supported schemas,
this prevents invalid enumerable tool-call syntax from being decoded rather
than only asking the model to follow the schema.
For ChatML and Llama 3, the LangChain4j adapter constrains finite tool-call spaces:
-
tool syntax must be one of the non-array-wrapped Models JSON formats, such as ChatML or Llama 3 JSON-native tool calls
-
argument properties must be string
enumvalues, or absent -
every
requiredproperty must be one of those enumerable properties -
the compiled call set is capped to keep decoding checks bounded
Schemas that require open text, numbers, arrays, nested objects, conditionals, references, or any other value space the adapter cannot enumerate are not partially constrained. The adapter falls back to ordinary tool calling for those schemas, leaving LangChain4j tool execution behavior unchanged.
Needle 2 has a separate array-aware grammar compiled directly from JSON Schema.
It supports objects, arrays, strings, integers, numbers, booleans, nulls,
enum, const, oneOf, and anyOf, with an explicit bound on optional-object
expansion.
Request Options
Non-null LangChain4j request values override adapter defaults for temperature,
top-p, top-k, maximum output tokens, and stop sequences. An absent request value
retains the configured Models default. A non-empty request stopSequences list
replaces the default list for that generation; repetition penalty and seed
remain Models defaults because LangChain4j’s common request contract does not
expose them consistently across supported versions.
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.request.ChatRequest;
import dev.langchain4j.model.chat.response.ChatResponse;
import java.util.List;
var request = ChatRequest.builder()
.messages(List.of(UserMessage.from("Return one cited sentence.")))
.temperature(0.2)
.maxOutputTokens(96)
.stopSequences(List.of("</answer>"))
.build();
ChatResponse response = model.chat(request);
System.out.println(response.aiMessage().text());
Streaming Chat
ModelsStreamingChatModel emits each decoded token fragment through
onPartialResponse in generation order. It then invokes exactly one terminal
callback: onCompleteResponse with the accumulated answer or onError with
the original generation failure. It does not invoke completion after an error.
The terminal ChatResponse carries the same exact TokenUsage as blocking
chat. Generation starts on the thread that calls doChat, so handlers should
return quickly if that thread serves other work.
import com.integrallis.models.langchain4j.ModelsStreamingChatModel;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.request.ChatRequest;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.chat.response.StreamingChatResponseHandler;
import java.util.List;
var streaming = new ModelsStreamingChatModel(
runtime.model(),
runtime.chatTemplate(),
defaults);
var request = ChatRequest.builder()
.messages(List.of(UserMessage.from("List the retrieved facts.")))
.stopSequences(List.of("</answer>"))
.build();
streaming.doChat(request, new StreamingChatResponseHandler() {
@Override
public void onPartialResponse(String token) {
System.out.print(token);
}
@Override
public void onCompleteResponse(ChatResponse response) {
System.out.println();
System.out.println("Complete: " + response.aiMessage().text());
}
@Override
public void onError(Throwable failure) {
failure.printStackTrace();
}
});
The application owns and closes the TextGenerationModel; the blocking and
streaming adapters do not close it.
RAG With Vectors
vectors-langchain4j implements LangChain4j’s standard
EmbeddingStore<TextSegment>. It composes directly with ModelsChatModel in
AiServices, so retrieval and generation stay in the same JVM.
dependencies {
implementation("com.integrallis:vectors-langchain4j:0.1.34")
}
ModelsEmbeddingModel supplies the EmbeddingModel. See
Embeddings for producing the backend it wraps.
For cross-encoder scoring, ModelsScoringModel implements LangChain4j’s standard
ScoringModel. See Reranking for the plain Java model and
the real-artifact adapter gate.
interface Assistant {
String answer(String question);
}
var embeddingModel = new ModelsEmbeddingModel(embeddingBackend);
var collection = VectorCollection.builder()
.dimension(embeddingModel.dimension())
.metric(SimilarityFunction.COSINE)
.indexType(IndexType.HNSW)
.build();
try (var runtime = ModelJars.openRuntime(MODEL);
var store = JavaVectorsEmbeddingStore.builder(collection)
.commitAfterAdd(true)
.build()) {
var retriever = EmbeddingStoreContentRetriever.builder()
.embeddingModel(embeddingModel)
.embeddingStore(store)
.maxResults(4)
.build();
var assistant = AiServices.builder(Assistant.class)
.chatModel(new ModelsChatModel(
runtime.model(),
runtime.chatTemplate(),
defaults))
.contentRetriever(retriever)
.build();
String answer = assistant.answer("What does the retrieved policy allow?");
}
Retrieval integration does not validate generated claims by itself. Apply the RAG Validation policy when the application requires retrieval gates, citation checks, and bounded fallback.
