The OpenAI Responses API in Java
For several years, the Chat Completions API was the standard way for an application to converse with a large language model. OpenAI introduced it in 2023, and its request format became so widespread that most model providers and most local inference servers adopted it as a compatibility layer. In March 2025, OpenAI published a successor, the Responses API, which it presents as the foundation of its platform for agentic applications. The Java ecosystem followed: Spring AI, LangChain4j and the Quarkus LangChain4j extension now each provide a model implementation that speaks this new protocol.
This article explains what the Responses API is and what it brings in comparison with the Chat Completions API. It then presents a project that implements the same small use case with three Java stacks: Spring AI on Spring Boot, LangChain4j on Spring Boot and LangChain4j on Quarkus. The article explains the code of each implementation in detail and highlights the differences between them. A single conformance test suite verifies all three implementations, so that every difference the article reports is an observed property of a stack rather than an impression.
The Chat Completions API
To understand what the Responses API changes, it is useful to recall precisely how the Chat Completions API works.
An application calls the Chat Completions API by sending an HTTP POST request to the endpoint https://api.openai.com/v1/chat/completions. This endpoint is defined by OpenAI in its API reference and in the OpenAPI description of its REST API. Other providers and local inference servers expose the same path, relative to their own base URL, because they reproduce the format that OpenAI defined. This makes Chat Completions a de facto standard rather than a published specification. The body of the request contains the name of the model and a list of messages. Each message has a role, which is system, user, assistant or tool, and a content. The following request asks a question that depends on an earlier exchange:
{
"model": "gpt-4o-mini",
"messages": [
{"role": "user", "content": "My name is Aurora. Remember it."},
{"role": "assistant", "content": "Nice to meet you, Aurora."},
{"role": "user", "content": "What is my name?"}
]
}
The provider answers with a list of choices, each of which contains one assistant message:
{
"id": "chatcmpl-B9MHDbslfkBeAs8l4bebGdFOJ6PeG",
"object": "chat.completion",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Your name is Aurora."
},
"finish_reason": "stop"
}
]
}
The essential property of this API is that it is stateless. The provider retains nothing between two requests, so the model knows about the earlier exchange only because the application sends it again. Every conversation therefore lives in the application. With each new question, the application appends the previous answer and the new question to its list and sends the complete list again. The request grows with the length of the conversation, and the application is responsible for storing, trimming and summarizing that history. The conversation memory components of Spring AI and LangChain4j exist precisely to perform this work on the client side.
Function calling follows the same principle. The application describes its functions in a tools array, in which each entry wraps a JSON Schema inside a function object. When the model decides to call a function, it answers with an assistant message carrying a tool_calls array instead of text. The application executes the function itself, appends a message that holds the result with the role tool, and sends the whole conversation again so that the model can produce its final answer. This cycle of requests, executions and new requests is called the tool loop. Every tool runs in the application, because the model only decides which tool to call and with which arguments.
What the Responses API is
OpenAI exposes the Responses API at the endpoint https://api.openai.com/v1/responses, which it defines in the same API reference and OpenAPI description. The smallest possible request contains a model and an input, which can be a simple string:
{
"model": "gpt-4o-mini",
"input": "My name is Aurora. Remember it."
}
The provider answers with a response object. Each response has its own identifier, which starts with resp_, and an output array of typed items:
{
"id": "resp_67ccd2bed1ec8190b14f964abc054267",
"object": "response",
"status": "completed",
"output": [
{
"type": "message",
"role": "assistant",
"content": [
{"type": "output_text", "text": "Nice to meet you, Aurora."}
]
}
]
}
The vocabulary changes in a meaningful way. Chat Completions exchanges messages, whereas the Responses API exchanges items. A message is one type of item among several. A function call, the output of a function call, a web search performed by the provider and the reasoning of a reasoning model are other types of items. Each of them appears in the output array as a separate, explicitly typed element. The input follows the same model: it is either a string or an array of items of the same types. The system prompt has its own field, named instructions, instead of being a message with the system role.
What the Responses API adds
The Responses API brings three capabilities that the Chat Completions API lacks. They are server side conversation state, hosted tools and a richer model of the exchange based on typed items. An additional characteristic, the publication of the protocol as an open specification, determines how widely the API can be used.
Server side conversation state
The Responses API can store each response on the provider side. The store field of the request controls this behavior, and OpenAI enables it by default. When a response is stored, the application can continue the conversation by sending only the new question together with the identifier of the previous response in the previous_response_id field:
{
"model": "gpt-4o-mini",
"input": "What is my name?",
"previous_response_id": "resp_67ccd2bed1ec8190b14f964abc054267"
}
The provider then reconstructs the conversation from its own store. The application sends one question per request, whatever the length of the conversation, and it keeps a single identifier instead of a complete history. The following diagram compares the two approaches over a conversation of two questions.

This capability has consequences that matter in production. The requests stay small, which reduces the network traffic. The provider can reuse what it already computed for the earlier part of the conversation, which improves the effectiveness of its cache. For reasoning models, the provider also keeps the reasoning items of earlier turns, which the model can use again in the following turns. An application that must keep the data on its own side can disable storage with "store": false and send the history explicitly, in the manner of Chat Completions. In that case, the application can request the reasoning items in encrypted form, through "include": ["reasoning.encrypted_content"], and send them back with the history, which preserves the continuity of the reasoning without any storage at the provider. OpenAI also offers a Conversations API, which manages a durable conversation object that several responses can share, as an alternative to chaining identifiers.
Hosted tools
With Chat Completions, every tool is a function that the application executes. The Responses API adds hosted tools, which the provider executes itself during the generation of a response. OpenAI offers, among others, a web search tool, a file search tool over vector stores, a code interpreter, an image generation tool and a tool that calls a remote MCP server. The application enables a hosted tool by adding an entry with its type to the tools array:
{
"model": "gpt-4o-mini",
"input": "What is the domain name of the Open Responses website?",
"tools": [
{"type": "web_search"}
]
}
The provider performs the search, adds a web_search_call item to the output and writes an answer based on the results. The application receives the final answer in a single exchange, without executing anything. Function tools remain available and coexist with hosted tools in the same request. Their declaration is slightly simpler than in Chat Completions, because the name, the description and the parameters sit directly in the tool entry instead of inside a nested function object:
{
"type": "function",
"name": "orderStatus",
"description": "Returns the status code of an order",
"parameters": {
"type": "object",
"properties": {"orderId": {"type": "string"}},
"required": ["orderId"]
}
}
When the model calls such a function, the output contains a function_call item with a call_id. The application executes the function and returns the result as a function_call_output item that carries the same call_id. The tool loop therefore still exists for function tools, and it remains the responsibility of the application or of the framework that the application uses.
Typed items
Because every element of the exchange is a typed item, an application can inspect precisely what happened during a response. It can tell a message from a function call, a web search or a reasoning step without interpreting text. This structure is what makes the API suitable for agents, which chain several model calls, tool executions and decisions within a single task.
An open specification
The wire format of the Responses API is published as an open specification named Open Responses, documented at openresponses.org. OpenAI donated it to the Agentic AI Foundation of the Linux Foundation, and several providers and inference servers implement it, including Ollama, vLLM, OpenRouter and Hugging Face. This openness has a practical consequence for the project described below: its tests run against Ollama on a developer workstation or in continuous integration, without an OpenAI account.
Implementing the format of the specification is one obligation, and offering every capability of OpenAI is another. The project shows that Ollama accepts the previous_response_id field and ignores it, because it keeps no state between requests. An application that relies on server side state therefore requires a provider that stores responses.
What a Java framework must provide
From the point of view of a Java developer, the Responses API raises three concrete questions for each framework. The question of endpoint selection asks how the application chooses the Responses API instead of Chat Completions. The question of server side state asks whether the application can send previous_response_id and whether the framework lets the provider store the responses. The question of hosted tools asks whether the application can enable a tool such as web_search, and in what form. The rest of this article answers these three questions for each of the three stacks.
The project
The project, named java-ai-responses-rosetta, follows the method of the book Java AI Frameworks and of its companion repository. The same behavior is implemented in the idiomatic manner of each stack and verified by one shared conformance suite. The name Rosetta refers to the Rosetta Stone, which carries the same text in three scripts. In the same way, the project carries the same use case in three stacks, which makes their differences directly comparable.
The project requires Java 21 and is built with Maven, through the Maven wrapper that the repository provides. Every library is at its latest stable version at the time of writing:
| Module | Library | Runtime |
|---|---|---|
responses-spring-ai-boot |
Spring AI 2.1.0 | Spring Boot 4.2.0 |
responses-langchain4j-boot |
LangChain4j 1.24.0 | Spring Boot 4.2.0 |
responses-langchain4j-quarkus |
Quarkus LangChain4j 1.15.1, based on LangChain4j 1.23.0 | Quarkus 3.40.1.1 |
Quarkus LangChain4j 1.15.1 is the latest stable release of the extension and is built on Quarkus 3.40.1.1. The line of the extension that targets Quarkus 4 is a release candidate at the time of writing, which explains the choice of this Quarkus version.
The use case
Each stack exposes one REST endpoint, POST /chat. The endpoint accepts a question, optionally the identifier of a previous response and a flag that enables the hosted web search tool:
{
"question": "What is the status of order 42?",
"previousResponseId": null,
"webSearch": false
}
It returns the answer of the model together with the identifier of the response, which the client can send back as previousResponseId to continue the conversation:
{
"answer": "The status of order 42 is QX7731.",
"responseId": "resp_68a1c3f0b2e48191a9f0d5c2e7b31c4f"
}
Each stack also registers one local function tool, named orderStatus, which returns the status code of an order. The status of order 42 is QX7731. This value is deliberately an opaque token that the model can obtain only by calling the tool. When the answer contains QX7731, the test therefore has proof that the tool was called. A value such as SHIPPED would be a poor proof, because a model can guess it, and small models tend to rephrase such words.
The use case thus exercises the three capabilities discussed above: a function tool executed by the application, a hosted tool executed by the provider and a conversation continued through previous_response_id.
The module layout
The project consists of a parent POM and five modules:
java-ai-responses-rosetta/
├── responses-common/
├── responses-langchain4j-common/
├── responses-spring-ai-boot/
├── responses-langchain4j-boot/
└── responses-langchain4j-quarkus/
The module responses-common holds what every stack shares: the contract of the REST endpoint, the data behind the orderStatus tool and the conformance suite, which it publishes as a test JAR. The module responses-langchain4j-common holds the service class that the two LangChain4j stacks share. The three remaining modules are the applications themselves. The following diagram shows the dependencies between the modules. A solid arrow denotes a compile dependency and a dashed arrow denotes a test dependency on the conformance suite.

The module responses-langchain4j-common deserves attention. The two LangChain4j stacks use exactly the same service class, so the library code is identical on Spring Boot and on Quarkus, and the two runtimes differ only in the way they construct the model and inject it. Sharing the class makes this observation visible in the structure of the project itself.
The shared contract
The module responses-common defines the contract in four small types of the package fr.simplex_software.workshop.responses.api. The request body is a record whose question component is validated with Jakarta Bean Validation:
public record Question(@NotBlank String question,
String previousResponseId, boolean webSearch)
{
}
The response body is another record:
public record Answer(String answer, String responseId)
{
}
The service interface states the single operation that each stack implements:
public interface ResponsesService
{
Answer chat(Question question);
}
Finally, the class OrderStatuses holds the data that the orderStatus tool returns. Each stack declares its tool with the annotations of its own library, and every declaration delegates to this class, so the three tools return the same values:
public final class OrderStatuses
{
private static final Map<String, String> STATUSES =
Map.of("42", "QX7731");
private OrderStatuses()
{
}
public static String statusOf(String orderId)
{
return STATUSES.getOrDefault(orderId.strip(), "UNKNOWN");
}
}
The contract depends only on the Jakarta Validation API. It contains nothing specific to Spring, Quarkus, Spring AI or LangChain4j, and each stack can therefore use it unchanged.
Spring AI on Spring Boot
The module responses-spring-ai-boot depends on the Spring Boot web and validation starters and on the Spring AI starter for OpenAI, spring-ai-starter-model-openai.
Selecting the Responses API
Spring AI provides two OpenAI chat models: OpenAiChatModel, which calls Chat Completions, and OpenAiResponsesChatModel, which calls the Responses API. The application chooses between them through configuration alone, in application.properties:
spring.ai.model.chat=openai
spring.ai.openai.chat.api=responses
spring.ai.openai.api-key=${OPENAI_API_KEY:not-set}
spring.ai.openai.responses.model=gpt-4o-mini
spring.ai.openai.responses.temperature=0.0
The property spring.ai.openai.chat.api takes the value chat-completions by default. With the value responses, the autoconfiguration creates an OpenAiResponsesChatModel and connects it to the usual ChatClient. The options of this model live under the prefix spring.ai.openai.responses, which is distinct from the prefix of the Chat Completions model. The temperature is set to zero to make the answers as reproducible as possible, which helps the tests.
The tool
The local tool is a Spring component whose method carries the @Tool annotation of Spring AI. The annotation gives the tool its name and its description, which the model reads to decide when to call it. The @ToolParam annotation describes the parameter:
@Component
public class OrderTools
{
@Tool(name = "orderStatus",
description = "Returns the status code of an order")
public String orderStatus(
@ToolParam(description = "the order id") String orderId)
{
return OrderStatuses.statusOf(orderId);
}
}
The service
The service implements ResponsesService with the ChatClient fluent API:
@Service
public class SpringAiResponsesService implements ResponsesService
{
private final ChatClient chatClient;
public SpringAiResponsesService(ChatClient.Builder chatClientBuilder,
OrderTools orderTools)
{
this.chatClient = chatClientBuilder.defaultTools(orderTools).build();
}
@Override
public Answer chat(Question question)
{
var prompt = chatClient.prompt().user(question.question());
if (question.webSearch())
prompt = prompt.options(OpenAiResponsesChatOptions.builder()
.hostedTools(HostedTool.WebSearch.of()));
var response = prompt.call().chatResponse();
return new Answer(response.getResult().getOutput().getText(),
response.getMetadata().getId());
}
}
The constructor receives the ChatClient.Builder that Spring AI configures automatically, together with the tool component. The call to defaultTools(orderTools) registers the annotated method as a tool for every prompt that this client sends.
The method chat builds a prompt from the question. When the client requested a web search, the method adds request options of type OpenAiResponsesChatOptions, which are specific to the Responses model. Spring AI represents each hosted tool as a type: HostedTool.WebSearch, HostedTool.FileSearch, HostedTool.CodeInterpreter, HostedTool.ImageGeneration and HostedTool.Mcp. The application therefore enables web search with a typed call, and the compiler verifies the name of the tool.
The call to call().chatResponse() sends the request and returns the complete response. Spring AI runs the tool loop itself, in a ToolCallingAdvisor that ChatClient registers automatically. When the model requests the orderStatus function, the framework invokes the annotated method, sends the result back to the model and returns only the final answer. The service code contains no trace of this loop. The identifier of the response, which starts with resp_ when the backend is OpenAI, is available in the metadata of the response.
Server side state in Spring AI
One field of the question is absent from this service: previousResponseId. Spring AI 2.1.0 sends "store": false on every request to the Responses API and offers no option to send previous_response_id. The documentation of the class OpenAiResponsesChatOptions presents this as a deliberate design. The Responses model of Spring AI is stateless, so the chat memory, the advisors and retrieval augmented generation work exactly as they do with Chat Completions. For reasoning models, Spring AI requests the reasoning of each response in encrypted form and sends it back with the following requests, which preserves the continuity of the reasoning without any storage at OpenAI. With Spring AI, the conversation history therefore remains in the application, exactly as with Chat Completions. A Spring AI application that needs a conversation uses its chat memory advisors, which store the history on the client side and send it with every request. The Responses API thus provides two of its three capabilities to a Spring AI application: hosted tools and typed items, among which the encrypted reasoning items that Spring AI replays.
The REST controller
The controller is identical in the two Spring Boot stacks. It validates the question and delegates to the service:
@RestController
public class ChatController
{
private final ResponsesService responsesService;
public ChatController(ResponsesService responsesService)
{
this.responsesService = responsesService;
}
@PostMapping("/chat")
public Answer chat(@Valid @RequestBody Question question)
{
return responsesService.chat(question);
}
}
The @Valid annotation activates the @NotBlank constraint of the record. A blank question produces the HTTP status 400 before the service is invoked. The property spring.mvc.problemdetails.enabled=true makes Spring MVC describe such errors in the standard Problem Details format of RFC 9457.
The shared LangChain4j service
LangChain4j offers two levels of abstraction. At the lower level, the ChatModel interface sends a ChatRequest and returns a ChatResponse. At the higher level, AI services generate the implementation of a Java interface and handle the prompt, the memory, the tools and the tool loop. For the Responses API, LangChain4j provides the class OpenAiResponsesChatModel in the langchain4j-open-ai module. The class carries the @Experimental annotation, which signals that its API may still change. The shared service uses an AI service built on top of this model.
Passing the Responses parameters to an AI service
The parameters that are specific to the Responses API, among them previousResponseId and serverTools, belong to the class OpenAiResponsesChatRequestParameters, which extends the generic DefaultChatRequestParameters class of LangChain4j. An AI service method can declare a parameter of type ChatRequestParameters. When the application passes an instance of OpenAiResponsesChatRequestParameters through this parameter, the AI service merges it with the parameters that it builds itself, such as the specifications of the tools, by calling the method defaultedBy. The class OpenAiResponsesChatRequestParameters implements this method so that the merged result keeps its type, and therefore its Responses fields. The AI service then uses the merged parameters for every request of the invocation, including the requests of its tool loop.
The interface of the AI service is short:
interface ResponsesAssistant
{
Result<String> chat(@UserMessage String question,
ChatRequestParameters parameters);
}
The @UserMessage annotation designates the argument that becomes the user message. The return type Result<String> gives access to the text of the answer through the method content and to the final ChatResponse of the model through the method finalResponse, which carries the identifier of the response. The interface is package private, because only the shared service uses it.
The tool
The tool class uses the @Tool and @P annotations of LangChain4j:
public class OrderTools
{
@Tool(name = "orderStatus",
value = "Returns the status code of an order")
public String orderStatus(@P("the order id") String orderId)
{
return OrderStatuses.statusOf(orderId);
}
}
The service
The class LangChain4jResponsesService lives in the module responses-langchain4j-common:
public class LangChain4jResponsesService implements ResponsesService
{
private static final List<Map<String, Object>> WEB_SEARCH =
List.of(Map.of("type", "web_search"));
private static final int MAX_TOOL_ROUNDS = 5;
private final ResponsesAssistant assistant;
public LangChain4jResponsesService(ChatModel chatModel)
{
this.assistant = AiServices.builder(ResponsesAssistant.class)
.chatModel(chatModel)
.tools(new OrderTools())
.maxToolCallingRoundTrips(MAX_TOOL_ROUNDS)
.build();
}
@Override
public Answer chat(Question question)
{
var parameters = OpenAiResponsesChatRequestParameters.builder()
.previousResponseId(question.previousResponseId());
if (question.webSearch())
parameters.serverTools(WEB_SEARCH);
var result = assistant.chat(question.question(), parameters.build());
return new Answer(result.content(), result.finalResponse().id());
}
}
The constructor receives the ChatModel and builds the AI service with the programmatic API of LangChain4j, AiServices.builder. It registers an OrderTools instance as the tool of the service and bounds the tool loop with maxToolCallingRoundTrips. The class is a plain Java class that depends neither on Spring nor on CDI. This independence is what allows the two runtimes to share it: each runtime constructs the model in its own manner and passes it to the constructor.
The constant WEB_SEARCH describes the hosted web search tool. LangChain4j represents hosted tools as raw maps that reproduce the JSON entries of the tools array. This representation is flexible, because it accepts any tool that the provider may add, but the compiler cannot verify the type name or the options of the tool.
The method chat builds the Responses parameters for the current question. They carry the identifier of the previous response, which is null at the start of a conversation, and the hosted web search tool when the client requested it. The method passes them to the AI service together with the question, and returns the text of the answer and the identifier of the response. This parameter is where LangChain4j provides what Spring AI 2.1.0 lacks: a direct way to send previous_response_id.
The tool loop of the AI service
The AI service runs the tool loop on behalf of the application. When the answer of the model contains a request to call orderStatus, the AI service parses the JSON arguments chosen by the model, invokes the annotated method, and sends the result back to the model in a new request, which LangChain4j translates into a function_call_output item. It repeats this cycle until the model answers with text. Each request of the loop carries the merged Responses parameters, so previous_response_id and the hosted tools remain present in every round.
Within the tool loop, each request also carries the complete list of the messages of the current invocation: the question, the tool calls of the model and their results. This behavior keeps the loop correct on any backend, including stateless ones such as Ollama, because each request contains everything the model needs to finish the current question. The previous_response_id field links the question to the earlier questions of the conversation, which only a stateful provider such as OpenAI retains.
The setting maxToolCallingRoundTrips protects the application against a model that would keep requesting tools indefinitely. Beyond five round trips, the AI service raises an exception instead of calling the model again. The Quarkus implementation of AI services honors the same setting. The following diagram shows the exchange for the question about order 42, which requires one round trip.

Compared with Spring AI, this service reaches a comparable concision, because LangChain4j runs the tool loop inside the AI service as Spring AI runs it inside ChatClient. The difference lies in the parameters: the LangChain4j service passes the Responses parameters explicitly on each call, and this explicit passing is what gives it access to the server side state of the Responses API.
LangChain4j on Spring Boot
The module responses-langchain4j-boot depends on the shared module, on the Spring Boot web and validation starters and, through the shared module, on langchain4j-open-ai. It constructs the Responses model itself, which keeps the construction of this experimental class explicit and visible.
The connection parameters form a configuration properties record:
@ConfigurationProperties("responses.openai")
public record ResponsesModelProperties(String baseUrl, String apiKey,
String model, Double temperature)
{
}
The annotation @ConfigurationPropertiesScan on the application class registers this record, and application.properties provides its values:
responses.openai.base-url=https://api.openai.com/v1
responses.openai.api-key=${OPENAI_API_KEY:not-set}
responses.openai.model=gpt-4o-mini
responses.openai.temperature=0.0
A configuration class declares two beans. The responsesChatModel bean is the chat model, built with the builder of OpenAiResponsesChatModel from the properties record. The responsesService bean is the shared service, which receives the chat model:
@Configuration
public class ResponsesConfig
{
@Bean
ChatModel responsesChatModel(ResponsesModelProperties properties)
{
return OpenAiResponsesChatModel.builder()
.baseUrl(properties.baseUrl())
.apiKey(properties.apiKey())
.modelName(properties.model())
.temperature(properties.temperature())
.build();
}
@Bean
ResponsesService responsesService(ChatModel responsesChatModel)
{
return new LangChain4jResponsesService(responsesChatModel);
}
}
The REST controller is the same as in the Spring AI stack. Selecting the Responses API in this stack thus means instantiating the class OpenAiResponsesChatModel instead of OpenAiChatModel. The choice appears in the Java code rather than in a property.
LangChain4j on Quarkus
The module responses-langchain4j-quarkus depends on the shared module and on the Quarkus extensions quarkus-rest-jackson, quarkus-hibernate-validator and quarkus-langchain4j-openai. It also includes quarkus-container-image-docker, which builds a container image of the application.
Selecting the Responses API
The Quarkus LangChain4j extension constructs the chat model itself, from its configuration:
quarkus.langchain4j.chat-model.provider=openai
quarkus.langchain4j.openai.chat-model.mode=responses
quarkus.langchain4j.openai.api-key=${OPENAI_API_KEY:not-set}
quarkus.langchain4j.openai.chat-model.model-name=gpt-4o-mini
quarkus.langchain4j.openai.chat-model.temperature=0.0
quarkus.langchain4j.openai.timeout=120s
quarkus.devservices.enabled=false
The property quarkus.langchain4j.openai.chat-model.mode takes the value chat-completion by default. With the value responses, the extension produces an OpenAiResponsesChatModel as the ChatModel bean of the application. This property is a build time property: Quarkus evaluates it while building the application, so changing it requires a new build. The timeout is raised to 120 seconds, which leaves enough time for a small local model on a modest machine. Dev Services are disabled so that the tests use exactly the same Ollama container as the two Spring Boot stacks, which the conformance suite starts.
Wiring the shared service
A CDI producer turns the chat model of the extension into the ResponsesService bean:
@ApplicationScoped
public class ResponsesServiceProducer
{
@Produces
@ApplicationScoped
ResponsesService responsesService(ChatModel chatModel)
{
return new LangChain4jResponsesService(chatModel);
}
}
This producer plays the role of the @Bean method of the Spring Boot stack. The shared service class remains unchanged, and only the mechanism that constructs and injects it differs.
Making the shared AI service visible to Quarkus
The shared service builds its AI service with AiServices.builder, and in a Quarkus application this call follows the build time model of Quarkus. Three mechanisms of the Quarkus LangChain4j extension explain the consequence.
The extension registers its own implementation of the LangChain4j interface AiServicesFactory, through the standard Java service loader mechanism. In a Quarkus application, a call to AiServices.builder therefore returns a builder provided by the extension.
This builder relies on code generated during the build. Upstream LangChain4j implements an AI service interface at runtime, with a dynamic proxy. Quarkus generates this implementation while it builds the application, which shortens the startup time and supports native compilation. At runtime, the builder retrieves the metadata recorded during the build for the requested interface.
The build discovers programmatic AI services by analyzing the bytecode of the classes of the Jandex index that refer to AiServices, and by reading the interface passed to builder. The Jandex index contains the classes of the application and the classes of the dependencies that Quarkus is asked to index. The module responses-langchain4j-common is an ordinary JAR, so its call site remains outside the analysis until the Quarkus module adds it to the index. Without that addition, the first request fails with the message “Quarkus was not able to determine class … as an AiService at build time”.
Two properties of the Quarkus module add the shared JAR to the index:
quarkus.index-dependency.shared.group-id=fr.simplex-software.workshop
quarkus.index-dependency.shared.artifact-id=responses-langchain4j-common
The error message suggests another remedy, the annotation @CreatedAware on the interface. This annotation belongs to the Quarkus extension, so the shared module, and with it the Spring Boot application, would then depend on Quarkus. Indexing the JAR keeps the shared module independent of both runtimes and confines the requirement to the configuration of the Quarkus module.
The REST resource
The REST resource uses Jakarta REST annotations:
@Path("/chat")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class ChatResource
{
private final ResponsesService responsesService;
public ChatResource(ResponsesService responsesService)
{
this.responsesService = responsesService;
}
@POST
public Answer chat(@Valid Question question)
{
return responsesService.chat(question);
}
}
Quarkus injects the service through the single constructor, so the resource requires no @Inject annotation. The @Valid annotation activates the validation of the question, as in the Spring Boot stacks. The class imports jakarta.validation.Valid explicitly: a wildcard import of jakarta.validation would make the annotation @Path ambiguous, because both jakarta.ws.rs and jakarta.validation contain a type named Path.
The conformance suite
The conformance suite is the element that makes the comparison reliable. It lives in the test sources of responses-common, and the Maven JAR plugin publishes it as a test JAR, which the three application modules declare as a test dependency. The suite verifies the behavior of the REST endpoint through HTTP only, so it is independent of the stack that implements the endpoint.
The base class
The abstract class AbstractResponsesIT sends a question to the endpoint with REST Assured. Each stack provides the address of its running application through the method baseUri:
public abstract class AbstractResponsesIT
{
protected abstract URI baseUri();
protected ValidatableResponse chat(String body)
{
return given().baseUri(baseUri().toString())
.contentType(ContentType.JSON).body(body)
.when().post("/chat")
.then();
}
Two static helper methods named question build the JSON body from a question, an optional previous response identifier and the web search flag.
The local tier
The local tier, in the abstract class AbstractLocalResponsesIT, runs against Ollama, which implements the Open Responses specification at its /v1/responses endpoint. It requires no API key and runs in continuous integration. It contains five tests, three positive and two negative:
@Test
@DisplayName("answers a factual question and returns a response id")
protected void answersAFactualQuestion()
{
chat(question("What is the capital of France? "
+ "Answer with the city name only."))
.statusCode(200)
.body("answer", containsStringIgnoringCase("paris"))
.body("responseId", not(emptyOrNullString()));
}
@Test
@DisplayName("calls a local function tool")
protected void callsALocalFunctionTool()
{
chat(question("What is the status of order 42? Use the orderStatus "
+ "tool and quote the status code exactly."))
.statusCode(200)
.body("answer", containsStringIgnoringCase("QX7731"));
}
The test answersAFactualQuestion verifies the basic exchange and the presence of a response identifier. The test callsALocalFunctionTool verifies that the tool loop works, through the opaque token QX7731. The test keepsNoConversationStateOnAStatelessBackend asks the model to remember a name, sends a follow up question with the identifier of the first response and verifies that the answer does not contain the name. This test documents the behavior of Ollama, which accepts previous_response_id and ignores it. The two negative tests, rejectsABlankQuestion and rejectsAMalformedPayload, verify that the endpoint answers with the HTTP status 400 to a blank question and to a body that is not valid JSON.
The Ollama container
The class OllamaTestSupport starts the Ollama container with Testcontainers and pulls the model:
public final class OllamaTestSupport
{
private static final String IMAGE =
System.getProperty("ollama.image", "ollama/ollama:latest");
private static final String MODEL =
System.getProperty("ollama.model", "qwen2.5:0.5b");
private static final OllamaContainer OLLAMA = startWithModel();
public static String openAiBaseUrl()
{
return OLLAMA.getEndpoint() + "/v1";
}
The container is held in a static field, so it starts once per test JVM and serves all the tests of a module. The image and the model are defined once, as properties of the parent POM, which the Maven Failsafe plugin passes to the tests as system properties. The model qwen2.5:0.5b is small enough to run on a continuous integration machine without a GPU, and it supports function calling. The method openAiBaseUrl returns the address of the OpenAI compatible API of Ollama, which each stack uses in place of the address of OpenAI.
The OpenAI tier
The OpenAI tier, in the abstract class AbstractOpenAiResponsesIT, verifies the two capabilities that require OpenAI: server side state and the hosted web search tool. Its tests run only when the environment variable OPENAI_API_KEY is defined:
@Test
@EnabledIfEnvironmentVariable(named = KEY, matches = ".+")
@DisplayName("recalls an earlier turn through previous_response_id")
protected void recallsAnEarlierTurnThroughPreviousResponseId()
{
Assumptions.assumeTrue(supportsServerState(),
"this stack cannot send previous_response_id");
var first = chat(question("My name is Aurora. Remember it."))
.statusCode(200)
.extract().path("responseId");
chat(question("What is my name? Answer with the name only.",
(String) first, false))
.statusCode(200)
.body("answer", containsStringIgnoringCase("aurora"));
}
The annotation @EnabledIfEnvironmentVariable sits on each test method. JUnit evaluates conditions declared on the test class itself and on its methods, and the test methods are inherited together with their annotations, so placing the condition on the methods makes it effective in every concrete subclass. The abstract method supportsServerState lets each stack declare whether it can send previous_response_id. The Spring AI stack returns false, so JUnit reports this test as skipped for Spring AI, together with the reason. The test searchesTheWebWithTheHostedTool enables web search and verifies that the answer contains the domain name openresponses.org.
Connecting each stack to the suite
Each application module contains two small test classes, one per tier, which extend the abstract classes of the suite. They start the application on a random port and redirect it to the Ollama container. The two Spring Boot stacks use @SpringBootTest and @DynamicPropertySource:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class SpringAiLocalResponsesIT extends AbstractLocalResponsesIT
{
@LocalServerPort
private int port;
@DynamicPropertySource
static void ollama(DynamicPropertyRegistry registry)
{
registry.add("spring.ai.openai.responses.base-url",
OllamaTestSupport::openAiBaseUrl);
registry.add("spring.ai.openai.responses.model",
OllamaTestSupport::model);
registry.add("spring.ai.openai.api-key", () -> "ollama");
}
@Override
protected URI baseUri()
{
return URI.create("http://localhost:" + port);
}
}
The class of the LangChain4j stack on Spring Boot is identical, apart from the property names, which are those of its responses.openai record. The Quarkus stack uses a test resource, the Quarkus mechanism for providing configuration to a test:
public class OllamaResponsesTestResource
implements QuarkusTestResourceLifecycleManager
{
@Override
public Map<String, String> start()
{
return Map.of(
"quarkus.langchain4j.openai.base-url",
OllamaTestSupport.openAiBaseUrl(),
"quarkus.langchain4j.openai.chat-model.model-name",
OllamaTestSupport.model(),
"quarkus.langchain4j.openai.api-key", "ollama");
}
@Override
public void stop()
{
}
}
The test class declares it with @WithTestResource and obtains the address of the application through @TestHTTPResource:
@QuarkusTest
@WithTestResource(OllamaResponsesTestResource.class)
class QuarkusLocalResponsesIT extends AbstractLocalResponsesIT
{
@TestHTTPResource
URI applicationUri;
@Override
protected URI baseUri()
{
return applicationUri;
}
}
Each stack thus adds only the code that connects its runtime to the suite. The tests themselves, with their questions and their assertions, exist once.
Verifying the endpoint that the stacks call
Every stack uses Chat Completions by default, and Ollama implements both APIs. A successful test run is therefore insufficient to prove that a stack calls the Responses API, because a misconfigured stack would pass the local tier through Chat Completions. The request logs settle the question. With OPENAI_LOG=debug for Spring AI and -Dquarkus.langchain4j.openai.log-requests=true for Quarkus, the logs show that the three stacks call /v1/responses. The logs of the Quarkus stack also show that LangChain4j sends the field, for example "previous_response_id" : "resp_320779", during the test on conversation state.
Comparison of the three implementations
The following table summarizes how each stack answers the three questions raised at the beginning of the article, together with the other differences that the code reveals.
| Aspect | Spring AI on Spring Boot | LangChain4j on Spring Boot | LangChain4j on Quarkus |
|---|---|---|---|
| Selection of the Responses API | property spring.ai.openai.chat.api=responses |
Java code that builds OpenAiResponsesChatModel in a @Bean method |
build time property quarkus.langchain4j.openai.chat-model.mode=responses |
| Default API | Chat Completions | Chat Completions, through OpenAiChatModel |
Chat Completions |
| Programming model | ChatClient fluent API |
AI service with a ChatRequestParameters argument |
the shared AI service |
| Tool loop | executed by the ToolCallingAdvisor of ChatClient |
executed by the AI service | executed by the AI service |
| Server side state | store set to false, conversation kept in the application |
previousResponseId request parameter |
previousResponseId request parameter |
| Hosted tools | typed, through HostedTool.WebSearch and its siblings |
raw maps, through serverTools |
raw maps, through serverTools |
| Status of the Responses model | regular class of Spring AI 2.1.0 | annotated @Experimental |
annotated @Experimental |
| Construction and injection | autoconfiguration | @ConfigurationProperties record and @Bean methods |
extension configuration, a CDI producer and the indexed shared JAR |
The differences fall into three groups.
The decisive difference concerns server side state. With LangChain4j, on both runtimes, an application can send previous_response_id and let OpenAI keep the conversation. With Spring AI 2.1.0, the application keeps the conversation itself, as it did with Chat Completions. A team that adopts the Responses API to reduce the size of its requests, by letting the provider keep the conversation, will therefore find this capability in LangChain4j today. Spring AI preserves the continuity of the reasoning on the client side, through the encrypted reasoning that it sends back, so this particular benefit requires no server side state.
The two libraries reach a comparable level of abstraction. Both run the tool loop on behalf of the application: Spring AI in the ToolCallingAdvisor of ChatClient, LangChain4j in its AI services. Spring AI offers typed hosted tools, which the compiler verifies. LangChain4j expresses hosted tools as raw maps and expects the application to pass the Responses parameters explicitly on each call, through a ChatRequestParameters argument of the AI service method, which is also what gives it access to previous_response_id.
The choice of runtime, finally, has no influence on the use of the library. The two LangChain4j stacks share the same service class, byte for byte. Spring Boot and Quarkus differ only in the way they construct the model, from a properties record in the case of Spring Boot and from the extension configuration in the case of Quarkus, and in the way they inject it, through a @Bean method or a CDI producer. Quarkus adds one requirement, which follows from its build time model: the JAR that contains the shared AI service must be part of its index.
The behavior of Ollama deserves a final remark. It implements the format of the Open Responses specification and function calling, which makes it an excellent backend for development and for continuous integration. It ignores previous_response_id without reporting an error, so an application that relies on server side state must verify this capability against its production provider.
Running the project
The local tier requires Docker. The following command builds the project and runs the local tier on the three stacks:
./mvnw verify
When an OpenAI API key is available, the OpenAI tier runs in addition, at a small cost per run:
OPENAI_API_KEY=sk-... ./mvnw verify
To start one stack against OpenAI and call it:
OPENAI_API_KEY=sk-... ./mvnw -pl responses-spring-ai-boot \
spring-boot:run
curl localhost:8080/chat -H 'Content-Type: application/json' \
-d '{"question":"What is the status of order 42?"}'
The project also contains a CircleCI pipeline, which pulls the Ollama model in advance and runs ./mvnw verify on a machine executor, because Testcontainers requires a Docker daemon.
Conclusion
The Responses API is more than a new endpoint for the same exchange. It moves the conversation state to the provider, it lets the provider execute tools such as web search, and it describes every step of a response as a typed item. Its publication as the Open Responses specification allows the same client code to work with OpenAI, with local servers such as Ollama and with other providers.
The three Java stacks studied here all reach the Responses API, and each of them requires an explicit choice, because Chat Completions remains their default. Spring AI offers the most strongly typed code. In version 2.1.0, it sends "store": false on every request and offers no option to send previous_response_id, by design, so the conversation remains in the application, and Spring AI preserves the continuity of the reasoning by sending it back in encrypted form. LangChain4j exposes the full set of Responses parameters, including previous_response_id, through an argument of its AI service methods. Both libraries run the tool loop on behalf of the application. The runtime, Spring Boot or Quarkus, changes only the wiring around an identical library usage, and Quarkus additionally requires the shared JAR to be part of its build time index. The shared conformance suite turns these observations into verifiable facts: each one corresponds to a test that passes, a test that is skipped with a stated reason, or a line in a request log.
Further reading
The complete source code of the project, including the three implementations, the conformance suite and the CircleCI pipeline, is available on GitHub at java-ai-responses-rosetta.
This project applies the method of the book Java AI Frameworks, which compares Spring AI, LangChain4j on Spring Boot and LangChain4j on Quarkus over a series of use cases, each implemented on the three stacks and verified by a shared conformance suite. The book is available as an ebook on Leanpub and as a paperback on Amazon.