Skip to main content

Build a retrieval index

Source on GitHub: the workflows/retrieval-index folder, with its README and its workflow file.

Builds the index a retrieval-augmented generation (RAG) application searches. Each PDF is fetched and split into chunks of text by Docling, all PDFs at the same time; Text Embeddings Inference embeds every chunk; DuckDB stores chunks and vectors in one Parquet file; and a test query is answered from it with cosine similarity, to show the index works.

StepTask definitionCompute
For each PDF: fetch itswaleio/http-requestcpu-4
For each PDF: convert it to chunksswaleio/doclingcpu-4
Serve the embedding model, as a runnerswaleio/tei-servea100-1
Wait for the server, checking every 5 secondsswaleio/http-requestcpu-4
Embed the chunks, 32 per requestswaleio/python-3-13cpu-4
Embed the test queryswaleio/http-requestcpu-4
Write index.parquet, count chunks per documentswaleio/duckdbcpu-4
Find the five chunks closest to the queryswaleio/duckdbcpu-4
Upload the index, when hub_repo is setswaleio/hf-uploadcpu-4

The Compute column gives each step's compute type, the compute its tasks are allocated.

Every step is its own task. The embedding client is a short Python script inside the workflow that uses only the standard library. Docling counts each chunk's tokens with a tokenizer it downloads from the Hugging Face Hub.

Inputs​

InputDefaultDescription
pdf_urlsthree papers from arXivThe PDFs, as a JSON array of URLs.
modelBAAI/bge-small-en-v1.5Embedding model; the query must be embedded with the same one.
querya question about Docling's tablesA question to test the index with; leave double quotes out of it.
hub_repoemptyHugging Face dataset repo to upload the index to, as data/train.parquet.

The upload reads the secret hf_token.

Output​

index.parquet on the workspace, with url, chunk, text and embedding for every chunk. The five closest chunks to the query are in the search task's log.

Run it​

You need the CLI, logged in to your account, and a project to add the workflow to; Getting started sets them up.

  1. Save the file under The workflow file as workflow.yaml, and add it to a project:

    swale workflow create --project-name my-project --file workflow.yaml

    The command prints Workflow created: followed by the workflow's ID.

  2. The workflow reads the secret hf_token. Create it as a project secret, or as an account secret that allows the project, as Use secrets in workflows shows.

  3. Start a run with the workflow's ID:

    swale workflow run start --project-name my-project --workflow-id <workflow-id>

    Each input you leave out takes its default from Inputs, and --input <name>=<value> gives it another value.

Create and manage workflows covers the other ways to add a workflow, Start and manage workflow runs how to follow a run, and View and stream task logs how to read its tasks' logs.

The workflow file​

Workflow definition syntax describes each key in it.

workflow.yaml
name: Build a retrieval index
description: Splits PDFs into text chunks with Docling, embeds them with Text Embeddings Inference, stores them as a Parquet index, and answers a test query.
compute_type: cpu-4

inputs:
pdf_urls:
description: The PDFs to index, as a JSON array of URLs.
default: '["https://arxiv.org/pdf/2408.09869v5", "https://arxiv.org/pdf/2501.17887v1", "https://arxiv.org/pdf/2305.14314v1"]'
model:
description: Hugging Face repo id of the embedding model.
default: BAAI/bge-small-en-v1.5
query:
description: A question to test the index with.
default: How does Docling recognize the structure of tables?
hub_repo:
description: Hugging Face dataset repo to upload the index to, as namespace/name. Leave empty to keep it on the workspace only.
default: ""

entry_point: main

blocks:
main:
tasks:
each_pdf:
name: Chunk each PDF
for_each:
items: ${{inputs.pdf_urls}}
block: chunk_one

serve:
name: Serve the embedding model
uses: swaleio/tei-serve
compute_type: a100-1
terminate_on:
- embed_chunks
- embed_query
args:
model: ${{inputs.model}}

wait_ready:
name: Wait for the server
uses: swaleio/http-request
start_on:
- serve
args:
url: http://${{tasks.serve.ip-address}}:8080/health
retry: "360"
retry_delay: "5"
expected_status: "200"

embed_chunks:
name: Embed the chunks
uses: swaleio/python-3-13
start_on:
- wait_ready
- each_pdf
args:
script: |
import glob, json, os, urllib.request

storage = os.environ["WORKFLOW_STORAGE"]
server = "http://${{tasks.serve.ip-address}}:8080/embed"
chunks = []
for path in sorted(glob.glob(f"{storage}/chunks/*.jsonl")):
with open(path) as f:
chunks += [json.loads(line) for line in f if line.strip()]

def embed(texts):
body = json.dumps({"inputs": texts, "truncate": True}).encode()
request = urllib.request.Request(server, body, {"Content-Type": "application/json"})
with urllib.request.urlopen(request, timeout=300) as response:
return json.load(response)

with open(f"{storage}/chunk-vectors.jsonl", "w") as out:
for start in range(0, len(chunks), 32):
batch = chunks[start:start + 32]
for chunk, vector in zip(batch, embed([c["text"] for c in batch])):
out.write(json.dumps({"document": chunk["filename"], "chunk": chunk["chunk_index"],
"text": chunk["text"], "embedding": vector}) + "\n")
print(f"embedded {len(chunks)} chunks")

embed_query:
name: Embed the test query
uses: swaleio/http-request
start_on:
- wait_ready
args:
url: http://${{tasks.serve.ip-address}}:8080/embed
method: POST
headers: |
Content-Type: application/json
body: '{"inputs": "${{inputs.query}}", "truncate": true}'
expected_status: "200"
response_path: ${{env.WORKFLOW_STORAGE}}/query-vector.json

index:
name: Write the index
uses: swaleio/duckdb
start_on:
- embed_chunks
args:
sql: |
CREATE TABLE sources AS
SELECT unnest(from_json($$${{inputs.pdf_urls}}$$, '["VARCHAR"]')) AS url,
(generate_subscripts(from_json($$${{inputs.pdf_urls}}$$, '["VARCHAR"]'), 1) - 1)::VARCHAR AS document;
CREATE TABLE chunks AS
SELECT s.url, c.chunk, c.text, c.embedding::FLOAT[] AS embedding
FROM read_json('${{env.WORKFLOW_STORAGE}}/chunk-vectors.jsonl',
columns = {'document': 'VARCHAR', 'chunk': 'INTEGER', 'text': 'VARCHAR', 'embedding': 'DOUBLE[]'}) c
JOIN sources s USING (document)
ORDER BY s.url, c.chunk;
COPY chunks TO '${{env.WORKFLOW_STORAGE}}/index.parquet' (FORMAT parquet);
SELECT url, count(*) AS chunks FROM chunks GROUP BY url ORDER BY url;

search:
name: Answer the test query
uses: swaleio/duckdb
start_on:
- index
- embed_query
args:
sql: |
-- The server answers /embed with one vector per input, so the query's is the first.
CREATE TABLE query AS
SELECT json_extract(json, '$[0]')::FLOAT[] AS vector
FROM read_json_objects('${{env.WORKFLOW_STORAGE}}/query-vector.json', format = 'unstructured');
SELECT round(list_cosine_similarity(c.embedding, q.vector), 3) AS similarity,
c.url, c.chunk, left(replace(c.text, chr(10), ' '), 160) AS text
FROM '${{env.WORKFLOW_STORAGE}}/index.parquet' c, query q
ORDER BY similarity DESC LIMIT 5;

publish:
name: Upload when asked
start_on:
- search
if:
condition: ${{inputs.hub_repo}}
true: upload

chunk_one:
tasks:
fetch:
name: Fetch PDF
uses: swaleio/http-request
args:
url: ${{tasks.each_pdf.for_each.item}}
expected_status: "200"
response_path: ${{env.WORKFLOW_STORAGE}}/pdf/${{tasks.each_pdf.for_each.index}}.pdf
chunk:
name: Convert to chunks
uses: swaleio/docling
start_on:
- fetch
args:
source: ${{env.WORKFLOW_STORAGE}}/pdf/${{tasks.each_pdf.for_each.index}}.pdf
output_dir: ${{env.WORKFLOW_STORAGE}}/chunks
to: chunks

upload:
tasks:
upload_index:
name: Upload to the Hugging Face Hub
uses: swaleio/hf-upload
args:
repo: ${{inputs.hub_repo}}
repo_type: dataset
source: ${{env.WORKFLOW_STORAGE}}/index.parquet
path_in_repo: data/train.parquet
token: ${{secrets.hf_token}}

Licenses of the defaults​