Dynamic Prompting, or RAG Reversed

16 Jan 2025

Problem

The Sber LegalDocs team extracts legal facts from corporate documents so that Sber's patented legal decision system (the "robot lawyer") can make a decision. The facts form a tree, and every leaf must be right: a payment period must attach to the correct payment inside the correct loan deal. A fixed prompt with hand-picked examples works for small, simple structures. It gives weaker results when documents of the same type differ in structure, style and content. Picking examples by hand for each document type is routine analyst work.

Example from the article: extracting loan-deal terms (payment type, period, start date) from corporate protocols that approve a deal.

Solution in brief

Instead of fixed examples, the pipeline embeds the incoming document in chunks, finds the most similar labeled chunks in a vector database and puts them into the prompt as few-shot examples. The assumption is that similar documents are parsed similarly. New labeled documents are only added to the database, so the pipeline is not rebuilt.

Questions this case answers
  • How to select in-context examples automatically for an LLM extraction pipeline when documents of one type differ widely in structure and style
  • How to extract nested, hierarchical structured fields from long documents with an LLM while keeping the relations between fields
  • How to choose few-shot examples for an LLM extraction prompt without hand-picking them for every document type?
  • How to improve LLM fact extraction (NER) from long, structurally varied legal documents?

Tools and methods

  • Dynamic few-shot prompting — retrieve labeled example chunks similar to the input and insert them into the prompt
  • Cosine similarity over embeddings — the search criterion between the input chunk and stored chunks
  • E5 embedding model — vectorizes chunks; needs a rich vocabulary and fast inference
  • JSON tree output — the LLM answers with nested JSON that mirrors the fact hierarchy
Continue reading — it's free

Google or a one-time email code. No password.