Overview

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.
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.
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 text completion with complete().
Supporting chat interactions with LLMs via chat().
Supporting chat interactions with LLMs via chat().
The UML class diagrams for BaseLLM and new data structures.
The UML class diagrams for BaseLLM and new data structures.
An example of a CompleteResult object that is returned from an invocation of complete().
An example of a CompleteResult object that is returned from an invocation of complete().
Example ChatMessage and ChatRole objects within a chat() invocation.
Example ChatMessage and ChatRole objects within a chat() invocation.
The familiar tool-calling process, now shown 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.
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.
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.
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.
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.
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 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 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.
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.

FAQ

What is the purpose of the BaseLLM class in the framework?The BaseLLM class defines a common interface for working with different LLM providers and frameworks. It standardizes how LLMs are used in the framework so users do not have to deal with provider-specific API differences.
Which LLM interaction modes are supported by BaseLLM?BaseLLM supports the standard interaction modes complete() for text completion and chat() for conversational interactions. It also includes support for continuing chat with tool results and for structured outputs.
Why does the chapter introduce CompleteResult and ChatMessage?These data structures help normalize LLM interactions. CompleteResult stores the prompt and generated response for text completion, while ChatMessage represents chat messages with a role, content, and optional tool calls.
What is ChatRole and why is it implemented as an enum?ChatRole is an enum that defines the valid senders of chat messages: SYSTEM, USER, ASSISTANT, and TOOL. Using an enum ensures message roles stay within a finite, predefined set of values.
How does tool calling work in a chat interaction?A tool-call request is represented by a ChatMessage with the ASSISTANT role and one or more ToolCall objects in its tool_calls attribute. The tool is executed, and its ToolCallResult is sent back to the LLM for synthesis.
What does continue_chat_with_tool_results() do?This method extends a chat by converting ToolCallResult objects into ChatMessage objects with the TOOL role, then sending them back to the LLM along with the chat history. It makes the final step of the tool-calling process easier and more explicit.
Why is structured_output() useful?structured_output() asks the LLM to return data in a pre-specified format, usually JSON. This makes downstream parsing and validation much more reliable than working with free-form text.
How is structured_output() typed in this framework?The method uses a generic type bound to pydantic.BaseModel, meaning the caller supplies a custom Pydantic model that defines the desired output structure. The method then returns an instance of that model.
What is OllamaLLM and what does it add to BaseLLM?OllamaLLM is a subclass of BaseLLM that connects to a running Ollama service. It adds a model setting and an internal _client for calling Ollama’s async APIs, enabling use of open-source models supported by Ollama.
How does the chapter demonstrate a complete tool-calling workflow with OllamaLLM?It first uses chat() to get a tool-call request from the LLM, then executes the tool to get a ToolCallResult, and finally uses continue_chat_with_tool_results() to send that result back to the LLM. This completes the full request–tool execution–LLM synthesis loop.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Build a Multi-Agent System (from Scratch) Build a Multi-Agent System (from Scratch) ebook for free
Close
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Build a Multi-Agent System (from Scratch) Build a Multi-Agent System (from Scratch) ebook for free