Skip to main content
Special thanks to Rohan Deshpande for the original implementation of this agent during his time at Cerebras!
Reading and reasoning over long documents like academic papers or legal texts presents a major challenge for AI due to the context window limitations of Large Language Models (LLMs). To solve this, we will build an agent that implements Gist Memory, a technique developed by Google DeepMind that mimics human reading patterns. Instead of ingesting a whole document at once, the agent intelligently breaks it into pages, creates high-level summaries (“gists”) of each one, and then selectively re-reads only the most relevant sections to answer questions. The agent’s workflow is entirely self-contained. It begins with a single ArXiv URL and processes it in memory through a structured sequence of steps. It first parses the document into clean text, then paginates it into semantic episodes. From there, it generates a concise gist for each page, creating a dual-memory structure: the full-text original pages and a parallel list of their corresponding summaries. This allows the agent to hold a compressed version of the entire document in memory. At the heart of this agent is the Gist Memory technique, which relies on two key LLM-driven stages: intelligent pagination to create coherent chunks and interactive lookup to retrieve relevant information on demand. This multi-step process requires dozens of sequential LLM calls, making fast inference essential for a responsive user experience. To handle document ingestion, we leverage a helper script that converts ArXiv papers into a clean HTML format using the ar5iv service. In this cookbook recipe, we’ll walk you through how to build this Gist Agent step by step.

Architecture Overview

The agent’s architecture can be understood as a sequence of four internal modules that work together to read, remember, and reason about a long document:
  • Parser: Fetches an ArXiv paper, converts it to HTML, and extracts a clean list of paragraphs for processing.
  • Paginator: Breaks the long list of paragraphs into semantically coherent “pages” by using an LLM to identify natural breakpoints in the text.
  • Summarizer: Reads each page and generates a concise “gist” to be stored in the agent’s memory.
  • Q&A Engine: When asked a question, it first consults the list of gists to decide which pages are relevant, retrieves the full text for only those pages, and then generates an answer based on the enriched context.
For the entire codebase of this project, please visit its directory in our cookbook repository.

Prerequisites

Before getting started, please ensure that:
  • You have installed the Cerebras Inference SDK
  • You have a Cerebras API key and have saved it as an environment variable as such:

Step 1: Parse Arxiv Papers

Before the agent can read a document, it needs clean, machine-readable text. The arxiv_parser.py script handles this by fetching an academic paper from ArXiv and converting it into a simple list of paragraphs. Since parsing PDFs is difficult, the script uses a clever workaround: it transforms the ArXiv link into its corresponding ar5iv HTML version, which is much easier to process with standard tools. The parser’s logic is built around a few key functions:
  • get_ar5iv_link(url): This function takes a standard ArXiv URL for a PDF or abstract page and converts it into the equivalent ar5iv.labs.arxiv.org HTML link. It uses a regular expression to extract the paper’s unique ID to build the new URL.
  • get_html_page(url): To avoid re-downloading the same paper, this function fetches the HTML and saves it to a local html_cache directory. On subsequent runs, if the file exists in the cache, it’s read directly from the disk.
  • get_paragraphs_from_html(html): This function does the main work of text extraction. Using the BeautifulSoup library, it finds all paragraph elements in the HTML. It also includes a crucial preprocessing step for scientific content: it finds all mathematical formula tags (<math>) and replaces them with their readable LaTeX alttext, wrapped in $ symbols so the LLM can understand them.
The final output of this script is a clean list of text paragraphs, ready to be passed to the main agent for the next stage: pagination.

Step 2: Intelligent Pagination

Once the document is parsed into paragraphs, the next step is to group them into coherent “pages.” Instead of creating naive, fixed-size chunks that might awkwardly split a sentence or idea, the agent uses an LLM to find logical breakpoints. This process, called Episode Pagination, is handled by the _get_next_page_break method. The pagination logic works as follows:
  • Accumulate and Mark Text: The agent gathers paragraphs into a chunk of about 600 words. After a certain threshold, it begins inserting numbered labels (e.g., <57>) between paragraphs . These labels correspond to the paragraph’s index in the full document.
  • Ask the LLM for a Breakpoint: This chunk, now containing embedded labels, is sent to the LLM. The prompt asks the model to choose the label that marks a “natural” place to break reading, such as a narrative transition or the end of an argument .
  • Set the Page Boundary: The agent parses the LLM’s response to extract the chosen label (e.g., <57>). If the label is valid, that paragraph index is used as the end of the current page. If the LLM fails to provide a valid break, the agent defaults to ending the page at the end of the accumulated chunk.
This iterative process is repeated until the entire document is divided. The result is a list of pages stored in self.pages, where each page is a semantically coherent section of the paper, ready for the next step.

Step 3: Summarization (Memory Gisting)

With the document now organized into coherent pages, the next step is to create a concise summary for each one. These summaries, or “gists,” form the agent’s Gist Memory—a condensed, high-level version of the entire document that can be quickly scanned later. This process is handled by the _create_summary method. The summarization logic for each page is straightforward:
  • The agent takes the full text of a page and inserts it into a simple, direct prompt defined by PROMPT_SHORTEN_TEMPLATE. This prompt instructs the LLM to “Please shorten the following passage. Just give me a shortened version. DO NOT explain your reason” .
  • The LLM’s response is then cleaned by a helper function, _post_process_summary, which strips away any conversational filler (e.g., “Here is the shortened version:”) to ensure the gist is clean.
This process is repeated for every page in the document. At the end of this stage, the agent holds two parallel data structures in its memory: self.pages (a list of the original, full-text pages) and self.shortened_pages (a list of the corresponding gists). This dual-memory system is the core of the Gist Memory technique and is essential for the final question-answering stage.

Step 4: The Q&A Engine with Interactive Lookup

This final stage is where the agent uses its Gist Memory to answer questions about the document. Instead of overwhelming the LLM with the full text, the answer method orchestrates a two-step “lookup then answer” process that allows the agent to focus only on the most relevant information. The Q&A logic works as follows: The Lookup Stage: The agent first needs to decide which parts of the document to re-read.
  • It compiles all the gists into a single “memory” text, where each gist is labeled with its page number.
  • Using the PROMPT_LOOKUP_TEMPLATE, it presents this gist memory and the user’s question to the LLM. The prompt specifically instructs the model not to answer the question yet, but to instead identify which pages it needs to read in full to find the answer.
  • The agent parses the page numbers from the model’s response (e.g., “I want to look up Page [2, 5]…”).
The Answering Stage: With the relevant page numbers identified, the agent constructs a final, enriched context to generate the answer.
  • It starts with the list of all page gists.
  • It then iterates through the page numbers chosen during the lookup stage and replaces their gists with the original, full-text versions from self.pages. The result is a hybrid context containing high-detail excerpts where needed and low-detail summaries everywhere else.
  • Finally, using the PROMPT_FREE_ANSWER_TEMPLATE, the agent sends this hybrid context and the user’s question to the LLM to generate the final, fully-informed answer.
By following this process, the agent intelligently consults its memory to retrieve only the most pertinent details on demand, allowing it to provide accurate answers based on documents that are far too long to fit in a single context window.

Conclusion

In this tutorial, we built a Gist Agent capable of reading and reasoning about academic papers far longer than a typical LLM context window can support. By mimicking a human reader’s strategy of semantic pagination, summarization, and targeted lookup, the agent intelligently overcomes the context limitations of standard models. This project serves as a powerful example of how to solve complex problems by breaking them into smaller, manageable parts and using an LLM as a component in a larger workflow. The Gist Memory agent demonstrates a fundamental shift in designing AI systems. Instead of relying on a single, massive prompt, we created an algorithmic workflow where the LLM is called dozens of times sequentially to paginate, summarize, and retrieve information. The model’s output from one step, such as the list of gists, directly informs the input for subsequent steps, like the lookup stage. This iterative, memory-augmented architecture represents a more sophisticated and capable approach to building AI agents. This new class of agent architecture is only practical with access to high-speed, low-latency inference. Processing a single document can require over 20 LLM calls, with additional calls needed for each question asked. If each call took several seconds, the user would be left waiting for minutes, rendering the agent useless for interactive Q&A. Fast inference is therefore not just a performance enhancement; it is the core enabling technology that makes complex, multi-step agentic workflows like this one viable.