Build a RAG AI Agent with ByteChef and MariaDB Vector

On this page
TL;DR: MariaDB 11.7+ stores embeddings in a native
VECTORcolumn and searches them with an HNSWVECTOR INDEX, so one database you already run can hold your knowledge base, your chat history and your business data.In this tutorial you run MariaDB 11.8 next to ByteChef, build an ingestion workflow that loads a document into MariaDB Vector, check the result with plain SQL, and test retrieval with the Search Documents action. Then you build a chat AI Agent that answers from MariaDB Vector through Question Answer RAG and keeps each conversation in MariaDB through JDBC Chat Memory.
Along the way you'll meet the one setting that decides whether searches use the vector index or scan the whole table: the index's distance function must match the connection's.
Most RAG tutorials start with "first, sign up for a vector database". That's one more service to provision, secure, back up and pay for, and one more place where your data lives.
If your team already runs MariaDB, you can skip that step. Since MariaDB 11.7, vectors are a native data type: a VECTOR(n) column, VEC_DISTANCE_COSINE() and VEC_DISTANCE_EUCLIDEAN() functions, and a VECTOR INDEX built on a modified HNSW algorithm. MariaDB 11.8 LTS is the first long-term-support release with all of this included.
ByteChef supports it out of the box. The MariaDB Vector Store component is built on Spring AI's MariaDBVectorStore, and it plugs into everything else ByteChef does: workflow triggers, 200+ integrations, document readers and splitters, and the AI Agent.
This is a long, hands-on post. By the end you'll have:
- MariaDB 11.8 and ByteChef running locally with one
docker compose up. - An ingestion workflow that turns a PDF into chunks with embeddings in a MariaDB table.
- A good understanding of what's actually in that table, checked with plain SQL.
- A chat AI Agent that answers questions from those documents and keeps its memory in the same MariaDB database.
- A way to keep the knowledge base current, and a list of the production settings that matter.
The SQL in this post was run on a real MariaDB 11.8 server, and the output shown was copied from it. The component names, parameters and defaults come from the ByteChef source code.
What You'll Build

There are two workflows, and they share one MariaDB database:
- Workflow 1, Ingest. A trigger starts the run. An HTTP Client step downloads a document. The MariaDB Vector Store Load Documents action reads it with a Document Reader, splits it with the Token Text Splitter, embeds each chunk with an Embedding model, and writes one row per chunk into the
vector_storetable. - Workflow 2, Ask. The Chat trigger gives you a hosted chat page. Each message goes to an AI Agent. The agent's Question Answer RAG element embeds the question, runs a similarity search against the same
vector_storetable, and adds the best chunks to the prompt. Its JDBC Chat Memory element stores the conversation in two more MariaDB tables,AI_SESSIONandAI_SESSION_EVENT.
The sample scenario is an employee handbook assistant: HR publishes a handbook PDF, and employees ask things like "How many days do I have to submit expenses?" You can swap the handbook for product docs, runbooks, contracts or support macros. The steps stay the same.
Why MariaDB for this?
- One database, not two. The vectors sit next to the data they describe. You can join chunks to your own tables, filter by tenant with a foreign key, and back everything up with the tools you already use.
- Plain SQL is the debugger. When retrieval returns something odd, you don't need a vendor console.
SELECT ... ORDER BY VEC_DISTANCE_COSINE(...)shows you exactly what the agent saw. - Transactions and permissions you already trust. Vector rows are InnoDB rows. The same users, grants, replication and auditing apply.
- Open source. MariaDB Server is GPLv2 and ByteChef is open source too, so you can self-host the whole stack.
Prerequisites
- Docker with Docker Compose v2.
- An OpenAI API key for embeddings and the chat model. (Prefer to stay fully local? See Running fully local with Ollama below.)
- A document to index. Any PDF, Word, Markdown, HTML or text file works. This post uses
acme-employee-handbook.pdf, a short fictional employee handbook made for this tutorial. The workflows download it straight from this blog, so you can follow along without a document of your own. - Optional: the
mariadbcommand-line client. You can also run every SQL snippet withdocker compose exec mariadb mariadb ....
You don't need to write any Java. Everything in ByteChef is configured in the visual editor. The post also shows the workflow JSON so you can see exactly what's configured, and every workflow is available as a download ready to import (see Downloads).
Step 1: Run MariaDB 11.8 and ByteChef
Create an empty folder and save this as docker-compose.yml (or download it):
services:
postgres:
image: postgres:16-alpine
environment:
POSTGRES_DB: bytechef
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
volumes:
- bytechef_db:/var/lib/postgresql/data
mariadb:
image: mariadb:11.8
# Make every VECTOR INDEX created without an explicit DISTANCE use cosine,
# so it matches the Cosine distance type of the ByteChef connection.
command: ["--mhnsw-default-distance=cosine"]
environment:
MARIADB_ROOT_PASSWORD: root
MARIADB_DATABASE: knowledge
MARIADB_USER: bytechef
MARIADB_PASSWORD: bytechef
ports:
- "3307:3306"
volumes:
- mariadb_data:/var/lib/mysql
healthcheck:
test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"]
interval: 10s
timeout: 5s
retries: 10
bytechef:
image: docker.bytechef.io/bytechef/bytechef:latest
depends_on:
postgres:
condition: service_started
mariadb:
condition: service_healthy
environment:
BYTECHEF_DATASOURCE_URL: jdbc:postgresql://postgres:5432/bytechef
BYTECHEF_DATASOURCE_USERNAME: postgres
BYTECHEF_DATASOURCE_PASSWORD: postgres
BYTECHEF_SECURITY_REMEMBER_ME_KEY: change-me-to-a-long-random-string
volumes:
- ~/.bytechef:/root/.bytechef
ports:
- "8080:8080"
volumes:
bytechef_db:
mariadb_data:Start it:
docker compose up -dA few things worth knowing about this file:
- Two databases, two jobs. PostgreSQL is ByteChef's own application database: workflows, connections, execution history. MariaDB is your database: the knowledge base and the agent's memory. ByteChef talks to MariaDB only through the connections you create in Step 3.
--mhnsw-default-distance=cosineis the most important line here. When ByteChef (through Spring AI) creates the vector table for you, it declaresVECTOR INDEX (embedding)without a distance function. MariaDB then uses the server default, which is Euclidean. The ByteChef connection searches with Cosine by default. If the two don't match, MariaDB can't use the index and scans every row instead. This flag changes the server default to cosine so they match. Under the Hood shows theEXPLAINoutput for both cases.- Port 3307 on the host avoids clashing with a local MySQL or MariaDB already on 3306. Inside the Docker network, ByteChef reaches MariaDB at
mariadb:3306. - The healthcheck uses
healthcheck.sh, which ships with the official MariaDB image. ByteChef starts only after InnoDB is ready.
Check that MariaDB is up and has vector support:
docker compose exec mariadb mariadb -ubytechef -pbytechef knowledge \
-e "SELECT VERSION(); SHOW VARIABLES LIKE 'mhnsw%';"VERSION()
11.8.9-MariaDB-ubu2404
Variable_name Value
mhnsw_default_distance cosine
mhnsw_default_m 6
mhnsw_ef_search 20
mhnsw_max_cache_size 16777216The mhnsw_* variables control MariaDB's HNSW vector index. We'll return to mhnsw_ef_search and mhnsw_max_cache_size in the production section.
Now open http://localhost:8080, create your account, and you're in the ByteChef workspace. Create a project called Handbook Assistant. Both workflows will live there.
Step 2: Decide Who Creates the Vector Table
The MariaDB Vector Store needs one table. You have two options, and it's worth choosing on purpose.
Option A: Let ByteChef create it (fastest)
Turn on Initialize Schema in the connection (Step 3). The first time a workflow uses the connection, Spring AI runs:
CREATE TABLE IF NOT EXISTS vector_store (
id UUID NOT NULL DEFAULT uuid() PRIMARY KEY,
content TEXT,
metadata JSON,
embedding VECTOR(1536) NOT NULL,
VECTOR INDEX vector_store_embedding_idx (embedding)
) ENGINE=InnoDBThis needs the CREATE privilege, and the index distance comes from mhnsw_default_distance. That's why the compose file sets it.
Option B: Create it yourself (recommended for production)
Create the table up front, set the index distance explicitly, and give ByteChef's user only the privileges it needs:
CREATE TABLE vector_store (
id UUID NOT NULL DEFAULT uuid() PRIMARY KEY,
content TEXT,
metadata JSON,
embedding VECTOR(1536) NOT NULL,
VECTOR INDEX vector_store_embedding_idx (embedding) M=16 DISTANCE=cosine
) ENGINE=InnoDB;
-- ByteChef only needs to read, write and delete rows
GRANT SELECT, INSERT, UPDATE, DELETE ON knowledge.vector_store TO 'bytechef'@'%';The mariadb-setup.sql download does all of this in one go. It creates this table, a 768-dimension table for the Ollama variant, and the two chat memory tables from Step 7. It also creates two least-privilege users: bytechef_ingest for the ingestion workflows and bytechef_agent for the chat agent. Run it as root, and change the passwords at the bottom first:
docker compose exec -T mariadb mariadb -uroot -proot < mariadb-setup.sqlThe script only uses IF NOT EXISTS, so running it twice is safe. For the rest of this tutorial, keep using the bytechef user from the compose file: Docker gives it full rights on the knowledge database, so it works for both options. The two extra users are there for when you move to production and want ingestion and the agent on separate, narrower accounts.
Then leave Initialize Schema off. Here's why this is the better default:
DISTANCE=cosineis part of the table definition. It doesn't depend on a server flag that someone might remove later.M=16gives each node in the HNSW graph more neighbors than the default of 6. That improves recall on larger collections, at the cost of a bigger index and slower inserts. The range is 3-200.- Least privilege. The ByteChef user can't create or drop tables.
- You control the dimension.
VECTOR(1536)must match your embedding model. The table below lists common values.
| Embedding model | Provider | Dimensions | Column type |
|---|---|---|---|
text-embedding-3-small | OpenAI | 1536 | VECTOR(1536) |
text-embedding-3-large | OpenAI | 3072 | VECTOR(3072) |
text-embedding-ada-002 | OpenAI | 1536 | VECTOR(1536) |
nomic-embed-text | Ollama | 768 | VECTOR(768) |
mxbai-embed-large | Ollama | 1024 | VECTOR(1024) |
One table per embedding model. Vectors from different models live in different "spaces", and comparing them gives meaningless distances. If you switch models, create a new table (for example
vector_store_te3_large), re-ingest, and point the connection at the new table. Don't mix models in one table.
Whichever option you pick, here is the table's anatomy:
id: a UUID per chunk. Spring AI generates it, and inserts useON DUPLICATE KEY UPDATE, so re-sending the same ID updates the row instead of duplicating it.content: the chunk text. This is what the agent will eventually read.metadata: a JSON document. ByteChef always addsfilename. You can add your own keys (Step 4), and filters run against them withJSON_VALUE().embedding: the vector itself, stored in MariaDB's compact binary format (4 bytes per dimension, so about 6 KB per row for 1536 dimensions).
Step 3: Create the MariaDB Vector Store Connection
In ByteChef, go to Connections → New Connection, choose MariaDB Vector Store, and fill in the fields:
| Field | Value for this tutorial | What it does |
|---|---|---|
| JDBC URL | jdbc:mariadb://mariadb:3306/knowledge | Where the database is. Use the Docker service name mariadb, not localhost: ByteChef runs in its own container. |
| Username | bytechef | The database user. |
| Password | bytechef | Stored encrypted by ByteChef, never shown in workflow JSON. |
| Table Name | vector_store (default) | The table that holds chunks and embeddings. Use a different name per knowledge base or per embedding model. |
| Schema Name | (empty) | The database (schema) that holds the table. Empty means the one in the JDBC URL. |
| Distance Type | Cosine (default) | The distance function used in searches. Must match the DISTANCE of the vector index. |
| Dimensions | 1536 (default) | The vector size. Must match the embedding model and the VECTOR(n) column. |
| Initialize Schema | On for Option A, off for Option B | Whether to run CREATE TABLE IF NOT EXISTS on first use. |
Under the hood, the component opens connections with the official MariaDB Connector/J driver (org.mariadb.jdbc.Driver), so the JDBC URL accepts all the usual Connector/J options. For example, add ?sslMode=verify-full when connecting to a managed MariaDB over TLS.
Cosine or Euclidean? Keep Cosine. It's what OpenAI recommends for its embeddings, the ByteChef default, and the only distance the Similarity Threshold works correctly with (production note 2 explains why).
You'll also need an OpenAI connection (your API key). Create it the same way. The embedding element and the chat model both use it.
Step 4: Build the Ingestion Workflow
Create a new workflow in the Handbook Assistant project and name it Ingest handbook into MariaDB Vector. It has a trigger and two steps.
4.1 The trigger
Start with the Manual trigger, so you can run the workflow with a click while you build it. In Step 9 you'll swap it for a trigger that runs on its own.
4.2 Download the document
Add HTTP Client → GET and configure it:
- URI: the address of your document. To follow along, use the sample handbook:
https://blog.bytechef.io/blogs/mariadb-vector-rag-agent/acme-employee-handbook.pdf. - Response Format: File. This tells ByteChef to save the response as a file object instead of parsing it as JSON.
- Content Type:
application/pdf. - Response Filename:
acme-employee-handbook.pdf. This becomes thefilenamemetadata on every chunk, so choose something readable. - Follow GET Redirect: on, because many file hosts redirect download links.
Your document might not be on a public URL. You can swap this step for any step that produces a file: Google Drive → Download File, Dropbox, OneDrive, Amazon S3, SharePoint, an email attachment, or a file uploaded to a Webhook trigger. The Load action doesn't care where the file came from.
4.3 Load Documents into MariaDB Vector
Add MariaDB Vector Store → Load Documents and choose the MariaDB connection from Step 3. Load Documents is a cluster root: it has slots for sub-elements that plug into it, shown in the editor as connected nodes. It has three slots.
Document Reader (required, one). This element turns the file into text. Pick one that suits the file type:
| Reader | Best for | Notes |
|---|---|---|
| Tika Document Reader | PDF, DOC/DOCX, PPT/PPTX, HTML and the many other formats Apache Tika supports | Extracts all the text into one document. Always pair it with a splitter. |
| Page PDF Document Reader | PDFs where pages matter | Groups parsed pages into documents. Useful when you want page-level metadata. |
| Markdown Document Reader | .md docs and wikis | Respects Markdown structure. |
| JSON Document Reader | JSON exports | Can pick which keys to read. |
| HTML (Jsoup) Document Reader | Web pages | Parses HTML with Jsoup. |
| TXT Document Reader | Plain .txt | No parsing, just text. |
For the handbook PDF, choose Tika Document Reader and set Document to the output of the HTTP step: ${httpClient_1}. In the editor, just drag the HTTP Client output pill into the field.
Document Transformer (optional, many). Transformers run in order, after reading and before embedding. Add the Token Text Splitter:
| Setting | Default | What it means |
|---|---|---|
| Default Chunk Size | 800 | Target chunk size in tokens (CL100K_BASE, the GPT-4 tokenizer). |
| Minimum Chunk Size Characters | 350 | When looking for a clean break (end of a sentence), don't cut before this many characters. |
| Minimum Chunk Length to Embed | 5 | Drop tiny fragments, such as stray page numbers. |
| Maximum Number of Chunks | 10000 | A safety cap per document. |
| Keep Separator | true | Keep newlines, so lists and headings stay readable. |
The defaults suit prose like a handbook. For short FAQ entries, try 300-400 tokens, so each chunk is about one question. For dense legal or technical text, 800-1000 keeps whole clauses together.
You can also add Keyword Metadata Enricher and Summary Metadata Enricher after the splitter. They use an LLM to add excerpt_keywords and section summaries to each chunk's metadata. This costs one model call per chunk, so turn them on when retrieval quality needs it, not by default.
Embedding (required, one). Add OpenAI Embedding, choose your OpenAI connection, and set Model to text-embedding-3-small. This model turns each chunk into a 1536-number vector, which matches the column and the connection's Dimensions.
Finally, set the action's own properties:
- Additional Metadata: key-value pairs merged into every chunk's metadata. Add
source = handbookandversion = 2026-10. You'll usesourceto filter searches andversionto replace old content later. Tag everything you ingest. It costs nothing now, and it's the only reliable way to update or delete content later. - Additional Columns (advanced): column-value pairs written to every row. Use these when you've added your own columns to the table, for example a
tenant_idwith a foreign key to yourtenantstable. Values can be numbers, strings, booleans or dates.
In the editor, the finished workflow is three steps, with the reader, splitter and embedding model attached to Load Documents:

Here's the whole workflow as JSON (download it and import it with Import Workflow, or start from the Load a PDF into MariaDB Vector for RAG template):
{
"label": "Ingest handbook into MariaDB Vector",
"triggers": [
{ "label": "Manual", "name": "trigger_1", "type": "manual/v1/manual" }
],
"tasks": [
{
"label": "Download Document",
"name": "httpClient_1",
"type": "httpClient/v1/get",
"parameters": {
"uri": "https://blog.bytechef.io/blogs/mariadb-vector-rag-agent/acme-employee-handbook.pdf",
"responseType": "BINARY",
"responseContentType": "application/pdf",
"responseFilename": "acme-employee-handbook.pdf",
"followRedirect": true
}
},
{
"label": "Load Documents",
"name": "mariaDbVectorStore_1",
"type": "mariaDbVectorStore/v1/load",
"parameters": {
"additionalMetadata": { "source": "handbook", "version": "2026-10" }
},
"clusterElements": {
"documentReader": {
"name": "documentReader_1",
"type": "documentReader/v1/tika",
"parameters": { "document": "${httpClient_1}" }
},
"documentTransformer": [
{
"name": "documentSplitter_1",
"type": "documentSplitter/v1/tokenTextSplitter",
"parameters": {
"tokenTextSplitter": { "defaultChunkSize": 800, "minChunkSizeChars": 350 }
}
}
],
"embedding": {
"name": "openAi_1",
"type": "openAi/v1/embedding",
"parameters": { "model": "text-embedding-3-small" }
}
}
}
]
}After importing, open each node that needs a connection (Load Documents and OpenAI Embedding) and select yours. Connections are never exported with a workflow, so a JSON file can't leak your credentials.
4.4 Run it
Click Test Workflow. Here's what happens inside the Load step:
- The Tika reader extracts the PDF text into one document, with
filename = acme-employee-handbook.pdfin its metadata. - The splitter cuts it into chunks of about 800 tokens each. Every chunk gets a copy of the metadata.
sourceandversionare merged into each chunk's metadata.- The OpenAI embedding model turns the chunks into vectors. Spring AI sends them in batches, so a 40-page handbook means a few API calls, not hundreds.
- Rows are written to
vector_storein batches of up to 10,000 withINSERT ... ON DUPLICATE KEY UPDATE.
The step returns no output, so check the result in MariaDB.
Step 5: Look at Your Knowledge Base with SQL
This is where MariaDB pays off: you can inspect everything with the SQL you already know. All the queries in this step and in Step 8, plus an EXPLAIN check, an exact-search query for measuring recall and a cleanup query for old chats, are in inspect-queries.sql. Open a client:
docker compose exec mariadb mariadb -ubytechef -pbytechef knowledgeHow many chunks came from each file?
SELECT JSON_VALUE(metadata, '$.filename') AS file,
JSON_VALUE(metadata, '$.version') AS version,
COUNT(*) AS chunks,
ROUND(AVG(CHAR_LENGTH(content))) AS avg_chars
FROM vector_store
GROUP BY file, version;What does a chunk look like?
SELECT id, LEFT(content, 120) AS preview, metadata
FROM vector_store
LIMIT 3\GIs the vector the right size? VEC_ToText() turns the binary vector back into JSON-style text:
SELECT JSON_LENGTH(VEC_ToText(embedding)) AS dimensions
FROM vector_store
LIMIT 1;That should print 1536. If it doesn't, the model and the column disagree. (MariaDB rejects vectors of the wrong size with Incorrect vector value, so you'd usually see that error during the Load step first.)
Is the index there, and which distance does it use?
SHOW CREATE TABLE vector_store\GCreate Table: CREATE TABLE `vector_store` (
`id` uuid NOT NULL DEFAULT uuid(),
`content` text DEFAULT NULL,
`metadata` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`metadata`)),
`embedding` vector(1536) NOT NULL,
PRIMARY KEY (`id`),
VECTOR KEY `vector_store_embedding_idx` (`embedding`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ciTwo details here. First, JSON in MariaDB is an alias for LONGTEXT with a json_valid() check, so metadata is plain text you can index or query. Second, SHOW CREATE TABLE only prints DISTANCE= when it's set explicitly. If you used Option A, the index got its distance from mhnsw_default_distance when it was created.
Run a similarity search by hand. Search needs a query vector, and only the embedding model can produce one. But you can use an existing chunk as the query to find its nearest neighbors. This is a great way to check that "similar" means what you expect:
SET @q = (SELECT embedding FROM vector_store LIMIT 1);
SELECT LEFT(content, 80) AS chunk,
VEC_DISTANCE_COSINE(embedding, @q) AS distance,
1 - VEC_DISTANCE_COSINE(embedding, @q) AS similarity
FROM vector_store
ORDER BY VEC_DISTANCE_COSINE(embedding, @q)
LIMIT 5;The first row is the chunk itself, with distance 0. The next rows should be about the same topic. Cosine distance ranges from 0 (same direction) to 2 (opposite). ByteChef reports score = 1 - distance, so a score of 0.6 means distance 0.4.
Step 6: Test Retrieval with the Search Documents Action
Before you put an agent on top, check retrieval on its own. When an agent gives a bad answer, the cause is usually retrieval, not the model. Testing the two separately saves hours.
Add a scratch workflow (or a temporary step) with MariaDB Vector Store → Search Documents, or import search-knowledge-base-workflow.json, which is preset with the expense question below. Give it the same connection and an Embedding sub-element with the same model you used for ingestion. Then set:
| Property | Example | What it does |
|---|---|---|
| Query | How long do I have to submit an expense report? | The natural-language question. It's embedded with the same model and compared to every chunk. |
| Metadata Filter | [{ "source": "handbook" }] | Optional. Limits results by metadata (see below). |
| Top K | 4 (default) | The maximum number of chunks to return. |
| Similarity Threshold | 0 (default) | The minimum score, 0-1. 0 accepts any result with a positive cosine similarity, 1 only exact matches. |
Click Test. The output is a list of documents. Each one has the chunk text, its metadata (now with a distance key added) and a score. Read the top results and ask yourself: would a person answer the question correctly from these chunks alone? If yes, retrieval is fine and the agent will be too. If not, tune chunking or the filter before going further.
How Metadata Filter works
The filter is a list of groups. Keys inside a group are combined with AND, and groups are combined with OR. So:
[
{ "source": "handbook", "version": "2026-10" },
{ "source": "policies" }
]means (source = handbook AND version = 2026-10) OR (source = policies). ByteChef turns this into a Spring AI filter expression, and Spring AI turns that into SQL with JSON_VALUE:
... AND JSON_VALUE(`metadata`, '$."source"') = 'handbook'
AND JSON_VALUE(`metadata`, '$."version"') = '2026-10' ...Filters are exact matches, and values are escaped properly, so you can safely pass user input such as a department name.
Picking a Similarity Threshold
Scores depend on the model and the content, so measure them on your data instead of guessing. Run 10-20 real questions through Search Documents with the threshold at 0 and write down the scores of good and bad results. With text-embedding-3-small, relevant chunks often score around 0.4-0.7 and unrelated ones below 0.3, but your numbers will differ. Set the threshold just under your lowest good score. A threshold that's too high is worse than none: the agent then sees no context and says "I couldn't find that" for questions it could have answered.
Step 7: Build the AI Agent
Create a second workflow in the same project: Handbook chat agent.
7.1 Chat trigger
Add Chat → New Chat Request with Mode set to Hosted Chat. ByteChef gives the workflow a ready-made chat page. Each message starts a run with two outputs you'll use: message (what the user typed) and conversationId (stable across one chat session).
Choose Embedded Chat instead if you want to put the chat in your own app. The workflow stays the same.
7.2 AI Agent
Add AI Agent → Chat (stream), so answers stream token by token. Set:
- Prompt:
${trigger_1.message}. - System Prompt: this is where you set the agent's behavior. For a RAG agent, the most important instruction is what to do when the context doesn't contain the answer:
You are the Acme employee handbook assistant. Answer only from the handbook
context you are given. If the context does not contain the answer, say you
could not find it in the handbook and suggest asking HR. Quote the relevant
policy name when you can, keep answers under 120 words, and never invent
numbers, dates or amounts.Keep that refusal instruction. When retrieval finds nothing, Question Answer RAG's own prompt template tells the model to fall back on its own knowledge rather than refuse, so the system prompt is the only thing that makes the agent say "I couldn't find that".
The AI Agent has five cluster element slots: Model, RAG, Memory, Tools and Guardrails. This tutorial fills three of them.
7.3 Model
Add OpenAI Model to the Model slot. Choose your OpenAI connection and a model such as gpt-5-mini. A small, fast model is usually enough for RAG, because the retrieved context does most of the work. You can swap in Anthropic, Gemini, Mistral, Amazon Bedrock, Azure OpenAI or a local Ollama model without touching the rest of the agent.
7.4 RAG: Question Answer RAG on top of MariaDB Vector
Add Question Answer RAG to the RAG slot. It has one slot of its own, Vector Store. Put MariaDB VectorStore there, select the MariaDB connection, and give it an Embedding element with the same model as ingestion (text-embedding-3-small).
Settings on Question Answer RAG:
- Top K:
5. A handbook answer often spans two neighboring chunks, so retrieve a few more than you strictly need. - Similarity Threshold: the value you measured in Step 6, for example
0.3. - Filter Expression (optional): a Spring AI filter expression string, for example
source == 'handbook'. This lets one table serve several agents.
Here's what happens on each message: the question is embedded, the k closest chunks above the threshold are fetched from MariaDB, and they're added to the user message as context before the model sees it. The model never queries the database itself. It only sees the chunks retrieval picked. That's why Step 6 matters so much.
7.5 Chat memory in MariaDB
Without memory, every message is a fresh start, and "what about for contractors?" means nothing. Add JDBC Chat Memory to the Memory slot:
- Conversation ID:
${trigger_1.conversationId}, so each chat session has its own history. - Compaction Strategy:
Turn window (by turns)with Max turns10. This keeps the last 10 turns and archives older ones, which keeps prompts small and costs predictable. Other options are a sliding window by events, a token count limit, and recursive LLM summarization.
JDBC Chat Memory needs a Data Source sub-element. Add MySQL → Data Source and create a MySQL connection that points at your MariaDB:
| Field | Value |
|---|---|
| Host | mariadb |
| Port | 3306 |
| Database | knowledge |
| Username / Password | bytechef / bytechef |
Why MySQL? ByteChef doesn't have a separate MariaDB data source component. MariaDB speaks the MySQL protocol, and the chat memory component detects the server type and uses the MySQL/MariaDB schema either way. Every time the agent starts, it runs CREATE TABLE IF NOT EXISTS for two tables in knowledge, so its user needs CREATE and REFERENCES on them, even after they exist. If you ran mariadb-setup.sql in Step 2, the tables and those grants are already there:
AI_SESSION: one row per conversation, with its user, timestamps and an event version counter.AI_SESSION_EVENT: one row per message (user, assistant or tool), ordered byseq, linked to its session with a foreign key andON DELETE CASCADE. Compaction marks old rowsarchivedinstead of deleting them.
So the knowledge base and the conversation history now sit side by side in the same MariaDB database.
7.6 The complete agent
Here's the agent in the editor. The model, memory and RAG elements hang off the AI Agent, and the vector store and its embedding model sit under Question Answer RAG:

{
"label": "Handbook chat agent",
"triggers": [
{
"name": "trigger_1",
"type": "chat/v1/newChatRequest",
"parameters": { "mode": 1 }
}
],
"tasks": [
{
"label": "AI Agent",
"name": "aiAgent_1",
"type": "aiAgent/v1/streamChat",
"parameters": {
"format": "SIMPLE",
"systemPrompt": "You are the Acme employee handbook assistant. ...",
"userPrompt": "${trigger_1.message}"
},
"clusterElements": {
"model": {
"name": "openAi_1",
"type": "openAi/v1/model",
"parameters": { "model": "gpt-5-mini" }
},
"rag": {
"name": "questionAnswerRag_1",
"type": "questionAnswerRag/v1/rag",
"parameters": { "topK": 5, "similarityThreshold": 0.3 },
"clusterElements": {
"vectorStore": {
"name": "mariaDbVectorStore_1",
"type": "mariaDbVectorStore/v1/vectorStore",
"clusterElements": {
"embedding": {
"name": "openAi_2",
"type": "openAi/v1/embedding",
"parameters": { "model": "text-embedding-3-small" }
}
}
}
}
},
"chatMemory": {
"name": "jdbcChatMemory_1",
"type": "jdbcChatMemory/v2/chatMemory",
"parameters": {
"conversationId": "${trigger_1.conversationId}",
"compactionStrategy": "TURN_WINDOW",
"maxTurns": 10
},
"clusterElements": {
"dataSource": { "name": "mysql_1", "type": "mysql/v1/dataSource" }
}
}
}
}
]
}The full version is ready to download, and it's also a template: Answer questions from MariaDB Vector with a RAG AI agent and MariaDB chat memory. As with ingestion, select connections on the nodes after you import it.
The nesting mirrors the editor: the agent contains a RAG element, which contains a vector store, which contains an embedding model. Each element is configured and swapped on its own.
Step 8: Chat with It, Then Look Under the Hood
Open the chat page from the trigger (or use the Test chat in the editor) and ask:
- "How many days do I have to submit an expense report?" The answer should quote the policy.
- "And if I'm a contractor?" This follow-up only works because of chat memory. "And if" refers to the previous question.
- "What's the cafeteria menu on Friday?" If the handbook doesn't cover it, the agent should say so instead of making something up. That's the refusal line in your system prompt at work, helped by the similarity threshold keeping unrelated chunks out.
Now check what happened in MariaDB:
-- Conversations, newest first
SELECT id, user_id, created_at, event_version
FROM AI_SESSION
ORDER BY created_at DESC
LIMIT 5;
-- The messages of one conversation, in order
SELECT seq, message_type, LEFT(message_content, 80) AS message, archived
FROM AI_SESSION_EVENT
WHERE session_id = '<conversation id>'
ORDER BY seq;If an answer was wrong, here's how to debug it: copy the question, paste it into the Search Documents test from Step 6 with the same Top K, threshold and filter, and look at the chunks. Either the right chunk isn't in the results (a retrieval problem: fix chunking, metadata or the threshold) or it is and the model ignored it (a prompt problem: tighten the system prompt). Because everything is in MariaDB, both halves of the investigation are just queries.
Step 9: Keep the Knowledge Base Fresh
Documents change after you load them, and the old chunks stay in the table until you remove them. The MariaDB Vector Store component has two actions for this.
Update Documents first deletes every chunk that matches a Metadata Filter, then loads the new document with the same reader, transformers and embedding as Load. To publish a new handbook version, run Update with:
- Metadata Filter:
[{ "filename": "acme-employee-handbook.pdf" }] - Additional Metadata:
{ "source": "handbook", "version": "2026-11" }
The old chunks go and the new ones arrive in one step. Without that tagging from Step 4, you'd have no reliable way to find the old chunks. (The delete and the load aren't one database transaction, so a run that fails halfway can leave the file missing until the next run.)
Delete Documents removes chunks by metadata filter and loads nothing. Use it when a document is withdrawn at the source. For example, if HR retires a policy PDF, delete [{ "filename": "travel-policy-2024.pdf" }], and the agent stops citing it right away. If you don't plan for this, deleted documents live on in the index forever.
Delete Documents with an empty filter does nothing. That's a deliberate safety net: you can't wipe the table by accident. To start over, run
TRUNCATE TABLE vector_storeyourself.
Two workflows are ready to import for this step:
refresh-handbook-workflow.jsonruns every night at 02:00 UTC. It downloads the handbook again and runs Update Documents filtered on itsfilename. Change theversionin Additional Metadata whenever you publish a new edition.remove-document-workflow.jsonruns Delete Documents for onefilename. Change the filter to the document you want to remove, and run it manually.
You can also replace the Manual trigger of the ingestion workflow with something that runs on its own:
- Google Drive → New File: ingest each new file dropped into a "Handbook" folder. Use Google Drive → Download File with
${trigger_1.id}instead of the HTTP step, and adddriveFileId = ${trigger_1.id}to Additional Metadata, so updates and deletes can target the file exactly. - Schedule → Every Day: re-ingest every night. Combine it with Update Documents so each run replaces instead of duplicating.
- Webhook: let your CMS or document system call ByteChef whenever a page is published.
Under the Hood: the SQL ByteChef Runs
You don't need this section to build the agent. But if you're the person who'll run MariaDB in production, you'll want to know exactly what reaches your database. The component is built on Spring AI's MariaDBVectorStore (Spring AI 2.0), so the queries are predictable.
Insert (Load and Update). Chunks are written in batches:
INSERT INTO vector_store (id, content, metadata, embedding) VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE content = VALUES(content), metadata = VALUES(metadata),
embedding = VALUES(embedding)If you set Additional Columns, ByteChef adds them to the column list and the UPDATE part, with backtick-quoted names.
Search (Search Documents and the RAG element).
SELECT * FROM (
SELECT id, content, metadata,
vec_distance_cosine(embedding, ?) AS distance
FROM vector_store
) AS t
WHERE distance < ? -- 1 - similarity threshold
AND JSON_VALUE(`metadata`, '$."source"') = '...' -- only if you set a filter
ORDER BY distance ASC
LIMIT ? -- Top KEach result's score is 1 - distance, and the raw distance is added to its metadata.
Does that query use the vector index? That depends on whether the index's distance matches the query's distance. Here's EXPLAIN on MariaDB 11.8 for the Spring AI query with Cosine, against two tables:
-- Index created without DISTANCE on a default server (euclidean index):
type: ALL key: NULL Extra: Using where; Using filesort
-- Index created with DISTANCE=cosine, or with --mhnsw-default-distance=cosine:
type: index key: vector_store_embedding_idx Extra: Using whereThe first one compares the question against every row and sorts them all. That's exact, and fine for a few thousand chunks, but it slows down as the table grows. The second walks the HNSW graph and reads only a small part of the table. With a matching index, the metadata filter doesn't stop the index from being used: MariaDB finds nearest neighbors through the index and applies the JSON_VALUE condition to them.
So the rule is: the distance type in the ByteChef connection must match the DISTANCE of the vector index. Cosine and cosine (recommended), or Euclidean and Euclidean.
Delete. Delete Documents and the first half of Update run DELETE FROM vector_store WHERE <filter>, using the same JSON_VALUE conditions.
Running MariaDB Vector in Production: 10 Settings That Matter
Moving from your laptop to production? These are the settings and decisions that matter, roughly in order of impact.
1. Match the index distance to the connection. Covered above, and worth repeating, because the failure is silent: everything works, it just gets slower as the table grows. Check with EXPLAIN on the query from the previous section, and look for your vector index in the key column.
2. Don't use Euclidean with the Similarity Threshold. ByteChef turns the threshold into distance < 1 - threshold for both distance types. Cosine distance runs from 0 to 2, so a threshold of 0 drops only chunks with a cosine similarity of 0 or less, which for text embeddings is almost nothing. Euclidean distance between normalized vectors (like OpenAI's) is sqrt(2 * (1 - cosine_similarity)), so distance < 1 means cosine similarity above 0.5. With Euclidean, a threshold of 0, which says "accept everything", quietly filters out a lot of useful chunks. Use Cosine.
3. Size the index cache. MariaDB keeps the HNSW graph in a cache limited by mhnsw_max_cache_size (16 MB by default). A 1536-dimension index takes up noticeably more than that once you have tens of thousands of chunks. When the graph doesn't fit, searches read from disk. Raise the value in your server config, for example mhnsw_max_cache_size = 1G, based on your table size and available RAM.
4. Tune recall versus speed. HNSW is approximate. mhnsw_ef_search (default 20) is how many candidates a search considers. Higher means better recall and slower queries. Note that MariaDB uses max(ef_search, LIMIT), so a Top K above 20 automatically searches more widely. M (set per index, 3-200) trades index size and insert speed for recall. Measure with your own questions: compare indexed results against an exact scan (IGNORE INDEX) and count how often the right chunk is missing.
5. Selective filters and Top K. With an index, MariaDB finds neighbors first and filters them afterwards. If a filter matches only a small part of the table (one tenant in a thousand), the nearest neighbors may all belong to other tenants, and you'll get fewer than Top K results. For strict per-tenant isolation at scale, use a table per tenant (one connection or Table Name per tenant) or raise mhnsw_ef_search.
6. Use one table per knowledge base and embedding model. Different models give incompatible vectors. Separate tables also let you rebuild one knowledge base without touching the others, and give each agent its own Table Name.
7. Least privilege. Ingestion needs SELECT, INSERT, UPDATE, DELETE on the vector table. A search-only agent needs just SELECT. Chat memory needs DML plus CREATE and REFERENCES on AI_SESSION and AI_SESSION_EVENT, because the agent runs CREATE TABLE IF NOT EXISTS for them every time it starts. Create tables with an admin account and leave Initialize Schema off. Consider separate MariaDB users for the ingestion connection and the agent's connection.
8. Embedding costs. Embeddings are cheap, but re-ingesting a large library every night isn't free. Use metadata (a version or a content hash) to re-embed only files that changed, and keep enrichers off unless they clearly improve retrieval.
9. Backups include your knowledge. Vector rows are InnoDB rows, so mariadb-dump, mariadb-backup, replication and point-in-time recovery all work as usual. That's a real advantage over a separate vector service. Just remember that a backup of the vectors is only useful together with the name of the model that made them, so record the model in metadata or in the table name.
10. Keep chat history under control. AI_SESSION_EVENT grows with every message. Compaction controls what the model sees, not what's stored. Archive or delete old sessions on a schedule (for example, sessions older than 90 days). Thanks to the ON DELETE CASCADE foreign key, deleting from AI_SESSION removes their events too.
Running fully local with Ollama
Want no data to leave your machine? Swap both OpenAI elements for Ollama. Everything you need is in the downloads:
-
Start Ollama next to the rest.
docker-compose.ollama.ymladds anollamaservice and a one-offollama-pulljob that downloadsnomic-embed-text(embeddings) andllama3.1(chat). Start both files together:docker compose -f docker-compose.yml -f docker-compose.ollama.yml up -dThe first start downloads about 5 GB of models.
docker compose logs -f ollama-pullshows the progress. -
Create the 768-dimension table.
nomic-embed-textmakes 768-number vectors, so it needs its own table.mariadb-setup.sqlalready createsvector_store_nomicasVECTOR(768)with a cosine index. -
Create the connections. An Ollama connection with URL
http://ollama:11434, and a second MariaDB Vector Store connection with Table Namevector_store_nomicand Dimensions768. -
Import the local workflows.
ingest-handbook-workflow-ollama.jsonandhandbook-chat-agent-workflow-ollama.jsonare the same workflows with Ollama Embedding (nomic-embed-text) in both the Load action and the RAG vector store, and Ollama Model (llama3.1) in the agent. Select the Ollama andvector_store_nomicconnections after importing.
Everything else stays the same, and the whole stack runs offline: documents, vectors, memory and the model.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
Failed to initialize MariaDB vector store | Wrong JDBC URL, credentials or database, or MariaDB older than 11.7. | Check that the URL uses the service name (mariadb) from inside Docker, check the credentials, and run SELECT VERSION(). |
Table 'knowledge.vector_store' doesn't exist | Initialize Schema is off and nobody created the table. | Turn on Initialize Schema, or create the table yourself (Step 2, Option B). |
Incorrect vector value ... for column embedding during Load | The model's dimension doesn't match VECTOR(n). | Align the model, the Dimensions field and the column type (see the table in Step 2). |
| Search returns nothing | Similarity Threshold too high, a filter value that doesn't match, or a different embedding model at search time. | Set the threshold to 0, remove the filter, and check that both sides use the same model. Then add things back one at a time. |
| Search gets slower as data grows | The index distance doesn't match the connection, so every search scans the table. | Run EXPLAIN on the search. Recreate the index with DISTANCE=cosine (or start the server with --mhnsw-default-distance=cosine before the table is created). |
| Fewer results than Top K with a filter | Index-first search plus a selective filter. | Raise mhnsw_ef_search, or split very selective data into its own table. |
| Agent ignores the handbook | Retrieval found nothing above the threshold, or the system prompt doesn't require using the context. | Test the exact question in Search Documents (Step 6), then tighten the system prompt. |
| Agent forgets the previous message | Conversation ID isn't mapped, so every message gets a new session. | Set Conversation ID to ${trigger_1.conversationId}. |
| Duplicate chunks after re-running ingestion | Load always adds rows, and new chunks get new IDs. | Use Update Documents with a filter on filename or your own ID instead of Load. |
Downloads
Everything used in this tutorial, in the order you need it:
| File | What it is | Used in |
|---|---|---|
docker-compose.yml | MariaDB 11.8 (with a cosine default index distance), PostgreSQL and ByteChef | Step 1 |
mariadb-setup.sql | Vector tables (1536 and 768 dimensions, cosine indexes), chat memory tables and least-privilege users | Step 2 |
acme-employee-handbook.pdf | The fictional sample handbook to index | Step 4 |
ingest-handbook-workflow.json | Ingestion workflow: download, read, split, embed, load | Step 4 |
inspect-queries.sql | SQL for checking chunks, vectors, the index and chat history | Steps 5 and 8 |
search-knowledge-base-workflow.json | Search Documents test workflow | Step 6 |
handbook-chat-agent-workflow.json | Chat AI Agent with MariaDB Vector RAG and MariaDB chat memory | Step 7 |
refresh-handbook-workflow.json | Nightly Update Documents run | Step 9 |
remove-document-workflow.json | Delete Documents by filename | Step 9 |
docker-compose.ollama.yml | Adds Ollama and pulls nomic-embed-text and llama3.1 | Fully local variant |
ingest-handbook-workflow-ollama.json | Ingestion with Ollama embeddings into vector_store_nomic | Fully local variant |
handbook-chat-agent-workflow-ollama.json | Chat agent with an Ollama model and embeddings | Fully local variant |
The ingestion workflow and the chat agent are also on the ByteChef template gallery: Load a PDF into MariaDB Vector for RAG and Answer questions from MariaDB Vector with a RAG AI agent and MariaDB chat memory.
Import each workflow with Import Workflow in your project, then select your connections on the nodes that need one: Load, Search, Update and Delete Documents, the embedding elements, the vector store, the model and the data source. Connections are never part of an exported workflow.
Where to Take It Next
- Add tools to the agent. Let it create a Jira ticket for HR when it can't answer, or post a summary to Slack.
- Feed it more sources. Confluence, Notion, Google Drive, SharePoint, or your own MariaDB tables through the MySQL component.
- Expose it in your product. Switch the chat trigger to Embedded Chat, or call the workflow from your app.
- Add Guardrails. Use the agent's Guardrails slot to screen inputs and outputs.
Already running MariaDB? Spin up the compose file above, point the ingestion workflow at a document you care about, and ask your first question in about fifteen minutes. Try it on ByteChef or self-host it from GitHub.
Subscribe to the ByteChef Newsletter
Get the latest guides on complex automation, AI agents, and visual workflow best practices delivered to your inbox.


