3 Working with LLMs
This chapter builds the LLM side of the agent framework by introducing a common abstraction for model interactions and the supporting data structures needed to use different providers in a consistent way. It starts by explaining why a shared interface is useful when working with many APIs and SDKs, then defines lightweight models for text completion and chat messages, including message roles and tool-call handling. The design is asynchronous by default, and it establishes a clean separation between framework-level objects and provider-specific implementations.
From there, the chapter shows how tool calling fits into chat-based LLM workflows and why structured responses are valuable for reliable downstream processing. It presents a method for continuing a conversation after tools have run, so the model can synthesize tool results into a final answer without requiring the user to manually convert data between formats. It also introduces structured output generation as a way to have the model return validated data models, emphasizing how this can reduce brittleness compared with free-form text and how it relates conceptually to tool use.
The second half of the chapter implements a concrete backend using Ollama, enabling the framework to work with many open-source models through a local or cloud Ollama service. The implementation covers model initialization, plain text completion, structured output via JSON Schema, conversational chat, and the follow-up step that feeds tool results back into the model. A complete end-to-end example demonstrates tool calling with a Hailstone tool, showing the full loop from model request to tool execution to final synthesized response, and the chapter closes by connecting these capabilities to future multi-agent systems where different agents can use different backbone LLMs depending on their role and cost.
Having added tools to our LLM agent framework, the focus of this chapter is to add the other main component of LLM agents—their backbone LLM—to our framework. We’ll specify the interface that all future LLMs must conform to through the BaseLLM class and implement the OllamaLLM subclass to enable the use of any of the open-source LLMs supported by Ollama.
Our LLM agent with its backbone LLM and equipped tools. The backbone LLM is the Qwen3-7b model from the OllamaLLM class that we’ll implement later in this chapter.
Supporting text completion with complete().
Supporting chat interactions with LLMs via chat().
The UML class diagrams for BaseLLM and new data structures.
An example of a CompleteResult object that is returned from an invocation of complete().
Example ChatMessage and ChatRole objects within a chat() invocation.
The familiar tool-calling process, now shown within a chat() invocation.
The structured output LLM interaction. An instruction prompt and the desired output format, mdl, are passed as the inputs to structured_output(). The LLM generates a response that can then be used to create an instance of mdl, a subclass of pydantic.BaseModel.
Integrating with the Ollama LLM inference framework. The OllamaLLM connects to a running Ollama server, often running locally on your machine, to work with any of the supported open-source LLMs.
UML class diagram for OllamaLLM.
Integrating with Ollama’s text completion interface. A complete() invocation of OllamaLLM invokes the generate() method of the Ollama library and returns an Ollama data type from which we derive the final return type, CompleteResult.
Three utility functions for converting between llm-agents-from-scratch data types and corresponding Ollama equivalent data types.
Integrating with Ollama’s structured output interface, which is facilitated by their chat interface. A structured_output() invocation of OllamaLLM invokes the ollama.chat() but not before creating the Ollama message data object. The returned result is an ollama.ChatResponse from which we extract the JSON payload corresponding to mdl that we then use to validate and create the final structured output object.
Integrating with Ollama’s chat interface to implement chat(). The user’s input and chat history are converted to Ollama messages, and tools are converted to Ollama tools. Next, ollama.chat() is invoked and its response is then converted back to a ChatMessage. This ChatMessage is returned along with another one derived from the user’s input.
Integrating with Ollama’s chat interface to implement continue_chat_with_tool_results(). The tool-call results and chat history are converted to Ollama messages, and tools are converted to Ollama tools. Next, ollama.chat() is invoked and its response is then converted back to a ChatMessage. This ChatMessage is returned along with the list of ChatMessage objects derived from the tool-call results.
Summary
- APIs provided by LLM providers typically support two modes of interaction with LLMs: one for text completion and another for conversational dialogue.
- Our BaseLLM class supports text completion via the complete() method, and the conversational mode of interaction through our chat() method.
- One important use case for LLMs is structured output, where we instruct an LLM to produce an output that conforms to a specified data format, often described in JSON.
- Structured outputs with our BaseLLM class, can be performed via the structured_output() method.
- Integrations into LLM providers and their companion Python SDKs can be added to our framework by subclassing BaseLLM.
- The OllamaLLM integration implemented in this chapter allows for the use of any open-source LLMs supported by Ollama in our framework.
Build a Multi-Agent System (from Scratch) ebook for free