In short.
This is an xAI cookbook walkthrough for developers who want to build a document question-answering app on the Grok API that quotes and cites its sources, and its main catch is that it needs two xAI keys (an API key and a management key) and uploads your documents to xAI's collections service. The page describes a TypeScript app that ingests documents into a collection with required version and team fields, searches with an AIP-160 filter, sends the top six passages to grok-4.7 with a JSON schema that puts quotes before the answer, verifies each quote word for word against its passage, and answers "I couldn't find that in your documents." when nothing supports an answer. It reports about 3 to 8 seconds and about $0.003 per answer at list prices, and a 20-question eval that the authors say passed fully. These are the authors' own figures. The page describes the implementation and reports the authors' results, but does not include implementation files, raw evaluation output or licence text. Independent runtime and performance verification is unknown.
Researched and written by an AI model and checked by a second AI model. How it works
Coverage is the complete selected page at [https://docs.x.ai/cookbook/examples/docs-to-cited-answers.md], captured on 2026-11-14 (selected-page.txt, 9,516 bytes). Linked pages are excluded: the Management API guide, the metadata documentation and the console. The example's source files and sample data (src/*.ts, public/index.html, eval.json, handbook/) are not part of the selected page, which describes their behaviour in prose only. The page includes no licence or notice, so rights are unknown. The page provides descriptions and author-reported results; the timing, cost and eval figures are the page authors' own statements, and independent runtime and performance verification is unknown.
The overview
What this resource is
Docs to Cited Answers is an example page in xAI's cookbook at [https://docs.x.ai/cookbook/examples/docs-to-cited-answers.md]. It describes a small app that answers questions from your own files using the Grok API and attaches a citation and a quoted sentence to each answer. The page names support articles, policies and an internal handbook as the use cases where answers have to be checkable.
The page is documentation about an example that lives at examples/docs-to-cited-answers/typescript. The page does not name the repository or give a version number for the example. It names the model grok-4.7 and Node.js 22.13 or later. The page refers to source files (src/ingest.ts, src/answers.ts, src/server.ts, src/index.ts, src/eval.ts, public/index.html, eval.json, handbook/metadata.json) but does not include their contents.
Overall assessment
This is a focused, practical walkthrough of a retrieval-then-cite pattern. It gives exact endpoints, the order of the JSON schema fields and why they are in that order, the search and eval behaviour, and several caveats the authors found themselves, such as the built-in collections search tool rejecting filters. For a developer who is already using or evaluating the Grok API, it looks like a useful starting point.
Treat the performance, cost and eval claims as the authors' own statements. The page says "When we ran it" for the eval result and gives timing and cost figures. The page describes the implementation and reports the authors' results, but does not include implementation files, raw evaluation output or licence text. Independent runtime and performance verification is unknown. The sample data is six documents for a made-up store and the eval is 20 questions. The authors report successful results on the six-document sample; independent validation and behaviour on larger or messier collections are unknown.
Who it is for
The main audience is developers who already build on, or are weighing up, the xAI Grok API and want an answer system whose output a reader can check against the source. The page's own examples are support articles, policies and an internal handbook. It is also useful to anyone who wants to see how to combine metadata filtering, structured streaming output and a quote check.
It assumes you can use Node.js and npm, set environment variables and create keys in the xAI console. A beginner can follow the commands as written, but the page does not teach retrieval concepts from scratch. It explains chunking, filters and structured output only as far as the app needs them.
What it shows how to do
The page lists what a reader will learn: create a collection with metadata fields and add documents with their fields; search with an AIP-160 filter such as version="2026"; have Grok quote passages before answering and check each quote against its passage; return "I couldn't find that in your documents." instead of guessing; stream structured output and show quotes and answer as they arrive; and measure search and citations with a small eval.
The described app has two front ends. The web page has a filter panel with a document library, streamed reasoning, an answer with numbered citations, and a panel of retrieved passages that shows file, relevance score and fields. The quoted sentence lights up as Grok copies it, and a Stop button cancels a request. The terminal command takes a question and an optional --filter, and saves the answer, quotes and passages to output/answers/. The filter defaults to version="2026", and --filter "" searches every document. The page's example is a sale-item return after 30 days: the answer changes from yes under version="2025" to no under version="2026".
Using it
Requirements
The page states Node.js 22.13 or later and two keys. XAI_API_KEY uploads files, searches and asks Grok. XAI_MANAGEMENT_API_KEY, created in the console under Settings, then Management Keys, creates the collection and adds documents. The management key needs the AddFileToCollection permission plus the permissions in the Collections Endpoint group for creating collections and reading their documents. It must be made in the same team as the API key. Only npm run ingest uses it.
Both keys go in a .env file at the repo root or are exported. The page refers to the console as the SpaceXAI Console at [https://console.x.ai]. It also links the Management API guide at [https://docs.x.ai/developers/management-api-guide]. Unknown from the page: whether your account needs specific plan, billing or region access to use collections, the Management API or grok-4.7. It also does not say which operating systems were used.
How it works
Ingestion (src/ingest.ts): creates a collection with POST /v1/collections on the Management API, with required version and team fields in field_definitions, so a document without them is rejected. Each document is uploaded with client.files.upload() and then added with POST /v1/collections/{collection_id}/documents/{file_id}. The script polls until the status is DOCUMENT_STATUS_PROCESSED. The collection uses 500-character chunks instead of the default 4,000 bytes, so each short policy yields several passages. These calls use fetch because the SDK does not cover the Management API.
Answering (src/answers.ts): answer() runs two steps. First, searchDocuments() sends the question, collection ID and filter to POST /v1/documents/search and gets back the six best passages with text, file, relevance score, page number and fields. Search mixes keyword and semantic matching by default. Filters use AIP-160 syntax, values match exactly, and a filter on a field no document has matches nothing. If no document matches the filter, the app answers "I couldn't find that in your documents." without calling Grok. Second, writeAnswer() numbers the passages and sends them to grok-4.7 with a JSON schema in three parts: quotes (passage number plus copied words), whether the passages answer the question, and the answer with a bracketed passage number after each fact. Quotes come first so Grok picks the evidence before writing. The app checks the quotes before it shows any of the answer. A quote counts only if it appears in its passage word for word, ignoring spacing, case and curly quotes, and an answer needs at least one quote that counts. Reasoning effort is low.
Serving: src/server.ts runs answer() and streams each step to the page as server-sent events. It passes an AbortSignal to each request so Stop or closing the page cancels it. It also serves output/collection.json, which the page uses to build the library and filter buttons.
Setup steps
The page gives this sequence: put both keys in .env or export them; cd examples/docs-to-cited-answers/typescript; npm install; npm run ingest. Ingest creates a collection named handbook, adds the six documents in handbook/ with the fields from handbook/metadata.json, waits until they are searchable, and saves the collection ID to output/collection.json. The page says this takes about 15 seconds. Then npm run web starts the app at [http://localhost:3000], or npm start -- "question" --filter 'version="2025"' asks from the terminal.
To use your own documents, put them in a folder with a metadata.json giving each file a version and a team, then run npm run ingest -- path/to/folder. To use other fields, change FIELDS in src/ingest.ts. The page builds filter buttons from whatever fields the documents have. Unknown: which file types besides the sample handbook's files (the page mentions a two-page PDF) are supported, and any upload size limits.
Worked example from the page
The sample is a handbook for a made-up outdoor store, with six documents. Ask whether a sale item can be returned after 30 days, first under version="2025" and then under version="2026", and the page says the answer changes from yes to no, because the filter decides which documents count. In the terminal: npm start -- "Can I return a sale item after 30 days?" --filter 'version="2025"'.
Questions the filtered documents cannot answer, such as a student discount or a sale-item return under team="Finance", should return "I couldn't find that in your documents." The page says all three such eval questions did so when the authors ran it. The outputs above are the page's own description; independent runtime verification is unknown.
Assessment & evidence
Limitations and caveats
The page is explicit about several limits. The built-in collectionsSearch() tool is not used because the API rejected filters on it with "Argument not supported: filters". Its results lack page number and fields, and the file name came back empty when the authors tried it. The search's page_number is documented as 0 for single-page documents, and it returned 0 for every passage of the two-page PDF, so the page shows page numbers only when the search reports one. Filters match values exactly, and the web page only turns key="value" pairs joined by AND into buttons. Anything else, such as OR or !=, is passed to the search as typed.
Further points follow from the described design, though the page does not state them as limits. The quote check confirms a quote is in its passage, and an answer needs at least one valid quote. The page does not say it checks that every claim in the answer is supported by a quote. Only six passages are retrieved per question, so an answer needing more is not described. The eval is 20 questions over six short documents. Seventeen cases check retrieval rank and citation against an expected file and phrase; three check unanswered questions. The question wording is not provided on this page. Eval requests that fail are left out of the totals and listed at the end. Quality on large, long or messy document sets is not assessed on the page. The selected page describes a TypeScript implementation requiring Node.js 22.13 or later; availability in other languages is unknown.
Why the design choices make sense
The page gives its own reasons for each choice. It searches first and then passes passages to Grok, instead of using the built-in search tool, because that makes the search the same every time, which is what the eval checks, and because the tool cannot take filters. Quotes come before the answer in the schema so Grok selects evidence before writing, and because Grok writes fields in schema order, the quotes are finished once the answer starts and can be checked before any answer text is shown. Low reasoning effort is used because copying quotes from six short passages does not need more, and it starts quoting within a few seconds. 500-character chunks are used so each short policy gives about one section per passage.
These are reasonable engineering trade-offs for a small, well-structured document set. The page gives no comparison against other chunk sizes, reasoning levels or retrieval settings, so how much each choice matters is not shown.
Alternatives
The only alternative the page discusses is Grok's built-in collectionsSearch() tool, which lets the model search a collection itself. The page says it rejected that for this app because the tool does not accept filters and returns less metadata. Whether that has changed is unknown.
Other ways to build cited document Q&A exist, such as other model providers, retrieval libraries or hosted search services. The page does not compare them. The main reasons to prefer this example are that it is built on the Grok API and shows the whole path from ingestion to a checked, cited answer. The main reasons to look elsewhere are if you do not use xAI, need your documents to stay on your own systems, or need a language other than TypeScript.
Evidence base
The resource is the selected page at [https://docs.x.ai/cookbook/examples/docs-to-cited-answers.md], a first-party xAI documentation page. It provides prose descriptions of the example's setup, code paths and behaviour, together with results the authors report from their own runs.
The page's claims about timing, token use, cost and eval results are the authors' own. The page does not include implementation files, raw evaluation output or licence text. Independent runtime and performance verification is unknown. The linked pages (the Management API guide, the metadata documentation and the console) are outside the selected scope.
Access & freshness
Costs
The page says an answer takes 3 to 8 seconds: about half a second for search, a few seconds of reasoning, then the quotes and answer. Grok reads about 1,100 tokens and writes 150 to 350, mostly reasoning, which the page puts at about $0.003 per answer at grok-4.7's list prices. The page and terminal show the token count and cost the API reports for each answer. The search does not report a cost of its own. The eval run takes 25 to 45 seconds, uses about 25,000 tokens and costs about 6 cents at list prices.
The page does not state grok-4.7's list prices, so the per-token rates cannot be checked from this page. Unknown: any charge for storing documents in collections, for search calls, for file uploads or for the Management API, and any free allowance or rate limits (the page only mentions that rate limits can make eval requests fail). Each ingest run creates a new collection, which you have to delete in the console yourself, so repeated runs leave collections behind. The cost of an unused collection is not stated. No licence or software fee is mentioned.
Rights and licence
The page states no licence, copyright notice or terms of use for the example code or the sample handbook, so reuse rights are unknown. The page names examples/docs-to-cited-answers/typescript, but does not identify its repository or provide a licence. Check the repository's licence and xAI's API terms before copying code into a product.
Using the app means uploading your files to xAI through the Files API and adding them to an xAI collection, and sending retrieved passages and your questions to grok-4.7. The page does not describe retention, training use, access controls or data location for uploaded documents. Check xAI's terms and privacy documentation before using confidential or regulated documents.
Freshness
The page was captured on 2026-11-14. It carries no publication or update date and no version number for the example. It names grok-4.7, the SpaceXAI Console and Node.js 22.13 or later, which reflects the state when it was written. The pricing figures are "list prices" at an unstated time. xAI model names, API behaviour (including the filters limitation on the built-in tool and the page_number behaviour) and console menu paths can change. Re-check them against current xAI documentation before depending on them.
Suggested next steps
If you use the Grok API, read the page, then run the sample handbook first (npm install, npm run ingest, npm run web) before using your own files. Create the management key with only the permissions the page lists, and delete test collections in the console afterwards. Run npm run eval to see the retrieval and citation figures on your own account. Then try your own documents, with a few questions that your documents do not answer, to see that "I couldn't find that in your documents." appears.
Before using real documents, check the repository licence, xAI's data-handling terms and current grok-4.7 pricing, and any storage or search charges for collections. If your answers depend on every claim being supported, consider adding a check beyond the one-valid-quote rule the page describes.
