# Search to context (/docs/sdks/search/context)



A common pattern for RAG and agents is to [search](/docs/sdks/search/query), then expand each match with the [content around it](/docs/sdks/papers/context). You give the model a few relevant passages instead of whole papers.

<Mermaid
  chart="
flowchart LR
A[&#x22;Question&#x22;] --> B[&#x22;Search&#x22;] --> C[&#x22;Matching nodes&#x22;] --> D[&#x22;Context&#x22;] --> E[&#x22;Model&#x22;]
"
/>

## Build context from search results [#build-context-from-search-results]

<Tabs groupId="language" items="[&#x22;JavaScript&#x22;]">
  <Tab value="JavaScript">
    ```ts
    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");
    ```
  </Tab>
</Tabs>

Results are [reranked](/docs/sdks/search/query#expansion-and-reranking) by relevance, so the first few results are usually the best ones to expand.

## Use several results [#use-several-results]

Expand the top results and give the model all of them, each with its source.

<Tabs groupId="language" items="[&#x22;JavaScript&#x22;]">
  <Tab value="JavaScript">
    ```ts
    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"),
        };
      }),
    );
    ```
  </Tab>
</Tabs>

## Cite the source [#cite-the-source]

Every [node](/docs/core-concepts/graph) keeps its page and bounding box, so you can show users where an answer came from.

<Tabs groupId="language" items="[&#x22;JavaScript&#x22;]">
  <Tab value="JavaScript">
    ```ts
    for (const { id, page } of result.nodes) {
      console.log(`${result.paper.fileName}, page ${page}`);
    }
    ```
  </Tab>
</Tabs>
