Chapter 3: The model call
This chapter sends one question to Gemma and returns its text reply.
Objectives:
- Create one shared
ChatClient. - Write the
Assistantservice. - Expose it over HTTP with
TestController. - See what the model answers without tools.
Step 1: The chat client
Build one chat client and share it.
The OpenAI starter provides a ChatClient.Builder, already pointed at LM Studio. Create AiConfig.java:
package com.garageeducation.harness;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Creates the beans that talk to the model.
*/
@Configuration
public class AiConfig {
/**
* Builds one {@link ChatClient} for the whole app.
*
* <p>The OpenAI starter provides the builder, already pointed at LM Studio.
* Every class that needs the model receives this client.
*
* @param builder the {@link ChatClient.Builder} from the OpenAI starter
* @return the shared chat client
*/
@Bean
ChatClient chatClient(ChatClient.Builder builder) {
return builder.build();
}
}
@Configurationmarks a class that creates objects for Spring.@Beanregisters the returnedChatClient. Spring calls this method once at startup.- Any class that asks for a
ChatClientnow receives this one.
ChatOpenAI speaks the OpenAI API, so it can point at LM Studio. Create ai_config.py:
"""Creates the objects that talk to the model."""
from langchain_core.language_models import BaseChatModel
from langchain_openai import ChatOpenAI
from pydantic import SecretStr
from harness.application_properties import ApplicationProperties
from harness.observation_logging import ChatModelObservationHandler
class AiConfig:
"""Creates the objects that talk to the model.
It plays the part of the Spring ``@Configuration`` class.
"""
def __init__(self, properties: ApplicationProperties) -> None:
self.properties = properties
def chat_model(self) -> BaseChatModel:
"""Builds one chat model for the whole app.
``ChatOpenAI`` speaks the OpenAI API, so ``base_url`` points it at LM Studio.
Every class that needs the model receives this object.
Returns:
the shared chat model
"""
return ChatOpenAI(
base_url=self.properties.base_url,
api_key=SecretStr(self.properties.api_key),
model=self.properties.chat_model,
callbacks=[ChatModelObservationHandler(self.properties.log_prompt, self.properties.log_completion)],
)
AiConfigplays the part of a Spring@Configurationclass.chat_model()plays the part of the@Beanmethod.base_url,api_key, andmodelcome fromapplication.yaml, through theApplicationPropertiesfrom Chapter 2.callbacksattaches the Chapter 2 logging handler. It prints each prompt and reply.create_app()callschat_model()once and passes the same object to every class that needs it. Step 3 shows it.
Step 2: The Assistant
package com.garageeducation.harness;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
/**
* Sends one question to the chat model and returns its text reply.
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class Assistant {
private static final String SYSTEM = "You are a careful assistant. Answer in two sentences or fewer.";
private final ChatClient chat;
/**
* Asks the model one question.
*
* <p>The system message limits the reply to two sentences.
*
* @param question the user's question, in plain text
* @return the model's final text reply
*/
public String askAutoToolCall(String question) {
log.debug("[auto] Spring AI runs every tool call. Question: {}", question);
String answer = chat.prompt()
.system(SYSTEM)
.user(question)
.call()
.content();
log.debug("[auto] Final answer: {}", answer);
return answer;
}
}
@Servicetells Spring to create oneAssistantat startup.@Slf4jcomes from Lombok. It adds alogfield. Eachlog.debugline shows in the console.@RequiredArgsConstructorcomes from Lombok. It writes a constructor with one argument perfinalfield. Spring calls it and passes theChatClientfrom Step 1..system(…)sets the rules..user(…)sets the question..call()picks a blocking call. It sends nothing yet..content()sends the request and returns the reply as aString.- Your code never builds the HTTP request. Figure 3.1 shows the call. Step 4 shows what happens inside it.
- The name
askAutoToolCalllooks ahead. Chapter 4 adds tools, andChatClientruns them for you.
Create assistant.py:
"""Sends one question to the chat model and returns its text reply."""
import logging
from typing import Final
from langchain_core.language_models import BaseChatModel
from langchain_core.messages import HumanMessage, SystemMessage
log: Final = logging.getLogger(__name__)
class Assistant:
"""Sends one question to the chat model and returns its text reply."""
SYSTEM: Final = "You are a careful assistant. Answer in two sentences or fewer."
def __init__(self, chat: BaseChatModel) -> None:
self.chat = chat
def ask_auto_tool_call(self, question: str) -> str:
"""Asks the model one question.
The system message limits the reply to two sentences.
Args:
question: the user's question, in plain text
Returns:
the model's final text reply
"""
log.debug("[auto] LangChain runs every tool call. Question: %s", question)
answer = self.chat.invoke([SystemMessage(self.SYSTEM), HumanMessage(question)]).text
log.debug("[auto] Final answer: %s", answer)
return answer
- The constructor receives the chat model.
create_app()passes it in, like Spring’s constructor injection. logis one logger per module. Eachlog.debugline shows in the console.SYSTEMis a class constant.Finaltells the type checker it never changes, likestatic final.SystemMessagesets the rules.HumanMessagecarries the question..invoke(…)sends the request and returns the reply as anAIMessage..textreturns its text.- Your code never builds the HTTP request. Figure 3.1 shows the call. Step 4 shows what happens inside it.
- The name
ask_auto_tool_calllooks ahead. Chapter 4 adds tools, and a LangChain agent runs them for you.
Step 3: The controller
package com.garageeducation.harness;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import lombok.RequiredArgsConstructor;
/**
* Exposes {@link Assistant} over HTTP for manual tests.
*
* <p>Example: {@code GET http://localhost:8080/askAutoToolCall?input=how many error events?}
*/
@RestController
@RequiredArgsConstructor
public class TestController {
private final Assistant assistant;
/**
* Sends the {@code input} query parameter to the model.
*
* @param input the question; the request fails without it
* @return the model's text reply
*/
@GetMapping("/askAutoToolCall")
public String askAutoToolCall(@RequestParam String input) {
return assistant.askAutoToolCall(input);
}
}
@RestControllerturns each method’s return value into the HTTP response.@GetMapping("/askAutoToolCall")mapsGET /askAutoToolCallto the method.@RequestParamreadsinputfrom the query string.
Create test_controller.py:
"""Exposes Assistant over HTTP for manual tests."""
from fastapi import APIRouter
from fastapi.responses import PlainTextResponse
from harness.assistant import Assistant
class TestController:
"""Exposes ``Assistant`` over HTTP for manual tests.
It plays the part of the Spring ``@RestController``. Each ``add_api_route`` line plays
the part of one ``@GetMapping``.
Example: ``GET http://localhost:8080/askAutoToolCall?input=how many error events?``
"""
def __init__(self, assistant: Assistant) -> None:
self.assistant = assistant
self.router = APIRouter()
self.router.add_api_route("/askAutoToolCall", self.ask_auto_tool_call, response_class=PlainTextResponse)
def ask_auto_tool_call(self, input: str) -> str:
"""Sends the ``input`` query parameter to the model.
Args:
input: the question; the request fails without it
Returns:
the model's text reply
"""
return self.assistant.ask_auto_tool_call(input)
add_api_routemapsGET /askAutoToolCallto the method, like@GetMapping.- FastAPI reads
inputfrom the query string because it is a plain parameter, like@RequestParam. PlainTextResponsereturns the text as is, like a SpringStringreturn value.
Wire the objects in harness_application.py. Replace create_app() from Chapter 2:
def create_app() -> FastAPI:
"""Creates every object and wires them together.
It plays the part of Spring's application context: one place builds each object once
and passes it to the constructors that need it.
Returns:
the web app, with the ``TestController`` routes
"""
properties = ApplicationProperties.load()
chat = AiConfig(properties).chat_model()
controller = TestController(Assistant(chat))
app = FastAPI(title="harness")
app.include_router(controller.router)
return app
- Spring finds and builds each bean for you. In Python,
create_app()builds each object in order and passes it on. - Add the imports for
AiConfig,Assistant, andTestControllerat the top of the file.
.call() only prepares the request. .content() sends it. No tools are attached, so the model answers from its own text.Step 4: Inside one call
.system(…) and .user(…) each add one message. Spring AI gives every message a role. Figure 3.2 shows the four roles.
- System sets the rules for the whole conversation.
- User is the question. One prompt can hold many user messages.
- Assistant is the model’s reply. Chapter 5 reads tool calls from it.
- Tool carries a tool result back to the model. Chapter 5 builds one by hand.
ChatClient puts the messages in a Prompt and hands it to the ChatModel from Chapter 2. Figure 3.3 shows what the ChatModel does with it.
ChatModel. Your code sees only the Prompt and the ChatResponse. Redrawn from the Spring AI reference, Chat Model API, for LM Studio.The numbers in Figure 3.3 match these steps:
- Options. The starter reads the model name from
application.yamlat startup. A request can override it with.options(…). This course keeps the startup options. - Convert the request.
OpenAiChatModelturns thePromptinto an OpenAI JSON request. LM Studio runs Gemma on it. - Convert the reply.
OpenAiChatModelturns the JSON reply into aChatResponse. It holds the reply message and metadata, such as token counts.
There are three ways to read the reply. Table 3.1 lists them.
| Method | Returns | Used in |
|---|---|---|
.content() | The reply text, as a String | Chapters 3 and 4 |
.chatResponse() | The full ChatResponse: reply message, tool calls, and token counts | Chapters 5 and 6 |
.entity(Type.class) | The reply parsed into a Java object | Not used yet |
| Call | Returns | Used in |
|---|---|---|
.invoke(messages).text | The reply text, as a str | Chapters 3 and 4 |
.invoke(messages) | The full AIMessage: text, tool_calls, and usage_metadata (token counts) | Chapters 5 and 6 |
.with_structured_output(Type).invoke(messages) | The reply parsed into a Python object | Not used yet |
In Python, .invoke(…) sends the request. There is no separate .call() step.
Table 3.1. Three ways to read one reply. Each one sends the request.
Between ChatClient and the ChatModel sits a chain of advisors. Chapter 4 explains it.
Step 5: Run the first call
Restart the app. Send a question:
curl -G http://localhost:8080/askAutoToolCall --data-urlencode "input=how many error events?"
The model has no data. It asks for the logs:
Please provide the logs or data you are referring to. Once you share them, I can count the error events for you.
The console log shows the same run:
00:15:18.392 DEBUG DispatcherServlet GET "/askAutoToolCall?input=how+many+error+events%3F", parameters={masked}
00:15:18.393 DEBUG Assistant [auto] Spring AI runs every tool call. Question: how many error events?
00:15:20.872 INFO ChatModelCompletionObservationHandler Chat Model Completion:
["Please provide the data or context you are referring to. I do not see any events listed in your message."]
00:15:20.872 INFO ChatModelPromptContentObservationHandler Chat Model Prompt Content:
["You are a careful assistant. Answer in two sentences or fewer.", "how many error events?"]
00:15:20.874 DEBUG Assistant [auto] Final answer: Please provide the data or context you are referring to. I do not see any events listed in your message.
00:15:20.882 DEBUG DispatcherServlet Completed 200 OK
- The prompt holds two messages: the system rules and your question. Figure 3.2 shows both.
- No
Executing tool callline appears. The model has no tools yet.
16:07:14.640 DEBUG harness.assistant [auto] LangChain runs every tool call. Question: how many error events?
16:07:14.644 INFO ChatModelPromptContent Chat Model Prompt Content:
['You are a careful assistant. Answer in two sentences or fewer.', 'how many error events?']
16:07:19.309 INFO httpx2 HTTP Request: POST http://localhost:1234/v1/chat/completions "HTTP/1.1 200 OK"
16:07:19.315 INFO ChatModelCompletion Chat Model Completion:
['Please provide the log or data you are referring to so I can count the events for you. I do not have any context yet to identify specific errors.']
16:07:19.315 DEBUG harness.assistant [auto] Final answer: Please provide the log or data you are referring to so I can count the events for you. I do not have any context yet to identify specific errors.
16:07:19.316 INFO uvicorn.access 127.0.0.1:55581 - "GET /askAutoToolCall?input=how%20many%20error%20events%3F HTTP/1.1" 200
- The prompt holds two messages: the system rules and your question. Figure 3.2 shows both.
httpx2writes one line per model call. It is the HTTP client inside the OpenAI SDK.uvicorn.accesswrites one line when the request ends, with its status code.- No
Executing tool callline appears. The model has no tools yet.
A request without input fails: Spring returns 400 and FastAPI returns 422. The model is never called.
Or run the Chapter 3 request in requests/harness.http.
Summary: One question reaches Gemma and returns text. The model cannot read logs yet. Chapter 4 gives it a tool.