Skip to content
ImagineWorld

Advanced components for LLM applications

node_idnode-book_build-small-language-model_chapter-14-advanced-components-for-llm-applications
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num14
chapter_titleAdvanced components for LLM applications
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 14 — Advanced components for LLM applications

Section titled “Chapter 14 — Advanced components for LLM applications”

This chapter covers

  • RAG on a knowledge graph
  • Combining RAG and agentic AI using only SLMs
  • Managing short- and long-term memory for chatbots and AI agents

In chapter 13, you learned about two key paradigms for language models: retrieval-augmented generation (RAG) and agentic AI. We built a RAG system from scratch, introduced vector databases for these applications, and implemented an AI agent using the open source smolagents framework. In this chapter, we’ll cover some new concepts and tools that can make RAG systems and agents more robust, and you’ll learn how to combine them.

In the previous chapter, you learned that RAG connects language models to external data sources, giving them access to private or domain-specific information and reducing hallucinations. A baseline RAG typically combines a vector database with two language models; the vector database stores embeddings, one model retrieves context for a user query, and the other model generates an answer from that context. This approach works well in many cases, but it can struggle with complex tasks that require multihop reasoning or connecting information from multiple sources. The core challenge is that baseline RAG retrieves text by semantic similarity, which does not reliably surface specific details needed to answer complex questions, especially when those details are not stated explicitly in the knowledge base. As a result, finding the right information can be difficult, sometimes leading to costly workarounds, such as manually creating Q&A pairs for common queries.

One way to address these challenges is to augment RAG retrieval and generation with knowledge graphs (KGs). A KG is a structured representation of knowledge that captures entities, their attributes, and the relationships between them. KGs consist of nodes (entities such as people, places, or concepts) and edges (relationships between entities), which help machines better represent context and meaning and can improve search, data integration, and reasoning. This is the definition of GraphRAG.

NOTE For an in-depth look at knowledge graphs and LLMs, see Knowledge Graphs and LLMs in Action by Alessandro Negro et al. (2025; https://www.manning.com/books/knowledge-graphs-and-llms-in-action).

One of the best approaches to implementing GraphRAG comes from Microsoft’s paper “From Local to Global: A GraphRAG Approach to Query-Focused Summarization” (https://arxiv.org/pdf/2404.16130). It presents a graph-based approach to question-answering over private text corpora that scales with both the breadth of user questions and the amount of source text. It uses an LLM to build a graph index in two stages:

  • Derive an entity knowledge graph from the source documents.
  • Pregenerate community summaries for groups of closely related entities.

Given a question, each community summary is used to generate a partial response; these partial responses are then summarized into a final response for the user. This approach, named GraphRAG, substantially improves on a conventional RAG baseline in both the comprehensiveness and the diversity of generated answers.

Figure 14.1, adapted from the Microsoft paper, shows the general GraphRAG workflow. Blocks on the left represent tasks in the indexing phase; blocks on the right represent tasks in the query phase. Some artifacts (such as graph communities and community summaries) are generated during indexing but used at query time, which is why they are shown in a different color. Indexing typically runs offline and produces a KG on top of the knowledge base. Input documents must be selected and preprocessed outside the indexing pipeline, because the quality of the KG depends on the quality of the source documents. The extracted text is chunked and sent to an LLM, which extracts domain-specific entities and relationships (the KG’s nodes and edges) and then detects and summarizes graph communities. Here, a community is a group of nodes that are more densely connected to one another than to the rest of the graph.

graph TD
    TC["Text chunks"] -->|Domain-tailored summarization| ER["Entities & relationships"]
    ER -->|Domain-tailored summarization| KG["Knowledge graph"]
    KG -->|Community detection| GC["Graph communities"]
    GC -->|Domain-tailored summarization| CS["Community summaries"]
    CS -->|Query-focused summarization| CA["Community answers"]

[!visual-conversion] Figure 14.1 — The logical blocks and workflow of Microsoft’s GraphRAG proposal (p. 306)

Imagine a KG representing a movie database with entities such as movies, actors, directors, genres, and production companies. In this setting, communities emerge from relationships between entities. For example, consider the Action Movies community, made up of the following entities (nodes):

  • Movies—“Mad Max: Fury Road,” “Die Hard,” “Mission: Impossible – Fallout”
  • Actors—“Tom Cruise,” “Bruce Willis,” “Charlize Theron”
  • Directors—“George Miller,” “John McTiernan,” “Christopher McQuarrie”
  • Genres—“Action”

It will have the following relationships (edges):

  • “Mad Max: Fury Road” is of genre “Action.”
  • “Die Hard” features actor “Bruce Willis.”
  • “Mission: Impossible – Fallout” features actor “Tom Cruise”
  • “Mad Max: Fury Road” is directed by “George Miller.”
  • “Die Hard” is directed by “John McTiernan.”
  • “Mission: Impossible – Fallout” is directed by “Christopher McQuarrie.”

Figure 14.2 shows the same data as a graph.

These are the characteristics of this community:

  • The movies, actors, and directors in this community are interconnected through multiple relationships (for example, actors appear in multiple action movies).
graph LR
    MM["Mad Max: Fury Road"]
    DH["Die Hard"]
    MI["Mission: Impossible – Fallout"]
    TC["Tom Cruise"]
    BW["Bruce Willis"]
    CT["Charlize Theron"]
    GM["George Miller"]
    JM["John McTiernan"]
    CM["Christopher McQuarrie"]
    AC["Action"]
    MM -->|is_of_genre| AC
    DH -->|features_actor| BW
    MI -->|features_actor| TC
    MM -->|directed_by| GM
    DH -->|directed_by| JM
    MI -->|directed_by| CM

[!visual-conversion] Figure 14.2 — The action movie graph for the preceding example data (p. 307)

  • All entities in this community belong to the “Action” genre, forming a distinct cluster in the KG.
  • This community makes some downstream tasks easier, such as analyzing trends in action movies, studying actor-director collaborations, and generating recommendations for action-movie fans.

During the query phase, a user prompt is enriched with retrieved content (entities and relationships) and community summaries, and then it is passed to the generator model to produce the final answer.

After the GraphRAG paper was published, Microsoft also released an official open source implementation (https://github.com/microsoft/graphrag) under the MIT license. Following the concepts introduced earlier in this section, we’ll build a naive Python implementation that’s framework- and vendor-agnostic. We’ll use a minimal set of Python packages because our goal is to understand the concepts and how they can benefit a RAG system, not to learn a specific implementation. Unlike Microsoft’s GraphRAG implementation, which supports only OpenAI and Azure OpenAI endpoints, we’ll use small, local, open source models. A companion Colab notebook is provided for this section, and we’ll refer to figure 14.1 throughout the implementation.

For this example, we’ll use the quantized Mistral 7B model from the Ollama library (https://ollama.com/library/mistral), hosted on a local Ollama server. I chose it because it performs well at extracting entities and relationships from unstructured text, outperforming other smaller open source models, performing nearly as well as the larger models supported by the MS implementation. The code runs without hardware acceleration, but a GPU is recommended to speed up model tasks, especially when working with a large knowledge base corpus.

The Colab notebook downloads three PDF papers on 8-bit quantization for LLMs—these will serve as our knowledge base. For simplicity, we’ll focus on one of the papers, “On-Device LLMs for Home Assistant: Dual Role in Intent Detection and Response Generation” (https://arxiv.org/pdf/2502.12923), but you can run the notebook with all the documents at any time.

After downloading the PDF, we’ll extract its text and save it to a file for chunking. The notebook provides the extract_text_from_pdfs function to read PDFs from a directory, extract their text, and save it. Next, we’ll chunk the extracted text using the split_text_into_chunks function, which takes the path of the directory containing the text files and a chunk size. It returns a dictionary mapping each original text filename to its list of chunks.

Once the text chunks are available, we can query the model to identify entities and relationships. We’ll assume the Mistral 7B model is deployed and available through our local Ollama server. To send requests to the model, we’ll use the official ollama-python client library (https://github.com/ollama/ollama-python).

We’ll also define a custom function, extract_entities_and_relationships, to make these requests, but first we need to address an issue with the format of the generated responses. I ran multiple experiments with the model using this final prompt:

prompt = f"""Extract entities and relationships from this
text:\n\n{chunk}\n\n
Relationships must follow the format 'Relationship, (Entity1, Entity2)'"""

I was prompting the model to extract entities and relationships from a text chunk and return them in a fixed format, but even with the temperature set to 0, the responses didn’t always match the expected format: a list of entities and a list of relationships. This made parsing difficult before building the KG: about 6% of entity outputs and 25% of relationship outputs had formatting errors.

To avoid this, we’ll use a feature in recent Ollama releases: structured outputs, which constrain the model’s output to a JSON schema. This feature is available through the official Python and JavaScript client APIs. First, we define the schema as a Pydantic class:

from pydantic import BaseModel
class RawKnowledgeGraph(BaseModel):
entities: list[str]
relationships: list[str]

We ask the model to return two lists: one for entities and one for relationships. Then the code to query the model, in the extract_entities_and_relationships function, looks like the following listing.

Listing 14.1 Extracting entities and relationships from a knowledge base

from ollama import chat
t
from ollama import ChatResponse
def extract_entities_and_relationships(chunks_dict, model_id):
results = {}
for filename, chunks in chunks_dict.items():
results[filename] = []
for chunk in chunks:
prompt = f"""Extract entities and relationships from this
text:\n\n{chunk}\n
Relationships must follow the format 'Relationship, (Entity1, Entity2)'""""
response: ChatResponse = chat(model=model_id, messages=[
{
'role': 'user',
'content': prompt,
},
], format=RawKnowledgeGraph.model_json_schema(),
options={"temperature": 0}
)
results[filename].append(response['message']['content'])
return results

This function uses ollama-python’s chat method to send requests for each text chunk in the dictionary and identify entities and relationships between them. These become the nodes and edges of the KG. The function’s output is stored in the content attribute of ollama-python’s ChatResponse class. As specified by the format attribute, it is a dictionary with the filename the chunk belongs to being the key, and the value following the JSON schema is defined by the custom RawKnowledgeGraph Pydantic class. Here’s a truncated sample response for one text chunk:

RawKnowledgeGraph(entities=['On-Device LLMs for Home Assistant', 'Dual Role
in Intent Detection and Response Generation', 'Rune Birkmose', 'Nathan
Mørkeberg Reece', 'Esben Hofstedt Norvin', 'Johannes Bjerva', 'Mike Zhang',
'Aalborg University, Denmark', '{rbirkm20, nreece20,
enorvi20}@student.aau.dk', '[email protected]', 'Large Lan-guage Models
(LLMs)', 'synthetic but domain-representative data', 'slot and intent
detection', 'natural language response generation', 'resource-limited, CPU-only
edge hardware', 'JSON action calls', 'text responses', '16-bit and 8-
bit quantized variants', '4-bit model', 'device-service classification
accuracy', 'noisy human prompts', 'out-of-domain intents', 'IoT Analytics,
2024', 'BBC News, 2025', 'Amazon, Google, and Apple', 'speech recognition
and intent detection on cloud servers', 'privacy concerns', 'data
ownership', 'reliance on proprietary ecosystems'],
relationships=['Investigates, (Large Lan-guage Models (LLMs), On-Device
LLMs for Home Assistant)', 'Fine-tuned, (Large Lan-guage Models (LLMs),
synthetic but domain-representative data)', 'Performs, (On-Device LLMs for
Home Assistant, slot and intent detection)', 'Performs, (On-Device LLMs for
Home Assistant, natural language response generation)', 'Produces, (On-Device
LLMs for Home Assistant, JSON action calls)', 'Produces, (On-Device
LLMs for Home Assistant, text responses)', 'Obtains, (On-Device LLMs for
Home Assistant, around 80-86% accuracy)', 'Affirms, (On-Device LLMs for
Home Assistant, ability to unify command interpretation and flexible
response generation for home automation)', 'Typically handles, (Amazon,
Google, and Apple, speech recognition and intent detection on cloud
servers)', 'Raises concerns about, (cloud servers, privacy, data ownership,
reliance on proprietary ecosystems)']

The returned content needs no further post-processing before we build the KG because the two lists always come back in the expected format. At this point, we can already build a graph from the returned entity and relationship lists. But as recommended in the GraphRAG paper, we’ll first generate summaries for the returned entities.

Our local Mistral 7B model will handle this step. A function for this, summarize_ elements, is available in the notebook. It loops over all elements and, for those in the same text chunk, asks the SLM to generate a summary using the following prompt:

prompt = f"""Summarize the following entities and relationships
in the same structured format:
Entities:
{entities}
Relationships:
{relationships}
"""

The summarized entities (in the same format as the originals) are used to build the KG. For this, we’ll use the NetworkX Python package (https://github.com/networkx/networkx), the standard library for network manipulation.

Once the model returns all required elements

elements = extract_entities_and_relationships(chunks_dict, 'mistral')

and they have been summarized

element_summaries = summarize_elements(elements)

we can iterate over them, build a KG for each, and then merge them into a final graph. A custom build_graph function, provided in the notebook, builds a graph for a single chunk using the NetworkX API. Given lists of entities and relationships, it first creates an empty undirected graph:

import networkx as nx
graph = nx.Graph()

Then it adds the nodes (entities):

graph.add_nodes_from(entities)

Finally, it adds the edges (relationships):

for relationship in relationships:
relationship_name = relationship[0]
subject1 = relationship[1]
if len(relationship) > 2:
subject2 = relationship[2]
graph.add_edge(subject1, subject2, label=relationship_name)
else:
graph.add_node(subject1)

After extracting the relationship name and first entity, the previous snippet determines the second entity, handling the cases with more than two, and adds a node without an edge if only one entity is present. This rare case occurs when the model hallucinates and can’t split a statement into its parts. Note that this is still a minimal implementation, with no validation checks.

The build_graph function iterates over the keys and chunks in the model’s returned dictionary to build partial graphs, which are then merged using NetworkX’s compose function, as in the following listing.

Listing 14.2 Building the KG starting from the generated entities and relationships

combined_graph = nx.Graph()
for filename, chunks_data in element_summaries.items():
for chunk_data in chunks_data:
try:
chunk_knowledge_graph = RawKnowledgeGraph.model_validate_json(chunk_data)
entities = chunk_knowledge_graph.entities
relationships = chunk_knowledge_graph.relationships
graph = build_graph(entities, relationships)
combined_graph = nx.compose(combined_graph, graph)
except Exception as e:
print(f"Error processing data for {filename}: {e}")

Listing 14.2 annotations (printed as margin callouts beside the code, in order):

  1. Checks that the current chunk data is in valid JSON format — RawKnowledgeGraph.model_validate_json(chunk_data)
  2. Extracts the current chunk entities — chunk_knowledge_graph.entities
  3. Extracts the current chunk relationships — chunk_knowledge_graph.relationships
  4. Builds the partial graph — build_graph(entities, relationships)
  5. Combines the partial graph with the main graph — nx.compose(combined_graph, graph)

[!visual-conversion] Listing 14.2 — Building the KG starting from the generated entities and relationships (p. 313)

The generated graph can now be rendered. The visualize_graph_with_plotly function, which visualizes it using the Plotly API for Python, is available in the notebook.

The indexing isn’t finished yet. We still need to compute the communities in this graph. NetworkX includes several community-detection algorithms, including the popular Louvain method. However, the GraphRAG paper reports better results with hierarchical clustering using the Leiden algorithm (https://arxiv.org/abs/1810.08473), which NetworkX doesn’t provide out of the box. The reference implementation is a Python wrapper around the libedgenalg C++ library, so we’ll build a simple pure-Python version.

The Louvain algorithm starts from a singleton partition, with each node in its own community. It then iteratively moves nodes between communities, builds an aggregated network from the resulting partition, and iterates on the aggregated network until the quality score no longer improves. According to the Leiden paper, one problem with the Louvain algorithm is that it can identify communities that are internally disconnected. The Leiden algorithm is partly based on its predecessor but addresses this issue. Like Louvain, it starts from a singleton partition and moves nodes between communities to improve the partition, but it refines the partition before aggregation. An aggregated network is then created based on the refined partition. The algorithm then repeats the move and aggregate steps until no further improvement is possible.

The Leiden algorithm optimizes modularity, a metric that measures how strongly a network divides into clusters. Maximizing modularity helps ensure the communities that are found are well defined and meaningful. The companion Colab notebook includes a simple Python implementation, including a utility function that computes the modularity gain from moving a node to a particular community in the graph:

def calculate_modularity_gain(graph, node, community,
communities, resolution):
m = graph.number_of_edges()
k_i = graph.degree(node)
k_i_in = sum(1 for neighbor in graph.neighbors(node)
if communities[neighbor] == community)
sigma_tot = sum(graph.degree(v) for v in graph.nodes
if communities[v] == community)
return (k_i_in - k_i * sigma_tot / (2 * m)) * resolution

A higher modularity gain means that moving a node into a community would improve the graph’s community structure. The resolution argument controls community size (higher values produce smaller communities). The calculate_modularity_gain function computes the graph’s total edge count, the input node’s degree (number of connections), the node’s number of connections to other nodes in the input community, the target community’s total degree for all nodes in the input community, and the change in modularity if the node is moved. This modularity gain formula compares the actual number of edges within the community with the expected number if edges were distributed randomly; the resolution parameter scales the gain.

A second utility function, aggregate_communities, aggregates (merges) communities in the graph based on their connectivity.

Listing 14.3 Custom function to aggregate communities within a graph

def aggregate_communities(graph, communities):
community_mapping = {}
next_community_id = 0
for component in nx.connected_components(graph):
for node in component:
if communities[node] not in community_mapping:
community_mapping[communities[node]] = next_community_id
next_community_id += 1
communities[node] = community_mapping[communities[node]]
num_communities = next_community_id
return communities, num_communities

Listing 14.3 annotations (printed as margin callouts beside the code, in order):

  1. Iterates across the connected component of the input graph — for component in nx.connected_components(graph):
  2. If the current node’s community isn’t in the community mapping, its ID is assigned a new aggregated community ID. — if communities[node] not in community_mapping:
  3. The current node’s community assignment is updated to the new aggregated community. — communities[node] = community_mapping[communities[node]]

At this stage, each node has an assigned community ID. This function iterates over each connected component (a subgraph in which every node is reachable from every other) in the graph. For each node, it checks whether that community ID is already in the community mapping; if not, it adds it and assigns it a new aggregated community ID. It then updates the node’s community assignment to that aggregated ID. Finally, it returns the updated mapping from nodes to aggregated community IDs, along with the total number of aggregated communities.

The function containing our custom implementation of the Leiden algorithm, leiden_algorithm, uses the two preceding utility functions.

Listing 14.4 The custom implementation of the Leiden algorithm

import random
def leiden_algorithm(graph, resolution=1.0, max_iterations=100):
communities = {node: i for i, node in enumerate(graph.nodes)}
num_communities = len(communities)
for _ in range(max_iterations):
improved = False
for node in graph.nodes:
best_community = communities[node]
best_modularity_gain = 0
for neighbor in graph.neighbors(node): neighbor_community = communities[neighbor]
if neighbor_community != best_community:
modularity_gain = calculate_modularity_gain(graph, node,
neighbor_community, communities, resolution)
if modularity_gain > best_modularity_gain:
best_modularity_gain = modularity_gain
best_community = neighbor_community
if best_community != communities[node]:
communities[node] = best_community
improved = True
for node in graph.nodes:
if len([n for n in graph.nodes if communities[n]
== communities[node]]) == 1:
neighbors = list(graph.neighbors(node))
if neighbors:
communities[node] = communities[random.choice(neighbors)]
if improved:
communities, num_communities = aggregate_communities(graph,
communities)
else:
break
return [communities[node] for node in graph.nodes]

The goal is to identify groups of nodes (communities) that are more densely connected to each other than to the rest of the input graph. Initially, each node is assigned to its own community, so the number of communities equals the number of nodes. The function then iterates for the number of steps specified by the max_iterations argument. For each node, it finds the community that would yield the largest modularity gain if the node were moved. If it finds a better community, it moves the node and sets the improved flag to True. It then runs a second pass across the nodes; any single-node communities (singletons) are reassigned to a neighbor to keep them from being isolated. The final step is community aggregation: if the community structure is improved in the current iteration (that is, improved is True), the aggregate_communities function merges communities based on connectivity. If there is no improvement, the algorithm terminates.

Finally, it returns a list of the final community assignment for each node in the graph:

communities = leiden_algorithm(combined_graph)

As a final indexing step, we generate community summaries using a local Mistral 7B model. First, we identify the unique communities in our list:

unique_communities = sorted(list(set(communities)))

Next, we iterate through the communities to group the nodes by unique community:

community_list = []
for community_id in unique_communities:
community_nodes = [node for node, community in zip(graph.nodes,
community_assignments) if community == community_id]
community_list.append(community_nodes)

community_list is a list of communities, each containing node IDs. In another for loop, we iterate over community_list and extract the text chunks associated with each node in a community:

community_summaries = {}
for community_id, community_nodes in enumerate(community_list):
community_text = ""
for node in community_nodes:
if node in chunks_dict:
for chunk in chunks_dict[node]:
community_text += chunk + "\n"

The community text is used to build a prompt for the Mistral model, which then generates a summary:

prompt = f"""Summarize the following text which represents a community of related documents:
{community_text}
"""
response: ChatResponse = chat(model=model_id, messages=[
{
'role': 'user',
'content': prompt,
},
], options={"temperature": 0})
summary = response['message']['content']

Each generated summary is then added to the community_summaries list:

community_summaries[community_id] = summary

Generating community summaries is expensive because it requires many calls to the model (depending on the number of communities and the size of the knowledge base). If you are running locally, this mostly costs time; if you use a third-party API, you’ll need to factor in charges for API calls and input or generated tokens.

The indexing process is now complete. Next, we’ll look at how we can search these summaries. We’ll implement what the Microsoft paper calls global search. Microsoft’s GraphRAG implementation also includes local search, which we’ll cover in section 14.1.1.

Once we’ve completed the previous steps, users can start asking questions of our knowledge base and receive answers generated by the SLM. Global search uses the following workflow:

  1. Intermediate answers are generated for each community summary in relation to the query.
  2. The final answer is generated by combining the intermediate answers into a concise response.

Let’s see what this implies in code. The notebook’s global search uses two functions: generate_answers and generate_final_answer. The generate_answers function loops through the community summaries and, for each one, queries the local model with the following prompt:

prompt = f"""Query: {query}
Use the following community summary to answer the query:
{summary}
Answer:
"""

It returns a list of generated answers for the user’s query and a summary for each community (a dictionary whose keys are community IDs and whose values are the intermediate answers). Downstream, the generate_final_answer function combines those intermediate answers to enrich the prompt for the local model and produce the final answer:

combined_answers_prompt = "Combine the following answers into a single, concise response:\n\n"
for community_id, answer in intermediate_answers.items():
combined_answers_prompt += f"Community {community_id}: {answer}\n\n"

This is a naive implementation of the GraphRAG paper, and it’s a good way to understand how GraphRAG works and why it can outperform vanilla RAG or other patterns that rely mostly on embedding similarity. Our custom implementation still has plenty of room for improvement, especially for local use. Here are some suggestions:

  • Persist the generated graph elements (entities, entity summaries, communities, and community summaries) in Parquet format to avoid rerunning the indexing process for each new query.
  • Validate the generated entities.
  • Export the graph as GraphML for visual analysis in a third-party tool.
  • Rank the generated community summaries, and then filter them by relevance to the user query before generating intermediate answers. This produces more accurate answers and fewer calls to the generative model.

14.1.1 Microsoft’s open source GraphRAG capabilities

Section titled “14.1.1 Microsoft’s open source GraphRAG capabilities”

As mentioned earlier in this chapter, Microsoft released an open source implementation based on the GraphRAG paper. In its implementation, it offers two options at query time:

  • Global search—Answers to user queries are based on community summaries generated at indexing time, which is the core idea of the GraphRAG paper. We used the same strategy in our custom implementation.
  • Local search—Answers are generated by combining relevant data from an AI-extracted KG (entities) with text chunks from the source documents (embeddings). This option also converts the knowledge base to vectors and stores them in a vector database. This approach is out of scope for this book.

Microsoft’s GraphRAG solution has been implemented in Python using only open source packages, but it supports only OpenAI’s commercial generative and embedding models via the OpenAI or Azure OpenAI APIs. It doesn’t support running open source SLMs locally or using other providers’ APIs. Still, it’s worth considering as an end-to-end solution: the code is open source, so you can fork the GitHub repository and adapt it to use local models via the Hugging Face Transformers library, vLLM, or Ollama, or use open source SLMs through Hugging Face endpoints.

Microsoft’s open source GraphRAG solution includes built-in logic to persist the graph and related artifacts, such as communities and community summaries. It stores everything in Parquet format on disk or in Azure Blob Storage or Cosmos DB.

NOTE Apache Parquet (https://parquet.apache.org/) is an open source, column-oriented storage format designed for efficient analytics and large-scale data processing. It uses compression and encoding to support complex data structures and fast queries.

Microsoft’s local search option in GraphRAG stores document embeddings in a vector database. This persistence works out of the box when you use a supported option: the open source LanceDB (introduced in chapter 13) or the Azure services Cosmos DB and Azure AI Search. Even if you plan to use only global search, indexing still requires a connection to one of the supported vector databases. To use a different graph store or vector database, you must fork the GraphRAG GitHub repository and implement it yourself.

Microsoft’s open source GraphRAG comes with a CLI, so we don’t need to write any Python code (as long as we use only the supported models and storage systems). The package can be installed as follows:

Terminal window
pip install graphrag

Once that’s done, we can initialize a GraphRAG space using the graphrag command, providing the path to the workspace root directory:

Terminal window
graphrag init --root <graphrag_space_root_dir>

After the workspace is created, edit the two configuration files it generates: .env, where you add your OpenAI or Azure OpenAI key, and settings.yaml, where you configure everything else (vector database connection, graph storage, LLM and embedding model settings, logging, and so on).

Then start indexing your knowledge base by running the same graphrag command in a terminal and waiting for it to complete:

Terminal window
graphrag index --root <graphrag_space_root_dir>

Once the indexing process is completed, we can perform a query as follows:

Terminal window
graphrag query --root <graphrag_space_root_dir> --method <search_method> --query "What are the main topic in this documents?"

In the simplest use case, we provide the workspace root path, the search method (global or local), and a query. Although the CLI is straightforward, we can also use this GraphRAG implementation programmatically via its Python API.

If you build a custom integration with other models, graph storage, or a vector store, you can still use the CLI in your fork to initialize the workspace, index data, and run queries.

Microsoft’s open source GraphRAG includes the building blocks, but it lacks capabilities such as text extraction and document preprocessing, graph visualization, and results evaluation. For these, you’ll need to integrate third-party open source or proprietary tools.

RAG improves the accuracy of LLM responses. There are many techniques and frameworks for evaluating LLM outputs (some covered in earlier chapters), but how can we assess the language models used in a RAG system, including GraphRAG? Which metrics should we use?

Traditional metrics, such as BLEU and ROUGE, widely used in NLP, often fail to capture what RAG applications require, such as factual accuracy and context relevance. BLEU doesn’t account for the context or evidence in the retrieved documents, which can leave gaps in evaluating factual accuracy, whereas ROUGE emphasizes recall and largely ignores precision. RAG needs both precision (how much retrieved information is relevant) and recall (how much relevant information is retrieved). We therefore need specialized RAG metrics, including metrics tailored to each phase of the pipeline (retrieval and generation).

NOTE BLEU (Bilingual Evaluation Understudy) is a precision-based metric that evaluates the overlap of sequences of words between the generated response and a reference response. ROUGE (Recall-Oriented Understudy for Gisting Evaluation) measures the overlap of word sequences and word pairs between the generated response and reference texts, with a focus on recall.

For retrieval, these are meaningful dedicated evaluation metrics:

  • Context precision—This measures how precisely the retrieved documents provide relevant information for a given query.
  • Context recall—This assesses how well the retrieved documents cover all relevant aspects of a query.

For answer generation, these are meaningful dedicated evaluation metrics:

  • Faithfulness—This measures the factual accuracy of a generated response against the retrieved documents.
  • Answer relevancy—This assesses how relevant a generated response is to the original query.

In theory, you can combine the preceding metrics into an average RAG score. In practice, you must assign a weight to each score based on its importance in your domain (see table 14.1).

Table 14.1 RAG-specific metrics

MetricRAG phaseFormula
Context precisionRetrievalCP = Number of relevant sentences retrieved / Total number of sentences retrieved
Context recallRetrievalCR = Number of relevant sentences retrieved / Total number of relevant sentences available
FaithfulnessGenerationF = Number of correct facts in the response / Total number of facts in the response
Answer relevancyGenerationAR = Number of relevant concepts in the response / Total number of concepts in the response

Table 14.1 summarizes these metrics for use in RAG systems. At the time of writing, only one open source Python library, Ragas (https://github.com/explodinggradients/ragas), implements these RAG-specific metrics, but it supports only commercial LLMs via the OpenAI, Azure OpenAI, and Google Vertex AI APIs, or models deployed on AWS Bedrock. You’ll need a custom implementation to support local SLMs and custom models.

In chapter 13, we discussed RAG (and continued in the first part of this chapter) and agentic AI. With those core concepts in mind, it’s natural to consider using them together—a pattern commonly known as agentic RAG. In a traditional RAG system, a retriever model pulls information relevant to a user query from one or more external sources (databases, vector stores, the web, and so on) and passes it to a language model that generates a response using the added context. When you add AI agents to a RAG system, they can plan multi-step retrieval, adapt to what they find by updating queries,

and use multiple tools to improve response accuracy. By breaking complex tasks into smaller, specialized ones (often using specialized tools and/or smaller agents), agentic frameworks can make a RAG system more efficient, effective, and easier to understand and maintain. This setup is well suited to customer support, research assistance, knowledge management, and domain-specific problem solving. Figure 14.3 shows a logical schema for a generic, basic agentic RAG system:

graph LR
    VDB[("Vector database")]
    Q{"Has info been found in the database?"}
    R["Response"]
    W["Web search tool"]
    I(["Internet"])
    VDB --> Q
    Q -->|Yes| R
    Q -->|No| W
    W --> I
    I --> R

[!visual-conversion] Figure 14.3 — The logical schema of a basic agentic RAG system (p. 322)

Given a user query, the agent searches the vector database. If the retrieved information isn’t relevant to the question, it then searches the web for additional context before generating the final answer.

Simple, flexible, and well integrated with the wider Python ecosystem for RAG—and with broad support for SLMs—smolagents (introduced in chapter 13) is a great choice for building an agentic RAG system. Let’s implement a basic example like the one in figure 14.3.

A companion Colab notebook with the complete code is provided. We’ll use the following open source Python libraries:

  • LangChain
  • pypdf
  • LanceDB
  • smolagents
  • rank_bm25
  • langchain-community
  • langchain-huggingface

You’re already familiar with LanceDB, smolagents, and pypdf (from chapter 13). LangChain (https://github.com/langchain-ai/langchain) is a framework for building LLM-powered applications, with standard interfaces for models, embeddings, vector stores, and more. I generally avoid frameworks that hide too much of the underlying logic because they can be harder to debug or customize, but LangChain is handy for implementing RAG systems. In this example, we’ll use it mainly for the RAG components. We’ll also use LangChain Community, which provides third-party integrations that implement the interfaces defined in the LangChain core framework. For a deeper dive into the ecosystem, see AI Agents and Applications: With LangChain, LangGraph, and MCP by Roberto Infante (Manning Publications, 2026).

For this example, we’ll use the same paper as before (https://arxiv.org/pdf/2502.12923) as our knowledge base. After downloading the PDF to the Colab VM, we’ll use the LangChain utility classes PyPDFLoader and RecursiveCharacterTextSplitter to load it, extract its text, and split it into chunks:

from langchain.document_loaders import PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
loader = PyPDFLoader("/content/arxiv_250212923.pdf")
documents = loader.load()
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000,
chunk_overlap=100)
docs = text_splitter.split_documents(documents)

Here, docs is a list of LangChain langchain.docstore.document.Document objects—one for each text chunk.

We can now implement the agent’s first tool. In chapter 13, we built smolagents tools using the @tool decorator, and you also saw that you can achieve the same result by extending the Tool class. Here we’ll use the latter approach because it makes it easier to manage access to the knowledge base.

The first tool we’ll create performs traditional text search to retrieve the parts of the source document most relevant to a user query. It uses BM25, a standard information-retrieval ranking algorithm that scores documents based on term frequency, inverse document frequency, and document length. BM25 is widely used in search engines and is the default ranking method in tools such as Elasticsearch and Apache Lucene. LangChain includes a built-in implementation.

This first tool class can be defined as follows:

from smolagents import Tool
class BM25SearchTool(Tool):
name = "do_bm25_search_on_local_documents"
description = "Uses text search to retrieve the parts of the documentation that could be most relevant to answer a query."
inputs = {
"query": {
"type": "string",
"description": "The search query string."
},
}
output_type = "string"

In addition to extending the smolagents Tool class, we have added the required attributes: name, description, inputs, and output_type. The last two specify the tool’s input and output types. BM25SearchTool implements the init function to initialize the class with the knowledge base:

from typing import List
from langchain.docstore.document import Document
def __init__(self, docs: List[Document], **kwargs):
super().__init__(**kwargs)
self.docs = docs

The BM25SearchTool class also implements the forward method, which defines what the agent does when it uses the BM25SearchTool:

from langchain_community.retrievers import BM25Retriever
def forward(self, query: str) -> str:
retriever = BM25Retriever.from_documents(self.docs, k=3)
docs = retriever.invoke(query)
return "\nRetrieved documents:\n" + "".join(
[f"\n\n==== Document {i} ==== \n" + doc.page_content for i,
doc in enumerate(docs)]
)

It uses LangChain’s BM25Retriever to search the document chunks.

Now let’s download the SLMs for our agent (as we did in the example in chapter 13):

import torch
from smolagents import TransformersModel
model_id = "HuggingFaceTB/SmolLM2-1.7B-Instruct"
model = TransformersModel(model_id,
device_map="auto",
max_new_tokens=700,
torch_dtype=torch.float16)

After loading the model checkpoints, we can initialize the tool with the text-chunk pool that makes up our knowledge base:

bm25_search_tool = BM25SearchTool(docs)

Finally, we can implement the CodeAgent (discussed in section 13.3):

from smolagents import CodeAgent
agent = CodeAgent(
tools=[bm25_search_tool],
model=model,
max_steps=3,
verbosity_level=2,
add_base_tools=True
)

Let’s examine how this works before making the system more complex. After giving the agent only the BM25 custom search tool (in addition to those in the smolagents base toolbox), we ask it to search for a set of keywords:

query = "Make a BM25 search about Smart Home technologies"
agent_output = agent.run(query)

It automatically selects the right tool for the job (see figure 14.4) in the first execution step.

────────────────────── New run ──────────────────────
Make a BM25 search about Smart Home technologies
─ TransformersModel - HuggingFaceTB/SmolLM2-1.7B-Instruct ─
─────────────────────── Step 1 ───────────────────────
Output message of the LLM:
assistant
Thought: I will use the `do_bm25_search_on_local_documents` tool to perform a BM25 search on the local documents
for Smart Home technologies.
Code:
```py
search_query = "Smart Home technologies"
bm25_search = do_bm25_search_on_local_documents(query=search_query)
print(bm25_search)
```<end_code>
─ Executing parsed code: ─
search_query = "Smart Home technologies"
bm25_search = do_bm25_search_on_local_documents(query=search_query)
print(bm25_search)

[!visual-conversion] Figure 14.4 — CodeAgent output for search at the first execution step (p. 325)

From the output in figure 14.4, we can see that the do_bm25_search_on_local_documents tool was selected, and the agent generated Python code to call it with the correct input (the keywords from our query). In this case, the search returns results because the knowledge base covers edge-device topics, including smart home technology. Here is the tool-call response (three chunks, since the code limit is set to 3):

======
Document 0 =====
retaining generative fluency, suffers a notice-
able drop in device-service classification ac-
curacy. Further evaluations on noisy human
(non-synthetic) prompts and out-of-domain in-
tents confirm the models' generalization abil-
ity, obtaining around 80-86% accuracy. While
the average inference time is 5-6 seconds per
query-acceptable for one-shot commands but
suboptimal for multi-turn dialogue—our results
affirm that an on-device LLM can effectively
unify command interpretation and flexible re-
sponse generation for home automation without
relying on specialized hardware.
1 Introduction
Smart home technologies and IoT devices have
proliferated in recent years, with an expected rise
from 16.6 billion to 18.8 billion connected devices
by the end of 2024 (IoT Analytics, 2024). Major
providers like Amazon, Google, and Apple typ-
ically handle speech recognition and intent detec-
tion on cloud servers, which raises user concerns
about privacy, data ownership, and reliance on pro-
======
Document 1 =====
dataset (acon96, 2024), which consists of 35,840
synthetic examples designed to mimic Home As-
sistant commands. Each instance consists of:
• A User Prompt: e.g., "Turn on the kitchen
light", "Set the thermostat to 22 degrees".
• One Valid JSON Action , containing the
service and device fields corresponding to
Home Assistant calls.
• A Natural Language Response: e.g., a para-
phrase or affirmation of the action taken.
2
======
Document 2 =====
• Slot and Intent Detection: The model out-
puts a valid JSON object that maps to a de-
sired service (intent) and device (slot) pair:
{"service": "light.turn_on",
"device": "light.living_room",
"assistant": "Sure, turning on
on the living room light."}
• Natural Language Generation: The model
also produces a textual response confirming
or elaborating on its action, as can be seen
in the example above. The text can then be
propagated to, e.g., a text-to-speech model.
Traditional classifiers only handle device-service
classification and do not produce any text. For user-
facing text, the baseline approach would rely on
templated responses.
3.1 Data and Pre-processing
To the best of our knowledge, there is no ex-
isting human-curated dataset specifically for the
Home Assistant software. Thus, we rely on syn-
thetic data. We use a publicly available synthetic
dataset (acon96, 2024), which consists of 35,840
synthetic examples designed to mimic Home As-

All three chunks are relevant to the query topic. The top result contains all three keywords the agent passed to the tool, while the others contain only one keyword (or closely related terms).

Let’s make the system more complex by adding a vector database to store our knowledge base as embeddings and a new similarity-search tool. This will let us see whether the agent chooses keyword search, vector search, or a hybrid of both. Hybrid search combines keyword and vector search to further improve retrieval quality (and, in turn, improve any downstream tasks that use the returned documents).

First, we need an embedding model:

from langchain_huggingface import HuggingFaceEmbeddings
embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")

We use the langchain-huggingface package’s HuggingFaceEmbeddings class to download the embedding model from the Hugging Face Hub. This time, we’ll use all-MiniLM -L6-v2, also available via the sentence-transformers library; it’s fast and delivers good quality.

Next, we’ll create and populate a vector database. We’ll use LanceDB, the same vector database we used for the RAG examples in chapter 13. We’ll create a local database

import lancedb
db = lancedb.connect("./lancedb")

define a schema

import pyarrow as pa
schema = pa.schema([
pa.field("embedding", pa.list_(pa.float32(), list_size=384)),
pa.field("text", pa.string()),
])

and create the destination table, applying the schema, and populate it:

import numpy as np
table = db.create_table(
"document_embeddings",
schema=schema,
data=[
{
"embedding": np.array(embeddings.embed_query(doc.page_content),
dtype=np.float32).flatten().tolist(),
"text": doc.page_content,
}
for doc in docs
],
)

The text column in the document_embeddings table contains the original text chunks, and the embedding column contains the corresponding embeddings. The table is populated from the original PDF’s text chunks.

Now we can implement SemanticSearchTool, the agent’s second tool, to run semantic searches on this database.

Listing 14.5 Implementing a semantic search tool in smolagents

from smolagents import Tool
class SemanticSearchTool(Tool):
name = "semantic_search"
description = "Performs semantic search on a database of document embeddings."
inputs = {
"query": {
"type": "string",
"description": "The search query string.",
},
"top_k": {
"type": "integer",
"description": "The number of top results to return.",
"default": 1,
"nullable": True,
},
}
output_type = "string"

As with the BM25 tool, we implement init so the class can be initialized with a LanceDB table and the embedding model:

def __init__(self, table, embeddings, **kwargs):
super().__init__(**kwargs)
self.table = table
self.embeddings = embeddings

Finally, we implement the forward function, which contains the code that runs when the agent uses this tool:

def forward(self, query: str, top_k: int = 1) -> str
"""Performs semantic search on the document_embeddings table."""
query_embedding = self.embeddings.embed_query(query)
query_embedding = np.array(query_embedding)
results = self.table.search(query_embedding,
vector_column_name="embedding").limit(top_k).to_df()
return results.to_string()

This function takes a query string and the number of documents to return. It then converts the query to embeddings and runs a semantic search. After searching the LanceDB table, it returns the results to the caller as a pandas DataFrame. Each row contains a retrieved chunk, the corresponding embeddings, and the distance from the query embeddings.

Now we’ll initialize the tool and add it to the agent’s custom toolbox:

semantic_search_tool = SemanticSearchTool(table, embeddings)
agent = CodeAgent(
tools=[bm25_search_tool, semantic_search_tool],
model=model,
max_steps=3,
verbosity_level=2,
add_base_tools=True
)

Finally, we’ll run it:

query = "Make a semantic search about Smart Home technologies"
agent_output = agent.run(query)

The agent’s output is shown in figure 14.5.

────────────────────── New run ──────────────────────
Make a semantic search about Smart Home technologies
─ TransformersModel - HuggingFaceTB/SmolLM2-1.7B-Instruct ─
─────────────────────── Step 1 ───────────────────────
Output message of the LLM:
assistant
Thought: I will use the `semantic_search` tool to perform a semantic search on the topic of Smart Home
technologies.
Code:
```py
answer = semantic_search(query="Smart Home technologies")
print(answer)
```<end_code>
─ Executing parsed code: ─
answer = semantic_search(query="Smart Home technologies")
print(answer)

[!visual-conversion] Figure 14.5 — Output from the updated CodeAgent search after the first execution step (p. 329)

We can see that the semantic_search tool (whose name was configured in SemanticSearchTool ) was selected, and the agent generated Python code to call it with the correct prompt. Because the code sets limit to 1, the search returns only the top result. The following output is the raw response from the tool call (embeddings, text, and distance), which you can refine downstream:

0 [-0.060476277, -0.07417085, 0.04922669, -0.021070601, 0.08913301,
-0.052974354, 0.06162752, -0.03218482,
0.00018902471, 0.007836956, -0.06839714, -0.014279998, 0.038929846,
-0.031182423, 0.076972865, -0.016114458,
0.12007754, -0.09009497, -0.043700386, -0.023762181, -0.00475547,
0.1318493, 0.04764576, 0.03634429, 0.048965942,
-0.062287927, 0.011540382, -0.08939378, -0.015377631, -0.031084208,
-0.0009671837, 0.054765128, 0.039253484,
0.06100833, -0.033431966, -0.021377146, 0.04979007, -0.003665536,
-0.001359899, -0.083, 0.024330147, -0.09869668,
-0.021324364, 0.006738895, 0.044605985, 0.008814336, -0.060209617,
-0.09980741, -0.025720797, 0.033721954,
-0.02343119, 0.033265233, 0.051016644, 0.043846488, -0.06426977,
0.043782152, 0.024849152, 0.07974727, 0.0949892,
0.066858895, -0.050578196, -0.10973127, -0.0034362087, 0.028922668,
0.067702985, 0.024692042, 0.058714554,
-0.049815375, 0.02196071, -0.037720874, 0.01877667, 0.04346404,
-0.085134467, 0.06124369, 0.0032529002,
0.0019797517, 0.015414694, -0.040237047, 0.035975154, -0.092962235,
-0.010244271, -0.023763157, -0.029036986,
0.056005232, 0.0070075965, -0.0123536475, -0.024238087, 0.07478274,
-0.004049021, 0.032314133, 0.049606774,
-0.12274005, 0.0621215, -0.039671533, -0.0063501373, 0.041631296,
-0.035621937, -0.1273948, -0.06314974, 0.0728013,
...] retaining generative fluency, suffers a notice\-nable drop in
device\-service classification ac\-curacy.
Further evaluations on noisy human\n(non\-synthetic) prompts and
out\-of\-domain in\-tents confirm the models'
generalization abil\-nity, obtaining around 80\-86% accuracy.
While\nthe average inference time is 5\-6 seconds
per\nquery\-acceptable for one\-shot commands but\nsuboptimal for
multi\-turn dialogue\-our results\naffirm that an
on\-device LLM can effectively\nunify command interpretation and
flexible re\-sponse generation for home automation
without\nrelying on specialized hardware.\n1 Introduction\nSmart
home technologies and IoT devices
have\nproliferated in recent years, with an expected rise\nfrom
16.6 billion to 18.8 billion connected devices\nby
the end of 2024 (IoT Analytics, 2024). Major\nproviders like Amazon,
Google, and Apple typi\-cally handle speech
recognition and intent detec\-tion on cloud servers, which raises user
concerns\nabout privacy, data ownership,
and reliance on pro\- 1.070648

We can combine the two custom tools into one to enable hybrid search in the vector database. This new tool is still a class that extends smolagents’ Tool:

from smolagents import Tool
class HybridSearchTool(Tool):
name = "hybrid_search"
description = "Performs a hybrid search (BM25 keyword + vector search) on a LanceDB table."
inputs = {
"query": {
"type": "string",
"description": "The search query string.",
},
"top_k": {
"type": "integer",
"description": "The number of top results to return.",
"default": 1,
"nullable": True,
},
}
output_type = "string"

The init function initializes LangChain’s EnsembleRetriever, a class that combines results from multiple retrievers (here, BM25 and semantic search):

from langchain.retrievers import EnsembleRetriever
def __init__(self, bm25_retriever, semantic_retriever, **kwargs):
super().__init__(**kwargs)
self.ensemble_retriever = EnsembleRetriever(
retrievers=[bm25_retriever, semantic_retriever],
weights=[0.4, 0.6])

We have weighted BM25 at 0.4 and semantic search at 0.6.

The forward function runs the hybrid search and returns the raw result to the caller (you can add postprocessing here):

def forward(self, query: str, top_k: int = 1) -> str:
docs = self.ensemble_retriever.get_relevant_documents(query)
return "\nRetrieved documents:\n" + "".join(
[f"\n\n==== Document {i} ==== \n" + doc.page_content for i,
doc in enumerate(docs)]
)

LangChain includes a built-in BM25 retriever but not a semantic one, so we’ll implement our own semantic retriever class, LanceBDVectorSearch, for the hybrid search tool:

from langchain.schema import BaseRetriever
from pydantic import Field
class LanceBDVectorSearch(BaseRetriever):
table: lancedb.table.LanceTable = Field(...)
embeddings: HuggingFaceEmbeddings = Field(...)

It extends LangChain’s BaseRetriever abstract class and requires two attributes: table (the LanceDB table to search) and embeddings (the embedding model used for queries). Both are set in the class’s init method:

def __init__(self, table: lancedb.table.LanceTable, embeddings:
HuggingFaceEmbeddings):
super().__init__(table=table, embeddings=embeddings)

Finally, we’ll implement the BaseRetriever’s _get_relevant_documents function to retrieve documents by running semantic search on a LanceDB table for a given query.

Listing 14.6 Semantic search on a LanceDB table

from typing import List
from langchain.schema import Document
def _get_relevant_documents(self, query: str) -> List[Document]:
query_embedding = self.embeddings.embed_query(query)
query_embedding = np.array(query_embedding)
results = self.table.search(query_embedding,
vector_column_name="embedding").limit(2).to_pandas()
documents = [
Document(page_content=row["text"], metadata={})
for _, row in results.iterrows()
]
return documents

We’ll now increase the complexity by replacing the toolbox tools with the new hybrid search tool and DuckDuckGo’s built-in web search:

from smolagents import DuckDuckGoSearchTool
search_tool = DuckDuckGoSearchTool()
bm25_retriever = BM25Retriever.from_documents(docs, k=3)
semantic_retriever = LanceDBVectorSearch(table=table,
embeddings=embeddings)
hybrid_search_tool = HybridSearchTool(bm25_retriever,
semantic_retriever)
agent = CodeAgent(
tools=[hybryd_search_tool, search_tool],
model=model,
max_steps=3,
verbosity_level=2,
add_base_tools=True
)

When you run the agent with the query “Do a hybrid search about Smart Home technologies,” it automatically selects the right tool for the job (see figure 14.6).

────────────────────── New run ──────────────────────
Do an hybrid search about Smart Home technologies
─ TransformersModel - HuggingFaceTB/SmolLM2-1.7B-Instruct ─
─────────────────────── Step 1 ───────────────────────
Output message of the LLM:
assistant
Thought: I will use the `hybrid_search` tool to perform a hybrid search on Smart Home technologies.
Code:
```py
smart_home_search = hybrid_search(query="Smart Home technologies")
print(smart_home_search)
```<end_code>
─ Executing parsed code: ─
smart_home_search = hybrid_search(query="Smart Home technologies")
print(smart_home_search)
Execution logs:
Retrieved documents:
===== Document 0 =====
retaining generative fluency, suffers a notice-
able drop in device-service classification ac-
curacy. Further evaluations on noisy human

[!visual-conversion] Figure 14.6 — CodeAgent output showing the correct tool choice (hybrid search on the local LanceDB database) and correct Python code for the query (p. 333)

────────────────────── New run ──────────────────────
Search the web for MSD
─ TransformersModel - HuggingFaceTB/SmolLM2-1.7B-Instruct ─
─────────────────────── Step 1 ───────────────────────
Output message of the LLM:
assistant
Thought: I will use the tool `web_search` to search the web for MSD.
Code:
```py
msd_search = web_search(query="MSD")
print(msd_search)
```<end_code>
─ Executing parsed code: ─
msd_search = web_search(query="MSD")
print(msd_search)
Execution logs:
## Search Results
[MSD | Home](https://www.msd.com/)
At MSD, we're following the science to tackle some of the world's greatest health threats. Get a glimpse of how we
work to improve lives.
[Who we are - MSD](https://www.msd.com/company-overview/)
MSD is a global leader in research and innovation for health solutions for people and animals. Learn about its
purpose, values, diversity, leadership and products.
[Worldwide locations - MSD](https://www.msd.com/contact-us/worldwide-locations/)
Contact information for all MSD worldwide locations. For patients and health care professionals. MSD Manuals
Medical information source covering thousands of topics in all fields of medicine ; Clinical trials Learn about our
clinical trials and find available studies

[!visual-conversion] Figure 14.7 — CodeAgent output showing the proper tool choice (web search) and correct Python code for the query (p. 333)

When you provide a different query, such as “Search the web for MSD,” it selects the web search tool to look up information about the MSD company (see figure 14.7).

When you pass a multistep query such as “Do a hybrid search about smart home technologies and then search the web about the same,” the agent can identify the two steps, select the right tool, and generate the Python code for each (see figure 14.8). It then returns a collection of local and web results.

────────────────────── New run ──────────────────────
Do an hybrid search about Smart Home technologies and then search the web about the same
─ TransformersModel - HuggingFaceTB/SmolLM2-1.7B-Instruct ─
─────────────────────── Step 1 ───────────────────────
Output message of the LLM:
assistant
Thought: I will perform a hybrid search about Smart Home technologies and then search the web about the same.
Code:
```py
smart_home_search = hybrid_search(query="Smart Home technologies")
print("Hybrid search results:", smart_home_search)
web_search_results = web_search(query="Smart Home technologies")
print("Web search results:", web_search_results)
```<end_code>
─ Executing parsed code: ─
smart_home_search = hybrid_search(query="Smart Home technologies")
print("Hybrid search results:", smart_home_search)
web_search_results = web_search(query="Smart Home technologies")
print("Web search results:", web_search_results)

[!visual-conversion] Figure 14.8 — CodeAgent output for a query requiring multiple tools (p. 334)

This is a simple implementation of an agentic RAG system, but it shows when it’s a good fit: when information is spread across multiple sources, as is common in organizations. The best practices for improving agents built with smolagents (such as those in section 12.3 and chapter 13) also apply to agentic RAG implementations.

14.3 Long- and short-term memory management

Section titled “14.3 Long- and short-term memory management”

You can further improve the performance of language-model applications—such as RAG systems, chatbots, and AI agents—by enriching the model’s prompt with context built from previous interactions with the same user (or session). Retrieving relevant content from past conversations and prompts, using short- or long-term memory, can narrow queries and searches and help models return more fine-grained, accurate answers.

NOTE Short-term memory tracks the ongoing conversation by maintaining message history within a session. Long-term memory stores user-specific or application-level data across sessions and is shared across conversational threads. It can be recalled at any time and in any thread.

This approach can also reduce costs by lowering the number of API calls and generated tokens. Even GraphRAG systems, which are more accurate than many other LLM-based solutions by design, can benefit from a memory-management strategy. Memoripy (https://github.com/caspiannmoon/memoripy) is an open source Python package that addresses this need. It supports LLM-based applications that require memory management, and it’s compatible with models behind the OpenAI and Azure OpenAI APIs, models available through the OpenRouter commercial API, and local open source SLMs available through the Ollama API.

Notable features that make Memoripy stand out include

  • Short- and long-term memory management—Based on relevance to the current user conversation.
  • Contextual retrieval—Memory retrieval is based on embeddings, concepts, and past interactions.
  • Concept extraction and embeddings—It uses language models to extract concepts and generate embeddings.
  • Graph-based associations—It builds a concept graph and uses spreading activation for relevance-based retrieval.
  • Hierarchical clustering—Memoripy clusters similar memories into semantic groups for more contextually relevant retrieval.
  • Decay and reinforcement—Older memories fade over time, while frequently accessed memories are reinforced.

NOTE Spreading activation is a method for searching associative networks, artificial neural networks, or semantic networks. The search process is initiated by labeling a set of source nodes (concepts) with weights (activation) and then iteratively propagating (spreading) that activation out to other nodes linked to the source nodes. It is often applied in information retrieval tasks.

Memoripy provides three built-in options for storing interaction data: in memory, in JSON files, or in Amazon DynamoDB (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html). Memory storage is suitable for development, debugging, and testing. JSON files can be a good option for local deployments. DynamoDB is more appropriate for large, distributed deployments. You can also add other backends by implementing the BaseStorage abstract class.

As you saw in the previous Memoripy feature list, user–model interaction data (prompts and responses in multi-turn conversations) is organized as a graph, like the knowledge base in GraphRAG. The graph is built with the NetworkX library (used earlier in this chapter). Indexes on the memory graph are created with Facebook AI Similarity Search (FAISS, introduced in chapter 2). Graph creation and updates are transparent to developers: Memoripy manages them internally, so you can focus on application-specific requirements rather than low-level processes.

The Memoripy workflow is as follows:

1 Previous interactions are loaded from the chosen storage option, and memory is initialized.

2 Once a new interaction has happened (the user’s prompt and the model’s response), the system stores it with its embedding and concepts.

3 Interactions relevant to the new one are retrieved by searching past interactions using cosine similarity, decay factors, and spreading activation.

4 The final response combines the current prompt with the retrieved interactions to keep it relevant to the context.

5 Unused memories decay faster, while frequently accessed ones are reinforced.

Again, this flow is transparent to developers, and it is fully managed by the underlying library.

Next, we’ll implement memory management with Memoripy using only SLMs served from a local Ollama instance. In this example, you’ll need an Ollama server running with the mxbai-embed-large embedding model (https://huggingface.co/ mixedbread-ai/mxbai-embed-large-v1) and the Microsoft Phi-3 Mini 4K Instruct model already pulled and available through the server’s REST API. You can install Memoripy from PyPI, or clone the GitHub repository and install the requirements to get the latest updates.

First, we’ll set up a storage option (a JSON file in this case):

from memoripy import JSONStorage
storage_option = JSONStorage("interaction_history.json")

Next, we’ll initialize the MemoryManager, specifying the generator and embedding models and the chosen storage option:

from memoripy import MemoryManager
from memoripy.implemented_models import OllamaChatModel, OllamaEmbeddingModel
chat_model_name = "phi3.5"
embedding_model_name = "mxbai-embed-large"
memory_manager = MemoryManager(OllamaChatModel(chat_model_name),
OllamaEmbeddingModel(embedding_model_name),
storage=storage_option)

OllamaChatModel and OllamaEmbeddingModel are the classes for models hosted on an Ollama server. Memoripy provides similar classes for OpenAI, Azure OpenAI, and OpenRouter models. During initialization, the MemoryManager loads any persisted interactions.

Whenever a user submits a new prompt, we need to load the short-term interactions:

short_term, _ = memory_manager.load_history()
last_interactions = short_term[-short_term_threshold:] if len(short_term) >= short_term_threshold else short_term

We set a threshold, short_term_threshold, to define which interactions count as short-term.

Also, the interactions most relevant to the current prompt need to be retrieved:

relevant_interactions = memory_manager.retrieve_relevant_interactions(query,
exclude_last_n=short_term_threshold)

We can now generate an answer to the prompt by enriching its context with the relevant short- and long-term interactions:

response = memory_manager.generate_response(query, last_interactions,
relevant_interactions)

Each new interaction like this one requires updating the persisted data. We need to capture these core concepts from the latest interaction:

combined_text = f"{query} {response}"
concepts = memory_manager.extract_concepts(combined_text)

Finally, we’ll store it with its embedding and concepts:

new_embedding = memory_manager.get_embedding(combined_text)
memory_manager.add_interaction(query, response, new_embedding, concepts)

The system is now ready for the next interaction.

The structure we see in storage (a JSON file in this case, but the structure is the same for all the supported options) looks like this—I’ve truncated the embedding list:

{
"short_term_memory": [
{
"id": "f1d186b2-e568-48f0-bd96-7c3134b48ef6",
"prompt": "My name is Guglielmo",
"output": "Hello, I am an AI developed to assist you with information and tasks within my capabilities. How can I help you today? If there are specific questions or topics related to your interests that come up frequently in our conversations about history, art, culture, science, technology, etc., feel free to share them!",
"embedding": [
0.5885149240493774,
-0.3385206162929535,
...
],
"timestamp": 1744199614.9675484,
"access_count": 1,
"concepts": [
"Guglielmo",
"art",
"culture",
"science",
"history",
"information and tasks",
"technology",
"AI assistant"
]
}
]
}
],
"decay_factor": 1.0
},
"long_term_memory": []
}

There are two sections: one for short-term memory and one for long-term memory. In the preceding example, the long-term memory section is empty because the file reflects the model’s first user interaction. When populated, it follows the same schema as the short-term section:

  • id—The unique identifier of a memory entry
  • prompt—The user input
  • output—The generated response
  • embedding—The vector corresponding to the response
  • timestamp—The moment in time the response has been generated
  • access_count—The number of times this entry has been retrieved for any further interaction
  • concepts—The list of concepts derived from this interaction
  • decay_factor—A weight used to promote or demote an interaction in time

The library uses timestamp, access_count, and decay_factor for decay and reinforcement, and embedding and concepts to retrieve relevant past interactions.

At the time of writing, Memoripy is a young but powerful Python project for memory management in LLM-based applications. Keep an eye on the official GitHub repo for updates.

  • GraphRAG improves on traditional RAG by using knowledge graphs to model entity relationships and support multihop reasoning across document collections.
  • Knowledge graphs (KGs) organize information, representing entities as nodes and relationships as edges.
  • Microsoft’s GraphRAG approach builds entity KGs from source documents and pregenerates community summaries for related entity groups.
  • Ollama structured outputs constrain responses to a specific JSON schema using Pydantic classes for consistent data formatting.
  • The NetworkX library lets you create and manipulate graphs to build KGs from extracted entities and relationships.
  • The Leiden algorithm identifies graph communities by optimizing modularity through iterative node movement and community aggregation.
  • Community detection groups densely connected entities into meaningful clusters for downstream summarization.
  • Community summaries are high-level overviews of entity groups that improve global search quality in GraphRAG systems.
  • Global search creates intermediate answers for each community summary and then combines them into a final response.
  • Local search combines KG entities with document embeddings for hybrid retrieval.
  • Microsoft’s open-source GraphRAG supports only OpenAI models but includes complete indexing and query workflows.
  • RAG evaluation calls for specialized metrics such as context precision, context recall, faithfulness, and answer relevance rather than traditional NLP metrics.
  • Agentic RAG systems pair autonomous agents with retrieval to perform multistep information gathering and reasoning.
  • smolagents’ CodeAgent can autonomously choose the right tools and search strategy for a query.
  • The BM25 algorithm ranks documents for keyword-based retrieval using term frequency, inverse document frequency, and document length.
  • Hybrid search combines BM25 keyword retrieval with semantic similarity search to improve retrieval.
  • LangChain’s EnsembleRetriever combines results from multiple retrievers, using configurable weights for different search methods.
  • Custom retriever classes extend LangChain’s BaseRetriever to implement domain-specific search.
  • Memory management systems track short-term conversation history and long-term interactions across sessions.
  • Memoripy stores memory as a graph, extracting concepts, generating embeddings, and using spreading activation to retrieve relevant items.
  • Decay and reinforcement mechanisms strengthen frequently accessed memories while degrading unused interactions over time.