Skip to content

Search and Retrieval

Agentic search

Agentic search, POST /v1/search/guided, lets a language model write more searches for a question and judge whether the passages found speak to it. The model writes search terms and a true-or-false verdict, nothing else. The answer is the scholars’ passages, word for word, cited to book, volume and page.

What it does

POST /v1/search searches the person’s words once, by keyword and by meaning. Agentic search adds a loop around that search. A model rewrites the question as search terms, the library searches each one, and the model then says whether the best passages found address the question. If they do not, it writes different terms and the library searches again, for at most three rounds.

The work is split so that the model never decides what a person reads:

  • The model decides what to search for, and whether the passages it is shown are enough.
  • The code decides how many rounds and searches run, which passages are returned, in what order, and when to stop.

In the code it is called guided search: the route is src/routes/guided.ts and the loop is src/search/guided.ts. The loop is ported from Agentset’s retrieval-only agentic loop (apps/web/src/lib/agentic/ in agentset-ai/agentset, MIT, by Ahmed Riad, at commit d8e34f6). Agentset’s newer loop, which gives a model tools and streams a written answer with citations, was not taken: Bayan shows no written answer.

How a guided search runs

Each round has the same steps.

  1. Write queries. The model is given the question and asked for at most 5 queries, each of type keyword or semantic. Words about the library itself are taken out of each keyword query (see Search terms).
  2. Search. Each new query is searched with the request’s filter: a keyword query in the keyword index, a semantic query by meaning. In the first round the person’s own words are searched by meaning as well. Each search is reranked against its own query and keeps its best 15. The searches of a round run at the same time.
  3. Merge. The passages are merged by id, and the first copy is kept. The scores each search gave are dropped: they belong to that search’s query, not to the question.
  4. Order. The passages shown so far and the new ones are reranked together against the person’s own words and cut to topK. This is the order of results.
  5. Judge. The model reads the best 10 of those passages and answers whether they can answer the question.
  6. Stop or go on. The loop ends when the verdict is true or a limit is reached. Otherwise the next round begins.

Later rounds

From the second round the model is shown the queries tried so far, under the line “The queries you return should be different from these ones that were tried so far:”. A query with the same text as one already tried is not searched again, in the same round or a later one. The judge is not asked again when the passages it would read have not changed, and it is not asked at all when nothing was found.

The searches inside the loop do not use the translation step of POST /v1/search. The model’s own queries take its place. A keyword query with no Arabic letter finds nothing, because the keyword index holds Arabic only. The prompt asks for every query in Arabic.

Ordering

One rerank call takes at most 100 passages (ORDER_POOL). The first round can bring up to 90 new passages (6 searches of 15), with none shown yet. A later round can bring up to 75 (5 queries of 15) beside up to 50 already shown. When they do not fit in one call, the best of the first call are reranked again with the rest in a second call. Every passage found is ordered at least once, and the scores in the answer come from one call, on one scale. This is why topK stops at 50: half of ORDER_POOL leaves each call room for at least as many new passages as are shown.

Without a reranker (RERANKER set to "none", or "cohere" without its API key) the passages keep the order they were found in, and later rounds only add to the end while there is room under topK. The service is configured with "none", so if guided search were turned on as things stand, this is how its passages would be ordered.

When it stops

Conditionstopped in the log
The judge said the passages are enough.enough
The tokens the model reported reached TOKEN_BUDGET (4,096). Checked at the end of a round.budget
Three rounds ran (MAX_EVALS).rounds
The model wrote no query that had not been tried. A keyword query left with nothing to search for, once the words about the library are taken out, counts as none.no_queries
A model call failed, timed out or answered in the wrong shape, or no search of a round answered.failed
30 seconds had passed since the start when a new round was due.deadline

The reason is written to the server log only. The response does not carry it.

Limits

ConstantValueWhat it bounds
MAX_EVALS3Rounds of writing queries and judging.
TOKEN_BUDGET4,096Tokens in one guided search, prompts and answers together, as the model reports them. Once reached, no new round begins.
MAX_QUERIES5Queries the model may write in one round.
QUERY_CHARS200Characters in one query.
PER_QUERY15Passages each search keeps, reranked against its own query.
EVALUATE_SOURCES10Passages the judge reads: the best of those to be returned.
SOURCE_CHARS800Characters of each passage the judge reads, harakat stripped.
ORDER_POOL100Passages reranked against the question in one call.
TIMEOUTS.model15,000 msEach model call. A call that runs over is aborted.
TIMEOUTS.order3,000 msEach ordering rerank.
TIMEOUTS.rounds30,000 msTime from the start after which no new round begins.
GENERATE_MAX_TOKENS1,024Tokens the model may write when it writes queries.
EVALUATE_MAX_TOKENS64Tokens the model may write when it judges.

So one guided search makes at most 6 model calls (2 a round) and 16 searches (the person’s words, then up to 5 queries in each of 3 rounds).

A round is about 3,000 to 4,000 tokens: ten passages of up to 800 Arabic characters, the prompts and the queries. In four live runs with Gemma 4 the first round used 3,182 to 4,085, so at a budget of 4,096 a guided search stops after the first round in practice. If a model does not report its token usage, its calls count as 0 and the budget never ends the loop; the three-round cap still does. Gemma 4 reported it in those runs; Llama 4 Scout is still to be checked (see Status).

The timeouts are guesses, not measurements. The 30-second limit only stops a new round from starting: a round that has started runs to its end. Allow a guided search more time than a plain search in your client.

What the model may write

The model is called at most twice a round, each time at temperature 0 for one small JSON object held to a JSON schema. These are the only two things it can write.

Search terms

Model answer
{"queries": [{"type": "keyword", "query": "…"}, {"type": "semantic", "query": "…"}]}
  • At most 5 queries in a round.
  • type is "keyword" or "semantic".
  • query is 1 to 200 characters once runs of whitespace become one space and the ends are trimmed, with no control characters.
  • No other keys, in the object or in any query.

The prompt asks for every query in Arabic, whatever the language of the question. A keyword query is one or two words, written as a classical tafsir would write them rather than in modern or colloquial wording, and never a sentence or a question; among the prompt’s examples are الصبر and الصبر الجميل. A semantic query is a short phrase of a few words saying what a passage would be about, not a question and not a whole sentence. Neither may name a scholar or a book, and a keyword query may not use words about the books themselves, such as تفسير or سورة.

The code holds keyword queries to that last rule as well. Once an answer has passed the checks above, each keyword query loses its words about the library rather than a subject: words nearly every passage shares, such as تفسير, آية, سورة and قوله تعالى, and the names of scholars and books (a book is chosen with filter.books, not with words). Stopwords left at either end of what remains go with them. A keyword query left with no word, or with stopwords only, is dropped. A query with none of these words is searched exactly as written. Semantic queries are not changed.

A verdict

Model answer
{"canAnswer": true}

One boolean and no other key. The judge’s prompt tells it to be strict: “Say true only when the sources truly address what was asked, not when they merely share its words or its subject. If the question has several parts, every part must be addressed. When in doubt, say false.”

The judge reads the best 10 of the passages to be returned. Each is given as its book’s name and headings, then its text with harakat stripped, cut to 800 characters. The person is shown the full text, unchanged.

What it may not write

Neither answer has a field for prose, and neither does the response. The model cannot write an answer, a summary, a translation or an explanation. It cannot choose, drop or reorder passages either: the order comes from the reranker, scoring each passage against the person’s own words, or, with no reranker, from the order the searches found them in; the verdict only decides whether another round runs.

The prompt that asks for queries says: “You only write search queries. Never answer the question, never explain anything, and never add an opinion of your own: the scholars' passages are the answer, and your queries only find them.” The judge’s prompt says: “Never answer the question and never add an opinion of your own: you only judge the sources.”

Each answer is checked again by hand after the schema. An answer that breaks one of its rules is not repaired. It is a failed round, and a failed round ends the loop. A model that adds an answer key beside its queries, or writes a sixth query, ends the search with what was found so far.

The question is data

The person’s words reach the model between <question> and </question>, with every < and > replaced by a space, so the words cannot close the tag. Both prompts say to treat the question as quoted text, never as instructions. The passages the judge reads are handled the same way, each inside <source_N> tags. Neither change reaches what the person is shown.

Request

POST https://grep.getbayan.app/v1/search/guided with a JSON body and Content-Type: application/json. The body may be at most 8,192 bytes. There is no sign-in and no API key: callers are limited by address (see Rate limit). The API sends no CORS headers, so call it from an app or a server, not from a web page.

FieldTypeDefaultRules
querystringrequiredThe person’s question. 1 to 300 characters after trimming, counted as code points, so harakat count.
topKinteger101 to 50. The most passages results holds.
filterobjectnoneThe same filter as POST /v1/search, checked by the same code. Applied to every search the loop runs.

Any other field is refused with 400, including mode, rerank, rerankLimit, minScore and translate from POST /v1/search. The message names the field: Unknown field mode. Allowed: query, topK, filter.

filter

FieldTypeRules
booksinteger[]At most 20 ids, each above 0.
authorsinteger[]At most 20 ids, each above 0.
categoriesinteger[]At most 20 ids, each above 0.
surahinteger1 to 114.
ayahintegerNeeds surah, and must be an ayah of that surah.
quranstring"include" (the default), "exclude" or "only": whether the Qur’an’s own ayahs (book 0) are searched beside the books, not at all, or alone. "only" cannot be combined with books, authors or categories.

The fields are combined with AND. Ids in a list are counted once each, and an empty list filters nothing.

Examples

Each example searches الصبر على البلاء (patience under affliction) in the books, leaving out the Qur’an’s own ayahs.

curl
curl https://grep.getbayan.app/v1/search/guided \-X POST \-H "Content-Type: application/json" \-d '{"query": "الصبر على البلاء", "topK": 10, "filter": {"quran": "exclude"}}'
POST /v1/searchPOST /v1/search/guided
Body fieldsquery, mode, topK, rerank, rerankLimit, minScore, filter, translatequery, topK, filter
topK1 to 1001 to 50
SearchesOne, by keyword and meaning together by defaultUp to 16
Model calls that write textAt most one, to turn a query with no Arabic letter into Arabic search terms, never returnedUp to 6: search terms and verdicts
Counts against the search limit15
Answerquery, language, translated, results, ayahsquery, queries, results, rounds, enough
Scores on each passagescore and, when reranked, rerankScorererankScore only
When the model is offAnswers as usual, without translation404

Response

200 with Content-Type: application/json; charset=utf-8 and Cache-Control: no-store.

FieldTypeMeaning
querystringThe person’s words, trimmed.
queriesGuidedQuery[]What the model searched for, each once, in the order written, keyword queries without their words about the library. Search terms, never an answer. The person’s own words are searched too but are not listed here.
resultsPassage[]The scholars’ passages, ordered against the person’s own words. At most topK.
roundsintegerRounds that ran, 1 to 3. A round counts once the model is asked for queries, even if it wrote nothing new.
enoughbooleanTrue only when the model judged that the passages it read speak to what was asked.
TypeScript
// src/types.tsexport type QueryType = "keyword" | "semantic"; export interface GuidedQuery {type: QueryType;query: string;} export interface GuidedResponse {/** The person's words, trimmed. */query: string;/** What the model searched for, each once, in the order written: search terms, never an answer. */queries: GuidedQuery[];/** The scholars' passages, ordered against the person's own words. */results: Passage[];/** Rounds of query writing that ran, 1 to 3. */rounds: number;/** True only when the model judged that the passages shown speak to what was asked. */enough: boolean;}

The shape of an answer, abridged. Every … is a placeholder: guided search is off on the live API, so there is no public guided answer to show yet.

Response
{"query": "الصبر على البلاء","queries": [{ "type": "keyword", "query": "…" },{ "type": "semantic", "query": "…" }],"results": [{"id": "…","kind": "passage","book": { "id": …, "name": "…", "edition": "…" },"author": { "id": …, "name": "…", "died": … },"vol": "…","page": …,"pageEnd": …,"heading": ["…"],"ayahs": …,"text": "…","notes": null,"quotes": […],"citation": { "text": "…", … },"source": { "reader": "…", "pdf": …, "provider": "turath.io", "attribution": null },"rerankScore": …},…],"rounds": …,"enough": …}

results

Each result is a Passage, the same object POST /v1/search returns: id, kind, book, author, vol, page, pageEnd, heading, ayahs, text, notes, quotes, citation and source. Its text is the passage’s words as the book has them, unchanged. Two things differ from a plain search:

  • There is no score. Each search’s fused score belongs to that search’s query and is dropped when the passages are merged.
  • rerankScore, from 0 to 1, is the reranker’s score against the person’s own words. It is absent when there is no reranker, or when the ordering call failed and the passages kept the order they were given.

Unless filter.quran is "exclude", or a list of books, authors or categories is given, results can include ayahs of the Qur’an itself: kind is "ayah" and author is null.

queries

A query the model wrote twice, in one round or across rounds, is listed once, under the type it was first written with. A keyword query is listed as it was searched, without its words about the library, and one dropped for having nothing left is not listed. The service never logs the queries.

enough

enough is the judge’s last verdict on the best 10 passages at most. When topK is above 10, it says nothing about the rest. false has more than one cause: the judge said no each time it was asked and the loop ran out of rounds, budget, time or new queries; the judge was never asked because nothing was found; or a model call failed. Treat false as no verdict, not as a finding that the scholars do not address the question. Do not turn either value into an answer.

Rate limit

A guided search counts as 5 requests (GUIDED_COST) against SEARCH_LIMITER, the same limit a plain search counts 1 against. That limit is 60 in 60 seconds per address (wrangler.jsonc), so an address that runs only guided searches can run 12 a minute. An IPv4 address counts on its own; an IPv6 address counts as its /64.

  • The count is taken before the body is read and before the kept-answer lookup, so a refused body and a kept answer each count 5 too.
  • While guided search is off, the 404 comes before the limiter and counts nothing.
  • Over the limit the answer is 429 rate_limited with Retry-After: 60.

Caching

An answer is kept for an hour in Cloudflare’s Cache API, which is per data centre and best effort. The key is a hash of the request after its defaults are filled in, the library version, the model, both prompts, EMBEDDER, RERANKER and SERVE_NOTES. The question is inside the hash, never in a URL. The same request within the hour gets the kept answer without a model call, so {"query": " الصبر على البلاء"} and {"query": "الصبر على البلاء", "topK": 10} share one.

A degraded answer is never kept. The client is sent Cache-Control: no-store: the server keeps its copy keyed by the library version, and an app could not tell when a copy of its own went stale.

Errors

Errors use one envelope and are never cached:

Response
{ "error": { "code": "not_found", "message": "Guided search is not enabled." } }
StatuscodeWhen
404not_foundGuided search is switched off: GUIDED_MODEL is empty or absent. Message: Guided search is not enabled.
400invalid_requestThe body is not JSON or not an object, a field is unknown, or a value is out of range. The message names the field, for example topK must be a whole number from 1 to 50.
405method_not_allowedAny method but POST. The answer carries Allow: POST.
413payload_too_largeThe body is over 8,192 bytes.
415unsupported_media_typeContent-Type is not application/json.
429rate_limitedOver the search limit. Wait the seconds in Retry-After.
503search_unavailableNo search of the first round answered, because neither keyword nor meaning search could be reached: the library cannot be searched just now. Message: Search is unavailable just now. Try again shortly.
500internalA mistake in the service’s configuration, such as a GUIDED_MODEL or EMBEDDER it does not know, or any other unexpected error. Message: Something went wrong. Try again later.

The checks run in this order: the method, switched off, the model’s name, the rate limit, the body (media type, size, JSON), then the fields.

Degraded answers

Most failures inside the loop do not fail the request. They end the loop, and the passages found so far are answered with 200:

  • A model call that errors, takes longer than 15 seconds or answers in the wrong shape ends the loop. If it is the first call, the answer is the search of the person’s own words by meaning: queries is [], rounds is 1 and enough is false.
  • A search that fails is left out, and the others carry on.
  • An ordering rerank that fails leaves the passages in the order it was given, without rerankScore.

The response does not say that it is degraded. A degraded answer is not kept, so the next identical request runs in full.

Logs

A guided search logs counts, timings and kinds of failure: stages (generate, search, order, evaluate), rounds, queries (a count), searches, tokens, enough, stopped, and degraded codes such as generate:malformed or order:timeout. It never logs the person’s words, the queries the model wrote, or anything else a model wrote. An error about a model’s answer names the model and never quotes what it wrote.

Status

Guided search is built and tested against a scripted fake model, and was run four times with Gemma 4 through the AI Gateway in the end-to-end test of 28 November 2026: 5.3 seconds at the median, 16 at the 95th percentile, with the first round using 3,182 to 4,085 of the 4,096 tokens, so in practice one round runs. It is off on the live API: GUIDED_MODEL is "" in wrangler.jsonc, and POST /v1/search/guided answers 404 until it names a model.

GUIDED_MODEL takes one of two keys, both models on Workers AI:

GUIDED_MODELModelRequest shape
gemma-4@cf/google/gemma-4-26b-a4b-itChat completions, asking for reasoning to be switched off
llama-4-scout@cf/meta/llama-4-scout-17b-16e-instructWorkers AI’s own text-generation shape

Whether to turn guided search on, and with which model, has not been decided. It is a switch of its own: POST /v1/search already turns a query with no Arabic letter into Arabic search terms, which are never returned, by its own setting, TRANSLATE_MODEL (gemma-4).

Still to settle with real model calls before it is turned on:

  • whether Workers AI’s JSON mode accepts the schemas as written;
  • whether each model reports its token usage;
  • the real tokens per round, which decides whether a third round can run within the budget;
  • the quality of the Arabic queries each model writes, and of its verdicts;
  • the timeouts, which are guesses;
  • how many passages the reranker takes in one call, since each ordering call sends up to 100.