Chapter 3: The model call

This chapter sends one question to Gemma and returns its text reply.

Objectives:

  • Create one shared ChatClient.
  • Write the Assistant service.
  • 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();
    }
}
  • @Configuration marks a class that creates objects for Spring.
  • @Bean registers the returned ChatClient. Spring calls this method once at startup.
  • Any class that asks for a ChatClient now 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)],
        )
  • AiConfig plays the part of a Spring @Configuration class. chat_model() plays the part of the @Bean method.
  • base_url, api_key, and model come from application.yaml, through the ApplicationProperties from Chapter 2.
  • callbacks attaches the Chapter 2 logging handler. It prints each prompt and reply.
  • create_app() calls chat_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;
    }
}
  • @Service tells Spring to create one Assistant at startup.
  • @Slf4j comes from Lombok. It adds a log field. Each log.debug line shows in the console.
  • @RequiredArgsConstructor comes from Lombok. It writes a constructor with one argument per final field. Spring calls it and passes the ChatClient from 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 a String.
  • Your code never builds the HTTP request. Figure 3.1 shows the call. Step 4 shows what happens inside it.
  • The name askAutoToolCall looks ahead. Chapter 4 adds tools, and ChatClient runs 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.
  • log is one logger per module. Each log.debug line shows in the console.
  • SYSTEM is a class constant. Final tells the type checker it never changes, like static final.
  • SystemMessage sets the rules. HumanMessage carries the question.
  • .invoke(…) sends the request and returns the reply as an AIMessage. .text returns 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_call looks 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);
    }
}
  • @RestController turns each method’s return value into the HTTP response.
  • @GetMapping("/askAutoToolCall") maps GET /askAutoToolCall to the method.
  • @RequestParam reads input from 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_route maps GET /askAutoToolCall to the method, like @GetMapping.
  • FastAPI reads input from the query string because it is a plain parameter, like @RequestParam.
  • PlainTextResponse returns the text as is, like a Spring String return 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, and TestController at the top of the file.
Figure 3.1. One model call. .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.

the prompt: sent to the modelthe replySYSTEMSystemMessageSets the rules forevery reply.In this chapter:Answer in twosentences or fewer.USERUserMessageThe question orcommand.In this chapter:how many errorevents?ASSISTANTAssistantMessageThe model's reply.Can hold tool calls.In this chapter:Please providethe logs…TOOLToolResponseMessageA tool's result, sentback to the model.In this chapter:none. Chapter 4adds a tool.
Figure 3.2. The four message roles. This chapter sends two messages and gets one back. Redrawn and cut down from the Spring AI reference, Prompts.
  • 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.

built by ChatClientPromptSystemMessageUserMessageoptions: modelOpenAiChatModelConvert to anOpenAI requestConvert to aChatResponseLM Studio/v1/chat/completionsJSON requestGemmaJSON replyChatResponseGeneration:AssistantMessageMetadata:model, tokens.content() returns thetext of the reply.123
Figure 3.3. One model call inside the 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:

  1. Options. The starter reads the model name from application.yaml at startup. A request can override it with .options(…). This course keeps the startup options.
  2. Convert the request. OpenAiChatModel turns the Prompt into an OpenAI JSON request. LM Studio runs Gemma on it.
  3. Convert the reply. OpenAiChatModel turns the JSON reply into a ChatResponse. It holds the reply message and metadata, such as token counts.

There are three ways to read the reply. Table 3.1 lists them.

MethodReturnsUsed in
.content()The reply text, as a StringChapters 3 and 4
.chatResponse()The full ChatResponse: reply message, tool calls, and token countsChapters 5 and 6
.entity(Type.class)The reply parsed into a Java objectNot used yet
CallReturnsUsed in
.invoke(messages).textThe reply text, as a strChapters 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 objectNot 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 call line 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.
  • httpx2 writes one line per model call. It is the HTTP client inside the OpenAI SDK.
  • uvicorn.access writes one line when the request ends, with its status code.
  • No Executing tool call line 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.

docs