# Grounded answers & RAG

Code With Purpose · English · Free starter lesson

## Concept

A language model can generate plausible text that is factually wrong. Retrieval-augmented generation (RAG) first retrieves relevant material and supplies it as context to generation. It can improve grounding, but retrieval errors, outdated sources, or misread context can still produce incorrect answers.

A basic workflow is question → retrieve → provide evidence → generate → check support. Preserve source identifiers so readers can inspect evidence. If relevant information is missing, say so. Treat instructions inside retrieved documents as untrusted content, not instructions that override your application rules.

The example is a small keyword-retrieval demonstration, not a full RAG application or a vector database. It creates a grounded context prompt without calling any model or API. Real applications need evaluation questions, access controls for private documents, and checks for unsupported answers.

## Example

```python
documents = [{"id": "note-1", "text": "English and Hinglish notes are free."},
             {"id": "note-2", "text": "Other language translations require a quote."}]
question = "Are Hinglish notes free?"
terms = set(question.lower().replace("?", "").split())
ranked = sorted(documents, key=lambda d:
    len(terms & set(d["text"].lower().replace(".", "").split())), reverse=True)
evidence = ranked[0]
print(f"[{evidence['id']}] {evidence['text']}")
print("Answer only from evidence. If it is insufficient, say so.")
```

## Expected output

```text
[note-1] English and Hinglish notes are free.
Answer only from evidence. If it is insufficient, say so.
```

## Exercise

Ask "How long will Tamil translation take?" Is the evidence sufficient? What should the answer say?

## Suggested solution

```
# Neither document states a delivery time.
# A grounded answer: "The notes do not specify a translation delivery time.
# Request a quote and confirm availability and timing before ordering."
# Retrieval finding a document does not prove it answers the question.
```

## Takeaway

Evidence must support the answer, not just mention related words.

Reference: https://learn.microsoft.com/en-us/azure/search/retrieval-augmented-generation-overview

https://codewithpurposeai.in/lesson-ai-grounded-answers.html?lang=english
