Search
Search to context
Turn search results into focused context for a model.
A common pattern for RAG and agents is to search, then expand each match with the content around it. You give the model a few relevant passages instead of whole papers.
Build context from search results
const question = "How did revenue change in Europe?";
const { items } = await paperful.search.query(question);
const [result] = items;
const graph = await paperful.papers.graph(result.paper.id);
const node = await graph.node(result.nodes[0].id);
const context = await node.context({ before: 3, after: 3 });
const text = context.map((n) => n.text).join("\n"); Results are reranked by relevance, so the first few results are usually the best ones to expand.
Use several results
Expand the top results and give the model all of them, each with its source.
const { items } = await paperful.search.query(question);
const passages = await Promise.all(
items.slice(0, 3).map(async (result) => {
const graph = await paperful.papers.graph(result.paper.id);
const node = await graph.node(result.nodes[0].id);
const context = await node.context({ before: 3, after: 3 });
return {
source: result.paper.fileName,
page: node.page,
text: context.map((n) => n.text).join("\n"),
};
}),
); Cite the source
Every node keeps its page and bounding box, so you can show users where an answer came from.
for (const { id, page } of result.nodes) {
console.log(`${result.paper.fileName}, page ${page}`);
}