Quick revision
The short answer
With a model starter on the classpath, Spring AI auto-configures a ChatClient.Builder; we inject it, build a ChatClient once, optionally with defaultSystem(...), and call chatClient.prompt().system(...).user(question).call().content() to get the answer as a String. The provider and model are chosen by the starter and the spring.ai.<provider>.* properties, and the API key comes from an environment variable or a secret store rather than application.yml in git. We also set timeouts and handle provider errors and rate limits, and for a browser we can stream with .stream().content().
What to remember
In this answer, we added a Spring AI model starter, injected the auto-configured ChatClient.Builder, built a ChatClient with a default system message, and wrote prompt().system(...).user(question).call().content() to get the answer text. We configured the provider and model with spring.ai.<provider>.* properties and kept the API key in an environment variable fed from a secret store. We set timeouts, relied on Spring AI's retries for 429 and 5xx errors, handled failures with clear messages, and streamed the answer with stream().content().
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
With a model starter on the classpath, Spring AI auto-configures a ChatClient.Builder; we inject it, build a ChatClient once, optionally with defaultSystem(...), and call chatClient.prompt().system(...).user(question).call().content() to get the answer as a String. The provider and model are chosen by the starter and the spring.ai.<provider>.* properties, and the API key comes from an environment variable or a secret store rather than application.yml in git. We also set timeouts and handle provider errors and rate limits, and for a browser we can stream with .stream().content().
Why this question is asked
Calling a chat model is now an ordinary task in many Java services, and Spring AI makes the first call look almost too simple. Interviewers ask for the code because it shows whether we know the main types and where configuration lives, and the follow-up questions about keys, timeouts and errors show whether we have run it in production. In this answer, we will add the dependency, write the service method, look at how the system and user messages differ, see where the model and key are configured, handle failures, and then stream the answer to a browser.
1A Quick Recap of the Pieces
Spring AI is the Spring project for calling AI models. It has a low-level ChatModel interface implemented once per provider, such as OpenAI, Anthropic or Ollama, and a fluent ChatClient on top of it that we normally use in application code. A starter is a dependency that brings the provider's ChatModel and the auto-configuration that creates it from properties.
A chat request is a list of messages. The system message sets the rules and role for the whole conversation, such as You are a support assistant for Acme; answer briefly. The user message carries the actual question. Models give the system message more weight, so instructions belong there and user text belongs in the user message.
2Adding the Starter
In Spring AI 1.0, starters follow the name spring-ai-starter-model-<provider>, and the Spring AI BOM keeps the versions in line.
Notice that the starter name decides the provider. Swapping to another provider is mostly a matter of changing this dependency and the properties, as long as our code uses ChatClient rather than provider-specific classes.
3Writing the Service Method
The auto-configuration registers a ChatClient.Builder bean, already wired to the provider's ChatModel. We inject the builder, set defaults that every request from this service shares, and build the client once in the constructor. A ChatClient is thread-safe and meant to be reused.
The chain reads like the request it builds: prompt() starts a request, system() and user() add messages, call() sends it and waits, and content() takes the text of the first answer. If we need token counts or the model name, chatResponse() instead of content() returns the full ChatResponse with metadata.
4Where the Model and the API Key Are Configured
The model and its options are set with properties under spring.ai.<provider>. For OpenAI, for example, the key is spring.ai.openai.api-key and the model is spring.ai.openai.chat.options.model; Anthropic and Ollama have their own prefixes. Property names have changed between Spring AI milestones and releases, so check the exact names in the reference documentation for your provider and version.
The placeholder ${OPENAI_API_KEY} means the real key never sits in the repository. A key committed to git is visible to everyone with access to the history, forever, and automated scanners find leaked keys within minutes on public repositories. In production the environment variable is filled from a secret store, and each environment gets its own key so that a leak can be revoked without breaking the others.
5Timeouts, Errors and Rate Limits
Model calls are slow compared with ordinary HTTP calls: a long answer can take 20 seconds or more. So we set explicit connect and read timeouts on the HTTP client that the starter uses, for example by defining a RestClientCustomizer bean with a request factory that has a 5 second connect timeout and a 60 second read timeout. The exact hook depends on the provider and version.
Providers also return errors we must expect. A 429 status means we hit a rate limit; 500 and 503 mean the provider had a problem. Spring AI wraps the call in a retry template configured by spring.ai.retry.* properties, which retries such errors with backoff. When retries run out, the call throws an exception, and our service should catch it and return a clear message, such as The assistant is busy, please try again, rather than a stack trace.
6Streaming the Answer to a Browser
For a chat screen, waiting 15 seconds for the full answer feels broken. Streaming sends tokens as they are generated, so the first words appear in under a second. In Spring AI we replace call() with stream(), which returns a Flux<String> of text pieces, and we can return it as server-sent events from a controller.
6 messages in order. Play them, or step through them one at a time.
Each element becomes one SSE event, and the browser appends the pieces as they arrive. This works in Spring MVC as well as WebFlux, because Spring MVC can write a Flux as a stream. Error handling moves into the stream: we add onErrorResume to send a final error event rather than cutting the connection silently.
7Follow-up questions
Should I create a ChatClient per request?
No. Build it once from the injected builder and reuse it; it is thread-safe. If different parts of the service need different defaults, build several clients, for example one with a support system prompt and one with a summarising prompt, each as a bean or a field.
How do I use two providers in one application?
Add both starters, and then the single auto-configured ChatClient.Builder becomes ambiguous. In that case we create builders explicitly with ChatClient.builder(openAiChatModel) and ChatClient.builder(anthropicChatModel), injecting the provider-specific ChatModel beans by type; the documentation describes switching off the default builder with a property, so check it for your version.
8Conclusion
In this answer, we added a Spring AI model starter, injected the auto-configured ChatClient.Builder, built a ChatClient with a default system message, and wrote prompt().system(...).user(question).call().content() to get the answer text. We configured the provider and model with spring.ai.<provider>.* properties and kept the API key in an environment variable fed from a secret store. We set timeouts, relied on Spring AI's retries for 429 and 5xx errors, handled failures with clear messages, and streamed the answer with stream().content().
Open with
With Spring AI 1.x, I add the starter for the provider, for example spring-ai-starter-model-openai, through the Spring AI BOM. The starter auto-configures the provider's ChatModel and a ChatClient.Builder.
Then, if they want more
In my service I inject the builder, set a default system message with defaultSystem, build the ChatClient once and keep it as a field, since it is thread-safe. The method is then chatClient.prompt().system with the instruction, or just the default, then .user(question), .call() and .content(), which returns the answer as a String.
If I need token usage or the model name, I call chatResponse() instead. The model and options come from properties under spring.ai and the provider name, such as spring.ai.openai.chat.options.model, and I always check the exact property names for the version I am on.
The API key is a placeholder in application.yml that resolves from an environment variable, which the platform fills from a secret store, so nothing secret is in git. I set connect and read timeouts suitable for long generations, rely on Spring AI's retry settings for 429 and 5xx responses, and catch the remaining exceptions to return a clear message.
To stream to a browser, I replace call() with stream().content(), which gives a Flux of text chunks that I return as text/event-stream.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring AI reference
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Using Spring AI 1.x, write the code for a Spring Boot service method that sends a system...": https://scrivio-interview-library.netlify.app/spring-boot/spring-ai/16037b8aa0/