> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mka1.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Multilingual retrieval benchmark

> Graph and vector retrieval quality on WebFAQRetrieval in English, Ukrainian, and Urdu.

This benchmark evaluates graph and vector retrieval through the MKA1 API on English, Ukrainian, and Urdu FAQ queries. It uses the official test queries, passages, and relevance judgments from [WebFAQRetrieval](https://huggingface.co/datasets/mteb/WebFAQRetrieval).

## Results

Each mode answered the same 64 test queries against the same 128 passages per language.

| Language | Retrieval mode | nDCG\@10 | Recall\@10 | MRR\@10 | Hit\@1 |
| - | - | -: | -: | -: | -: |
| English | Vector | 1.000 | 100.0% | 1.000 | 100.0% |
| English | Graph | 0.984 | 98.4% | 0.984 | 98.4% |
| Ukrainian | Vector | 0.994 | 100.0% | 0.992 | 98.4% |
| Ukrainian | Graph | 0.994 | 100.0% | 0.992 | 98.4% |
| Urdu | Vector | 0.955 | 100.0% | 0.940 | 90.6% |
| Urdu | Graph | 0.928 | 95.3% | 0.919 | 89.1% |

For Ukrainian, both modes returned the labeled passage in the top ten for all 64 queries and first for 63. In graph mode, the labeled passage received a positive keyword score for 57 queries. Vector retrieval returned every labeled passage in the top ten for English and Urdu. Graph retrieval returned 63 of 64 in English and 61 of 64 in Urdu.

* **nDCG\@10** gives more credit to results near the top. With one labeled answer per query, the score is `1 / log2(rank + 1)`.
* **Recall\@10** is the share of queries that return the labeled passage in the top ten.
* **MRR\@10** averages the reciprocal rank of the labeled passage across queries.
* **Hit\@1** is the share of queries that put the labeled passage first.

A missing labeled passage contributes zero to each metric. The workload also counts a search as a miss if the API still returns a service error after retries.

## Dataset and method

The workload selects 64 queries per language by sorting official test query IDs by a salted SHA-256 hash. Each index includes the 64 judged answer passages and 64 distractors. It selects one unique distractor per query from the judged answers to other test queries in the same language, using inverse-document-frequency-weighted keyword overlap and adjusting for passage length.

The workload normalizes Unicode composition and whitespace before uploading each passage as a text file. It verifies that each file produces exactly one chunk, with a 4,096-token limit and zero overlap. Searches request ten results with a minimum score of zero and query rewriting disabled. The workload scores the returned file IDs against the published relevance judgments. [Files](https://docs.mka1.com/docs/files.md) · [Vector stores](https://docs.mka1.com/docs/vector-stores.md)

Both modes used `meetkai:embedding` with 4,096 dimensions. The graph stores used `openai:gpt-4.1-mini` for extraction. The benchmark set the reranker to `auto`, which selects the ranker in the serving environment. Every search returned a reranker score. [Graph retrieval](https://docs.mka1.com/docs/graph-retrieval.md)

These scores describe retrieval on the fixed WebFAQRetrieval subset above. The full corpus includes many more candidate passages. WebFAQRetrieval labels one relevant passage per query, so a different passage can answer the question and still receive zero credit. Compare retrieval modes within each language.

## Reproduce the benchmark

1. Set `MKA1_API_KEY` and `MKA1_BASE_URL` in your environment. The base URL must end in `/api/v1/llm`. Use an account with access to the embedding and extraction models listed above.
2. Copy the Python workload into `retrieval-benchmark.py`.
3. Run the commands below to download the pinned WebFAQRetrieval data and execute the workload with [uv](https://docs.astral.sh/uv/). The English corpus download is about 1 GB. The workload creates temporary stores, scores them, and requests deletion of its stores and uploads on exit. Ingestion and search use your account's model quota.

```bash theme={null}
DATA_DIR=$(mktemp -d)
BASE=https://huggingface.co/datasets/mteb/WebFAQRetrieval/resolve/f64f483ad0f31d2e78209d524c14a4a867965959

for language in eng ukr urd; do
  for part in queries qrels; do
    curl -fLsS -o "$DATA_DIR/$language-$part.parquet" \
      "$BASE/$language-$part/test-00000-of-00001.parquet" || exit 1
  done
done

for shard in 0 1 2 3; do
  curl -fLsS -o "$DATA_DIR/eng-corpus-$shard.parquet" \
    "$BASE/eng-corpus/test-0000$shard-of-00004.parquet" || exit 1
done

for language in ukr urd; do
  curl -fLsS -o "$DATA_DIR/$language-corpus-0.parquet" \
    "$BASE/$language-corpus/test-00000-of-00001.parquet" || exit 1
done

uv run retrieval-benchmark.py \
  --api-base-url "$MKA1_BASE_URL" \
  --data-dir "$DATA_DIR" \
  --output "$DATA_DIR/results.json"
```

> [accordion] Python benchmark workload
>
> ```python retrieval-benchmark.py theme={null}
> # /// script
> # requires-python = ">=3.12,<3.13"
> # dependencies = ["pyarrow==26.0.1"]
> # ///
>
> """Measure MKA1 API retrieval against official WebFAQRetrieval test labels."""
>
> import argparse
> from collections import Counter
> from concurrent.futures import ThreadPoolExecutor, as_completed
> import hashlib
> import json
> import math
> import os
> from pathlib import Path
> import re
> from statistics import mean, median
> import time
> import unicodedata
> from urllib.error import HTTPError, URLError
> from urllib.parse import urlsplit
> from urllib.request import HTTPRedirectHandler, Request, build_opener
> import uuid
>
> import pyarrow as pa
> import pyarrow.compute as pc
> import pyarrow.parquet as parquet
>
> REVISION = "f64f483ad0f31d2e78209d524c14a4a867965959"
> LANGUAGES = ("eng", "ukr", "urd")
> TEST_QUERIES = 64
> RESULT_COUNT = 10
> SALT = "mka1-webfaq-retrieval-v1"
> TOKEN = re.compile(r"[^\W_]+")
>
>
> CHUNKING = {"type": "static", "static": {"max_chunk_size_tokens": 4096, "chunk_overlap_tokens": 0}}
> KEY_NAME = "MKA1_API_KEY"
> RANKING = {"ranker": "auto", "score_threshold": 0}
> INGEST_BATCH_SIZE = {"vector": 8, "graph": 6}
>
>
> class NoRedirect(HTTPRedirectHandler):
>     def redirect_request(self, req, fp, code, msg, headers, newurl):
>         return None
>
>
> class BenchmarkAPI:
>     def __init__(self, base_url, key):
>         self.base_url = base_url
>         self.key = key
>         self.opener = build_opener(NoRedirect())
>
>     def call(self, method, path, *, payload=None, data=None, content_type=None, retry=False):
>         if payload is not None:
>             data = json.dumps(payload).encode()
>             content_type = "application/json"
>         headers = {"Authorization": f"Bearer {self.key}"}
>         if content_type:
>             headers["Content-Type"] = content_type
>         request = Request(f"{self.base_url}/{path}", data=data, headers=headers, method=method)
>         for attempt in range(4):
>             try:
>                 with self.opener.open(request, timeout=90) as response:
>                     return json.load(response)
>             except HTTPError as error:
>                 message = error.read().decode(errors="replace").replace(self.key, "[redacted]")
>                 transient = error.code in (429, 500, 502, 503, 504) or (
>                     error.code == 400 and "feature_unavailable" in message
>                 )
>                 if not retry or attempt == 3 or not transient:
>                     raise RuntimeError(f"{method} {path} returned {error.code}: {message[:350]}") from None
>             except (TimeoutError, URLError):
>                 if not retry or attempt == 3:
>                     raise
>             time.sleep(2 ** (attempt + 1))
>
>     def upload(self, filename, text):
>         boundary = uuid.uuid4().hex
>         body = (
>             f'--{boundary}\r\nContent-Disposition: form-data; name="purpose"\r\n\r\nassistants\r\n'
>             f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="{filename}"\r\n'
>             f"Content-Type: text/plain\r\n\r\n{text}\r\n--{boundary}--\r\n"
>         ).encode()
>         uploaded = self.call("POST", "files", data=body, content_type=f"multipart/form-data; boundary={boundary}")
>         return uploaded["id"]
>
>     def create_store(self, name, mode, extraction_model, embedding_model=None):
>         payload = {
>             "name": name,
>             "retrieval_mode": mode,
>             "expires_after": {"anchor": "last_active_at", "days": 1},
>         }
>         if mode == "graph" and extraction_model:
>             payload["extraction_model"] = extraction_model
>         if embedding_model:
>             payload["embedding_model"] = embedding_model
>         return self.call("POST", "vector_stores", payload=payload)
>
>     def await_batch(self, path, file_ids):
>         batch = self.call("POST", f"{path}/file_batches", payload={
>             "file_ids": file_ids, "chunking_strategy": CHUNKING,
>         })
>         batch_path = f"{path}/file_batches/{batch['id']}"
>         deadline = time.monotonic() + 5 * 60
>         next_update = time.monotonic() + 45
>         while time.monotonic() < deadline:
>             counts = self.call("GET", batch_path, retry=True)["file_counts"]
>             if counts["completed"] == len(file_ids):
>                 return []
>             if counts["completed"] + counts["failed"] + counts["cancelled"] == len(file_ids):
>                 rows = self.call("GET", f"{batch_path}/files?limit=100", retry=True)["data"]
>                 return [row for row in rows if row["status"] != "completed"]
>             if time.monotonic() >= next_update:
>                 print(f"Waiting for {counts['in_progress']} ingests in {batch_path}", flush=True)
>                 next_update = time.monotonic() + 45
>             time.sleep(3)
>         raise TimeoutError(f"{batch_path} did not finish within five minutes")
>
>     def ingest(self, store, file_ids, batch_size=None):
>         path = f"vector_stores/{store['id']}"
>         batch_size = batch_size or INGEST_BATCH_SIZE[store["retrieval_mode"]]
>         for offset in range(0, len(file_ids), batch_size):
>             batch_files = file_ids[offset:offset + batch_size]
>             failures = self.await_batch(path, batch_files)
>             for row in failures:
>                 error = row.get("last_error") or {}
>                 if error.get("code") != "server_error":
>                     raise RuntimeError(f"{store['name']} ingestion failed: {error}")
>                 print(f"{store['name']}: retrying a failed ingestion", flush=True)
>                 self.call("DELETE", f"{path}/files/{row['id']}")
>                 repeated_failures = self.await_batch(path, [row["id"]])
>                 if repeated_failures:
>                     raise RuntimeError(f"{store['name']} retry failed: {repeated_failures[0].get('last_error')}")
>             completed = offset + len(batch_files)
>             if completed % 24 == 0 or completed == len(file_ids):
>                 print(f"{store['name']}: indexed {completed}/{len(file_ids)}", flush=True)
>         files = []
>         cursor = ""
>         while True:
>             page = self.call("GET", f"{path}/files?limit=100{cursor}", retry=True)
>             files.extend(page["data"])
>             if not page["has_more"]:
>                 break
>             if not page["data"]:
>                 raise RuntimeError(f"Empty file page for {store['name']}")
>             cursor = f"&after={page['data'][-1]['id']}"
>         if {row["id"] for row in files} != set(file_ids) or any(
>             row["chunk_count"] != 1 or row["status"] != "completed" for row in files
>         ):
>             raise RuntimeError(f"{store['name']} must index every passage as exactly one chunk")
>
>     def search(self, store_id, query):
>         return self.call("POST", f"vector_stores/{store_id}/search", retry=True, payload={
>             "query": query, "max_num_results": RESULT_COUNT, "ranking_options": RANKING, "rewrite_query": False,
>         })["data"]
>
>
> def digest(text):
>     return hashlib.sha256(text.encode()).hexdigest()
>
>
> def normalized(text):
>     return " ".join(unicodedata.normalize("NFC", text).split())
>
>
> def terms(text):
>     return set(TOKEN.findall(unicodedata.normalize("NFKC", text).casefold()))
>
>
> def select_corpus(directory, language):
>     query_path = directory / f"{language}-queries.parquet"
>     qrel_path = directory / f"{language}-qrels.parquet"
>     queries = {row["id"]: row["text"] for row in parquet.read_table(query_path).to_pylist()}
>     labels = {}
>     for row in parquet.read_table(qrel_path).to_pylist():
>         query_id = row["query-id"]
>         if row["score"] != 1 or query_id in labels:
>             raise ValueError(f"Expected one positive WebFAQ judgment per query for {language}")
>         labels[query_id] = row["corpus-id"]
>     if queries.keys() != labels.keys():
>         raise ValueError(f"Test query and qrel IDs differ for {language}")
>
>     selected = sorted(queries, key=lambda qid: digest(f"{SALT}/{language}/{qid}"))[:TEST_QUERIES]
>     relevant = {labels[qid] for qid in selected}
>     targets = pa.array(sorted(set(labels.values())))
>     paths = sorted(directory.glob(f"{language}-corpus-*.parquet"))
>     expected_shards = 4 if language == "eng" else 1
>     if len(paths) != expected_shards:
>         raise ValueError(f"Expected {expected_shards} pinned corpus shards for {language}")
>
>     pool = {}
>     for path in paths:
>         for batch in parquet.ParquetFile(path).iter_batches(batch_size=16_384, columns=["id", "text"]):
>             for row in batch.filter(pc.is_in(batch.column("id"), value_set=targets)).to_pylist():
>                 text = normalized(row["text"])
>                 if text:
>                     pool[row["id"]] = text
>     if not relevant <= pool.keys():
>         raise ValueError(f"Missing labeled passages for {language}")
>
>     passage_terms = {did: terms(text) for did, text in pool.items()}
>     frequencies = Counter(token for tokens in passage_terms.values() for token in tokens)
>     weights = {token: math.log1p(len(pool) / frequency) for token, frequency in frequencies.items()}
>     available = set(pool) - relevant
>     distractors = set()
>     for qid in selected:
>         query_terms = terms(queries[qid])
>
>         def ranking_key(did):
>             tokens = passage_terms[did]
>             overlap = math.fsum(weights[token] for token in sorted(query_terms & tokens))
>             return -overlap / math.sqrt(max(1, len(tokens))), did
>
>         candidate = min(available, key=ranking_key)
>         available.remove(candidate)
>         distractors.add(candidate)
>
>     documents = {did: pool[did] for did in sorted(relevant | distractors)}
>     if len(set(documents.values())) != len(documents):
>         raise ValueError(f"Duplicate passage text in {language} evaluation subset")
>     questions = [(qid, queries[qid], labels[qid]) for qid in selected]
>     return documents, questions, len(queries), len(pool)
>
>
> def scores(api, store_id, files, questions):
>     def search(question):
>         qid, query, expected = question
>         started = time.monotonic()
>         try:
>             hits = api.search(store_id, query)
>         except RuntimeError as error:
>             if not re.search(r"returned (429|500|502|503|504):|feature_unavailable", str(error)):
>                 raise
>             print(f"WebFAQ query {qid} could not be scored after retries: {error}", flush=True)
>             return {
>                 "query_id": qid,
>                 "relevant_document_rank": 0,
>                 "reranked": False,
>                 "positive_keyword_score_on_relevant_document": False,
>                 "api_error": True,
>                 "elapsed": time.monotonic() - started,
>             }
>         elapsed = time.monotonic() - started
>         rank = next((index for index, hit in enumerate(hits, start=1) if hit["file_id"] == files[expected]), 0)
>         return {
>             "query_id": qid,
>             "relevant_document_rank": rank,
>             "reranked": any(hit["score_breakdown"]["rerank"] is not None for hit in hits),
>             "positive_keyword_score_on_relevant_document": bool(
>                 rank and (hits[rank - 1]["score_breakdown"]["keyword"] or 0) > 0
>             ),
>             "elapsed": elapsed,
>         }
>
>     with ThreadPoolExecutor(max_workers=3) as pool:
>         observations = list(pool.map(search, questions))
>     ranks = [item["relevant_document_rank"] for item in observations]
>     metrics = {
>         "ndcg_at_10": mean(1 / math.log2(rank + 1) if rank else 0 for rank in ranks),
>         "recall_at_10": mean(rank > 0 for rank in ranks),
>         "mrr_at_10": mean(1 / rank if rank else 0 for rank in ranks),
>         "hit_at_1": mean(rank == 1 for rank in ranks),
>         "searches_reranked": sum(item["reranked"] for item in observations),
>         "searches_with_api_errors": sum(item.get("api_error", False) for item in observations),
>         "searches_with_positive_keyword_score_on_relevant_document": sum(
>             item["positive_keyword_score_on_relevant_document"] for item in observations
>         ),
>         "median_api_seconds": round(median(item.pop("elapsed") for item in observations), 3),
>     }
>     return {"metrics": metrics, "observations": observations}
>
>
> def evaluate(api, args, language, collection, run_name):
>     documents, questions, official_queries, pool_size = collection
>     files, stores = {}, {}
>     try:
>         print(f"{language}: uploading {len(documents)} official WebFAQ passages", flush=True)
>         with ThreadPoolExecutor(max_workers=3) as pool:
>             tasks = {pool.submit(api.upload, f"{run_name}-{language}-{did}.txt", text): did
>                      for did, text in documents.items()}
>             errors = []
>             for task in as_completed(tasks):
>                 try:
>                     files[tasks[task]] = task.result()
>                 except Exception as error:
>                     errors.append(error)
>             if errors:
>                 raise errors[0]
>
>         result = {
>             "documents": len(documents), "test_queries": len(questions),
>             "official_test_queries": official_queries, "distractor_pool_documents": pool_size,
>             "document_ids_sha256": digest("\n".join(documents)),
>             "query_ids_sha256": digest("\n".join(qid for qid, _, _ in questions)), "variants": {},
>         }
>         for mode in ("vector", "graph"):
>             store = api.create_store(f"{run_name}-{language}-{mode}", mode, args.extraction_model, args.embedding_model)
>             stores[mode] = store["id"]
>             api.ingest(store, [files[did] for did in documents], batch_size=4)
>             print(f"{language}: scoring {len(questions)} WebFAQ queries in {mode} mode", flush=True)
>             run = scores(api, store["id"], files, questions)
>             keys = ("embedding_model", "embedding_dimensions", "extraction_model", "max_hops")
>             run["settings"] = {key: store.get(key) for key in keys}
>             result["variants"][mode] = run
>         actual_embeddings = {(v["settings"]["embedding_model"], v["settings"]["embedding_dimensions"])
>                              for v in result["variants"].values()}
>         if len(actual_embeddings) != 1:
>             raise ValueError(f"Vector and graph embeddings differ for {language}")
>         return result
>     finally:
>         for prefix, identifiers in (("vector_stores", stores.values()), ("files", files.values())):
>             with ThreadPoolExecutor(max_workers=3) as pool:
>                 def remove(identifier):
>                     try:
>                         api.call("DELETE", f"{prefix}/{identifier}", retry=True)
>                     except Exception as error:
>                         print(f"Cleanup failed for {prefix}/{identifier}: {error}", flush=True)
>
>                 list(pool.map(remove, identifiers))
>         print(f"{language}: cleanup requested for {len(stores)} stores and {len(files)} uploads", flush=True)
>
>
> def main():
>     parser = argparse.ArgumentParser(description=__doc__)
>     parser.add_argument("--api-base-url", required=True)
>     parser.add_argument("--data-dir", type=Path, required=True)
>     parser.add_argument("--output", type=Path, required=True)
>     parser.add_argument("--languages", nargs="+", choices=LANGUAGES, default=list(LANGUAGES))
>     parser.add_argument("--embedding-model", default="meetkai:embedding")
>     parser.add_argument("--extraction-model", default="openai:gpt-4.1-mini")
>     parser.add_argument("--prepare-only", action="store_true", help="Verify the selected inputs without calling the API")
>     args = parser.parse_args()
>     base_url = args.api_base_url.rstrip("/")
>     parsed = urlsplit(base_url)
>     if (parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.password
>             or parsed.query or parsed.fragment or not parsed.path.endswith("/api/v1/llm")):
>         parser.error("--api-base-url must be an HTTPS URL ending in /api/v1/llm")
>
>     collections = {}
>     for language in args.languages:
>         collection = select_corpus(args.data_dir, language)
>         print(language, f"{len(collection[0])} passages and {len(collection[1])} official test queries", flush=True)
>         collections[language] = collection
>     if args.prepare_only:
>         return
>
>     api_key = os.environ.get(KEY_NAME)
>     if not api_key:
>         parser.error(f"Set {KEY_NAME} to your MKA1 API key")
>     api = BenchmarkAPI(base_url, api_key)
>     run_name = f"webfaq-retrieval-{uuid.uuid4().hex[:10]}"
>     result = {"dataset": "mteb/WebFAQRetrieval", "revision": REVISION, "result_limit": RESULT_COUNT,
>               "ranking_options": RANKING, "chunking_strategy": CHUNKING, "languages": {}}
>     with ThreadPoolExecutor(max_workers=3) as pool:
>         jobs = {pool.submit(evaluate, api, args, language, collection, run_name): language
>                 for language, collection in collections.items()}
>         failures = []
>         for job in as_completed(jobs):
>             language = jobs[job]
>             try:
>                 result["languages"][language] = job.result()
>             except Exception as error:
>                 print(f"{language}: benchmark failed: {error}", flush=True)
>                 failures.append(error)
>             args.output.write_text(json.dumps(result, indent=2, sort_keys=True) + "\n")
>         if failures:
>             raise failures[0]
>
>
> if __name__ == "__main__":
>     main()
> ```

The output contains metrics for each retrieval mode, the resolved model settings, and the labeled result's rank for each query. Compare the resolved settings and `searches_reranked` before comparing scores.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.