CertSafari
    Databricks Certified Generative AI Engineer Associate· Lessons

    Domain 3 · Lesson 18/56

    Augmenting prompts with intents, key fields and terms from user input

    Augment a prompt with additional context from a user's input based on key fields, terms, and intents

    19 min read
    2.31% of exam
    6 sources
    Published 22 Oct 2026
    Docs as of 17 Oct 2026

    What you will be able to do

    • Explain why a raw user message is usually a weak retrieval query, and what query understanding does about it
    • Classify a user query's intent and use that intent to route the request or choose a prompt template
    • Turn entities in a query, such as product, date or region, into metadata filters or tool lookups
    • Rewrite and expand vague or conversational queries so retrieval finds documents that use different terms
    • Assemble a prompt that holds the user query, resolved facts and retrieved chunks, and choose what to leave out

    Key concept

    Query understanding — A step at the start of the RAG chain that reads the user's message before retrieval. It works out what the user wants (intent), pulls out the concrete values that narrow the search (key fields), and turns loose wording into terms the knowledge base actually uses. Every later step works from what this step produces.

    1.Why the user's message is not yet a retrieval query

    A user writes the way people talk: "my usual store", "last quarter", "that error again". A knowledge base is indexed by product names, dates, regions and the terms used in its manuals. Sending the raw message straight to retrieval sometimes works. It fails when the meaning sits in a reference the index cannot resolve, or in a word the documents never use.

    For that reason, the RAG chain at inference time often starts with an optional preprocessing step that turns the message into a retrieval query. This step can put the query into a template, use another model to rewrite the request, or extract keywords to help retrieval. Retrieval then works from what this step returns, not from the user's original wording.

    Query understanding does three jobs, and each one augments the final prompt in a different way:

    • Intent: what the user wants done. This decides the route or the prompt template.
    • Key fields: values such as a product, a time period or a region. These become retrieval filters or arguments to a lookup.
    • Terms: the words used for search. They are rewritten or expanded so they match the documents' vocabulary.

    Each of these jobs is an ordinary model task pointed at the query itself rather than at a document. Intent is a classification task, and key fields come from an extraction task. The foundation model task types (chat, embeddings, vision, reasoning) lesson covers picking a model for that kind of task. What matters here is that the task runs on the user's message, before anything is retrieved.

    Checkpoint 1 of 9· Match them up

    Query understanding does three jobs on the user's message before retrieval. Match each job to how its output is used in the RAG chain.

    Tap a term, then the definition that fits it.

    Sources12

    2.Intent detection: deciding what the request is for

    Intent detection sorts the query into one of a fixed set of categories that you define for the application. A customer-support bot might use "product information", "troubleshooting" and "account management". The category matters because each one needs different context. A troubleshooting question needs passages from the error knowledge base. An account question needs the customer's record. A product question needs catalog data. Once the intent is known, the chain can pick the right prompt template, retriever or tool instead of sending every request down the same path.

    Intent also shapes what gets extracted next. With the intent "troubleshooting", the entities worth pulling out are product names and reported errors. With "account management", it is an account number. A common design runs these steps in order: classify the intent, extract entities based on that intent, then rewrite the query using both.

    A single, carefully written call is efficient, and for simple queries it is often enough. Once one prompt has to classify, extract and rewrite all at once, splitting it into one call per job usually works better. Each step gets its own instructions and can be checked on its own, at the cost of extra latency. This rule applies to any prompt that tries to carry several complex logic steps at once.

    A multi-step query understanding chain for a customer-support bot
    StepWhat the LLM call doesOutput passed on
    Intent classificationAssigns the query to a predefined category"product information", "troubleshooting" or "account management"
    Entity extractionExtracts the entities relevant to that intentProduct names, reported errors, account numbers
    Query rewritingRewrites the original query using the intent and entitiesA more specific and targeted retrieval query

    Checkpoint 2 of 9· Check yourself

    A support bot's first LLM call labels the message "I can't see my invoices since I changed my billing email" as "account management". What should the chain do next?

    Sources1

    3.Turning key fields into retrieval filters and lookups

    Key fields are the parts of a query that can narrow the search exactly. Examples are a time period ("reports from 2023"), a product or category ("laptops"), and a geographic entity such as a city name or country code. Filter extraction finds these values and passes them to retrieval as extra parameters. The similarity search then runs only over the matching subset of chunks. Filtering cuts the search space sharply and improves both precision and recall. A filter on make, model and year keeps a Camry brake question from pulling in Corolla manuals.

    The simplest extractor is deterministic code that looks for known values and builds a filter string. It is fast and predictable. However, it only catches values someone thought to code for.

    Rule-based filter extraction that builds a SQL-like filter string from the querypython
    # Parse query for filter criteria
    def extract_filters(user_query):
        filter_parts = []
        if "Toyota" in user_query:
            filter_parts.append('make = "Toyota"')
        if "2023" in user_query:
            filter_parts.append('year = 2023')
        return " AND ".join(filter_parts) if filter_parts else None

    The LLM-driven alternative hands extraction to the model. With dynamic_filter=True, a VectorSearchRetrieverTool lets the agent read "brake issues in my 2023 Toyota Camry". The agent then extracts the entities, generates the filter, and runs a search that combines semantic matching with exact filtering. The columns list matters here: the agent can only filter on metadata that the index holds.

    A retriever tool that generates metadata filters from the agent's reading of the querypython
    vector_search_tool = VectorSearchRetrieverTool(
        index_name="catalog.schema.car_manuals_index",
        # Optional: specify columns to return
        columns=["content", "make", "model", "year", "chunk_id"],
        # Optional: set number of results
        num_results=10,
        # Optional: use hybrid (keyword + vector) search
        query_type="HYBRID",
        # Enable LLM-generated filters based on the agent's understanding of the query
        dynamic_filter=True,
    )

    Each extracted value has to arrive in a form the index accepts. Standard endpoints take a Python dictionary in which the key holds both the column and the operator, and multiple keys are combined with AND. Storage-optimized endpoints take a SQL-like string, like the one extract_filters returns.

    From a phrase in the query to a standard-endpoint filter dictionary
    Phrase in the user queryExtracted fieldFilter
    "a Toyota or a Honda"make (string, OR){"make": ["Toyota","Honda"]}
    "the 2024 model"year (integer){"year": 2024}
    "under 55,000"price (numeric){"price <=": 55000}
    "listed in Q1 2024"listed_at (timestamp range){"listed_at >=": "2024-01-01T00:00:00Z", "listed_at <": "2024-04-01T00:00:00Z"}
    "in stock"in_stock (boolean){"in_stock": true}

    Some key fields do not name a document at all. They point to a record. "My usual store" means nothing to a vector index, but the application may already hold the user's default store ID. "Q3 EMEA revenue" is a set of rows in a revenue table, not a paragraph in a PDF. The knowledge base behind retrieval can be a vector store, a keyword search or a SQL database. An agent can also call tools for external data or actions, such as a function lookup_order(customer_id, order_id) when a user asks for their order status. In these cases the right move is to extract the field, resolve it against the system that holds the answer, and put the resolved value and the returned data into the prompt. For a stock check, that means the store ID and the current inventory for the SKU. For a revenue comparison, it means the EMEA figures for both quarters plus whatever an anomaly service flagged.

    Asking the user is a fallback, not the first step. When a lookup fails, for example when the tool replies "invalid order number", the agent can retry or ask the user for the correct ID. If the application can already resolve the reference from stored preferences or the query itself, a clarifying question before trying only adds a turn. Asking the model to guess the value is worse, because the prompt then carries a made-up fact.

    Checkpoint 3 of 9· Check yourself

    Your team changes the query-understanding prompt so the LLM pulls "EMEA" out of questions and passes {"region": "EMEA"} to the retriever. Answers still draw on chunks from every region. What is the most likely cause?

    Checkpoint 4 of 9· Check yourself

    A shopper asks, "Is the blue rain jacket in stock at my usual store?" Their profile holds a default store ID, and the agent has an inventory lookup tool. How should the chain build the prompt?

    Checkpoint 5 of 9· Exam question

    A retail chatbot receives: "Can you check if the blue XL hoodie is in stock at my usual store?" The application already has the user's stored preferences, including their default store ID and past purchase history. Which strategy best augments the prompt sent to the LLM so it can answer accurately?

    Checkpoint 6 of 9· Exam question

    A financial analyst assistant receives: "Compare Q3 revenue for our EMEA region against the same quarter last year, and flag anything unusual." The application has access to a structured revenue database and an anomaly-detection service. Which augmentation approach best prepares the prompt sent to the LLM?

    Sources13456

    4.Query rewriting and term expansion

    Query rewriting turns a user query into one or more queries that better express what the user meant, phrased so retrieval is more likely to find the right documents. It helps most when the query is complex or ambiguous, or when the user's words differ from the words in the documents. Typical rewrites include:

    • turning earlier turns of a multi-turn chat into a standalone question, so "what about the other one?" becomes something that can be searched;
    • correcting spelling mistakes;
    • replacing words or phrases with synonyms to reach more relevant documents.

    Rewriting works best after intent and entities are known. A support bot that has classified a message as troubleshooting, and has extracted "Model Serving" and the reported error, can produce a targeted query such as "My RAG chain is failing to deploy on Model Serving, I'm seeing the following error…". That query is far easier to search than the user's original wording.

    Query expansion searches with several versions of the query instead of one. There are two ways to use the variations. You can run a separate search for each one and merge the results, or you can join them all into a single retrieval query. The variations are usually generated in the query understanding step. That is why expansion needs changes in both places: the step that produces the variations and the retriever that consumes them.

    Expanding a query with LLM-generated synonyms, searching each variation, and deduplicatingpython
    # Use LLM to expand query with synonyms and related terms
    def expand_query(user_query):
        prompt = f"""Generate 3 variations of this search query including synonyms:
        Query: {user_query}
        Return only the variations, one per line."""
    
        variations = llm.generate(prompt).split('\n')
    
        # Search with original + variations
        all_results = []
        for query in [user_query] + variations:
            results = index.similarity_search(query_text=query, num_results=10)
            all_results.extend(results)
    
        # Deduplicate and return
        return deduplicate_results(all_results)

    Notice that the original query is kept alongside the variations. Expansion adds ways to match. It does not replace what the user wrote. The deduplication step matters because overlapping searches return the same chunk several times. Without it, the prompt would contain repeated passages.

    Checkpoint 7 of 9· Fill the gap

    This helper expands a query with LLM-generated synonyms before searching. Which token fills the blank so the loop searches the right set of queries?

    # Use LLM to expand query with synonyms and related terms
    def expand_query(user_query):
        prompt = f"""Generate 3 variations of this search query including synonyms:
        Query: {user_query}
        Return only the variations, one per line."""
    
        variations = llm.generate(prompt).split('\n')
    
        # Search with original + variations
        all_results = []
        for query in [ ? ] + variations:
            results = index.similarity_search(query_text=query, num_results=10)
            all_results.extend(results)
    
        # Deduplicate and return
        return deduplicate_results(all_results)

    Sources13

    5.Assembling the augmented prompt

    The augmented prompt is what the LLM actually receives. It combines the user's query with the retrieved context in a template that tells the model how to use each part, often with extra instructions about response format. Everything query understanding produced ends up here: the intent decides which template is used, the resolved key fields and tool results become stated facts, and the chunks found with the rewritten or expanded query become the context.

    A typical layout gives the model its role in the system message. The user message then contains the retrieved context first, followed by the instruction to answer the user's request using that context. For the support message "My Model Serving endpoint keeps returning 429 errors when I load test it", the chain extracts "Model Serving", "429 errors" and "load test", queries a retriever over the troubleshooting knowledge base, and puts the matching passages into the prompt before the user's question. Retrieval is what lets the answer draw on proprietary information that was never part of the model's training data.

    More context is not the same as better context. How many chunks to retrieve, and how to combine them with the query, can significantly affect answer quality. Three bad choices fail in different ways:

    • Dumping everything: an entire purchase history or a full revenue export for every region. The model has to find the relevant entities itself, and they get lost in the noise.
    • A static passage on every request: the same rate-limit paragraph added whatever the message says. The model talks about throttling even when the user reported a different failure.
    • No retrieval at all: relying on the model's pretrained knowledge for internal procedures. The answer cannot reflect the organisation's own knowledge base.

    The prompt that works holds only what this query needs: the resolved fields, the data looked up for them, and the passages found for the extracted terms.

    Checkpoint 8 of 9· Match them up

    Four teams build the augmented prompt for the same support bot in different ways. Match each design to the result it most likely produces.

    Tap a term, then the definition that fits it.

    Checkpoint 9 of 9· Exam question

    A support-ticket assistant receives the raw user message: "My Model Serving endpoint keeps returning 429 errors when I load test it." Before sending this to the LLM, a developer wants to extract the key terms ("Model Serving", "429 errors", "load test") and pull matching sections from an internal troubleshooting knowledge base to inject into the prompt. Which approach best accomplishes this prompt augmentation step?

    Sources25

    Sources

    (6)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “Using the user query directly as a retrieval query can work for some queries.”
      ↩︎ Why the user's message is not yet a retrieval query
      “Use an LLM to classify the user's query into predefined categories”
      ↩︎ Intent detection: deciding what the request is for
      “use another LLM call to extract relevant entities from the query, such as product names, reported errors, or account numbers”
      ↩︎ Intent detection: deciding what the request is for
      “Although this approach may add some latency to the overall process, it can allow for more fine-grained control”
      ↩︎ Intent detection: deciding what the request is for
      “Filter extraction involves identifying and extracting these filters from the query and passing them to the retrieval step as additional parameters.”
      ↩︎ Turning key fields into retrieval filters and lookups
      “Query rewriting involves translating a user query into one or more queries that better represent the original intent.”
      ↩︎ Query rewriting and term expansion
      “Replacing words or phrases in the user query with synonyms to capture a broader range of relevant documents”
      ↩︎ Query rewriting and term expansion
      “Use the extracted intent and entities to rewrite the original query into a more specific and targeted format”
      ↩︎ Query rewriting and term expansion
      “The multiple variations of a retrieval query are typically generated in this step.”
      ↩︎ Query rewriting and term expansion
      “Analyzing and transforming user queries to better represent intent and extract relevant information, such as filters or keywords, to improve the retrieval process.”
      ↩︎ Key concept
      “Filter extraction must be done in conjunction with changes to both metadata extraction data pipeline and retriever chain components.”
      ↩︎ Exam trap 1
      “either conducting individual searches for each expanded query, or using a concatenation of all expanded search queries in a single retrieval query”
      ↩︎ Exam trap 3
      “Analyzing and transforming user queries to better represent intent and extract relevant information, such as filters or keywords, to improve the retrieval process.”
      ↩︎ Checkpoint
      “Based on the identified intent, use another LLM call to extract relevant entities from the query, such as product names, reported errors, or account numbers.”
      ↩︎ Checkpoint
      “The metadata extraction step should ensure that the relevant metadata fields are available for each document/chunk”
      ↩︎ Checkpoint
    2. 2.
      “This can involve formatting the query within a template, using another model to rewrite the request, or extracting keywords to aid retrieval.”
      ↩︎ Why the user's message is not yet a retrieval query
      “augmenting the user's query with the retrieved context, in a template that instructs the model how to use each component”
      ↩︎ Assembling the augmented prompt
      “determining how many chunks to retrieve in step 2 and how to combine them with the user's query in step 3 can significantly impact”
      ↩︎ Assembling the augmented prompt
      “determining how many chunks to retrieve in step 2 and how to combine them with the user's query in step 3 can significantly impact”
      ↩︎ Exam trap 4
      “how many chunks to retrieve in step 2 and how to combine them with the user's query in step 3 can significantly impact”
      ↩︎ Checkpoint
    3. 3.
      “Filtering dramatically reduces search space and improves both precision and recall.”
      ↩︎ Turning key fields into retrieval filters and lookups
      “Impact: Improves recall by finding documents with different terminology.”
      ↩︎ Query rewriting and term expansion
    4. 5.
      “The user's request is used to query an outside knowledge base such as a vector store, keyword search, or SQL database.”
      ↩︎ Turning key fields into retrieval filters and lookups
      “RAG can include proprietary information not initially used to train the LLM”
      ↩︎ Assembling the augmented prompt
    5. 6.
      “If the user wants their order status, the agent might call a function lookup_order(customer_id, order_id).”
      ↩︎ Turning key fields into retrieval filters and lookups
      “Reason about how best to respond, optionally deciding whether to call tools for external data or actions.”
      ↩︎ Turning key fields into retrieval filters and lookups
      “the agent can retry or prompt the user for the correct ID”
      ↩︎ Exam trap 2
      “If that tool responds with "invalid order number," the agent can retry or prompt the user for the correct ID”
      ↩︎ Checkpoint

    Spotted a mistake, or was something unclear? Tell us.