Using the Query API¶
The Query API is how a module, theme or custom code asks a question and gets
back cited sources or an answer. It is a PHP API in the base
drupal_rag_toolkit module; there is no HTTP API. Its classes are
experimental during the alpha and may change before beta.
The base module defines the API. drupal_rag_toolkit_search_api provides
the implementation, so enable both.
Ask a question¶
Inject the context factory and the query service by interface:
use Drupal\drupal_rag_toolkit\Contract\ToolkitQueryContextFactoryInterface;
use Drupal\drupal_rag_toolkit\Contract\ToolkitQueryInterface;
use Drupal\drupal_rag_toolkit\Value\Result\ToolkitQueryResultInterface;
use Drupal\drupal_rag_toolkit\Value\ToolkitQueryRequest;
class HelpAnswer {
public function __construct(
private readonly ToolkitQueryContextFactoryInterface $contextFactory,
private readonly ToolkitQueryInterface $query,
) {}
public function ask(string $question): ToolkitQueryResultInterface {
$context = $this->contextFactory->create('my_module.help_answer', [
'user',
'languages:language_content',
]);
return $this->query->query(new ToolkitQueryRequest($question, $context));
}
}
The context records who is asking and which cache contexts the result varies by. Use a stable consumer ID for your module. Every request needs a context; access is checked for the current user.
ToolkitQueryRequest takes:
| Argument | Default | Meaning |
|---|---|---|
question |
The visitor's question. | |
context |
From the context factory. | |
profileId |
'default' |
The profile to answer with. |
evidenceOnly |
FALSE |
Return cited sources without generating an answer, even if the profile can generate. |
constraints |
NULL |
Corpus filters, such as content type, used by governed Views. |
groundedAnswerPolicy |
NULL |
Limits on how much evidence goes into a generated answer. |
onAnswerText |
NULL |
A closure called with each piece of a generated answer as it is written. |
Read the result¶
query() returns one of four result types. Check state():
| State | Class | What you get |
|---|---|---|
grounded |
GroundedQueryResult |
$answer and $citations |
evidence |
CitedSourcesQueryResult |
$citations |
no_grounded_answer |
NoGroundedAnswerQueryResult |
Nothing eligible answered the question. |
unavailable |
UnavailableQueryResult |
A dependency, such as the provider, failed. |
Each citation has a title, url and sourceUuid. When the profile cites
each claim, $answer contains markers such as [2]: marker n refers to
the n-th citation. The query does not throw for these outcomes, so handle
all four states.
$result = $helpAnswer->ask('How do I renew my business license?');
if ($result->state() === 'grounded') {
$text = $result->answer;
}
foreach ($result->citations ?? [] as $citation) {
$links[] = ['title' => $citation->title, 'url' => $citation->url];
}
toArray() gives a serializable form, and cacheability() gives the cache
metadata to apply to anything you build from the result.
Render the result¶
To show a result with the toolkit's own markup, inject
drupal_rag_toolkit.query_result_renderer:
$build = $renderer->render($result, $context);
The render array shows the state, the answer and citations, and carries the correct cache metadata. Results depend on the user's access, so do not cache them more broadly than the context says.
Stream an answer¶
To show a generated answer as it is written, pass onAnswerText:
$request = new ToolkitQueryRequest(
$question,
$context,
onAnswerText: function (string $text): void {
echo json_encode(['text' => $text]) . "\n";
flush();
},
);
$result = $this->query->query($request);
The streamed text is a draft. When the query returns, replace it with the
result, which has passed the citation checks. Profiles with a guardrail set
never stream, because their output must be checked before anyone sees it.
The knowledge search page's SummaryStreamController is a working example.
Without code¶
- Views: add a governed RAG search to a View on the corpus's Search API index. Keep at least one RAG Corpus filter.
- Drush:
drush drupal-rag-toolkit:query "your question"runs the same API as the anonymous user and prints the result. - Example module:
tests/modules/drupal_rag_toolkit_reference_consumerin the Search API submodule is a block that uses only this API.