# Grounding in context (/use-cases/data-agents/grounding-in-context)



Data agents need your table history and business definitions to write reliable SQL. Add validated queries, table metadata, and business rules to the agent's knowledge. Ask the agent to retrieve relevant context before writing SQL.

```bash
uv pip install "agno[openai,pgvector,psycopg,sql]"
```

Set `OPENAI_API_KEY` in the environment before running the Python code. Replace the warehouse URLs with your own PostgreSQL connection strings and create the database roles, schemas, and grants described on this page first. The host `warehouse`, database `analytics`, and roles such as `readonly` and `dash_writer` are placeholders.

Examples using `PostgresDb` or `PgVector` also need a separate writable application database. The sample URL assumes a PostgreSQL service at `localhost:5532` with database/user/password `ai`; knowledge examples need the pgvector extension. See [PgVector setup](/knowledge/vector-stores/pgvector/overview). Keep this application's storage credentials separate from the restricted warehouse role.

```python
from agno.agent import Agent
from agno.knowledge.knowledge import Knowledge
from agno.models.openai import OpenAIResponses
from agno.tools.sql import SQLTools
from agno.vectordb.pgvector import PgVector

knowledge = Knowledge(
    vector_db=PgVector(table_name="dash_knowledge", db_url="postgresql+psycopg://ai:ai@localhost:5532/ai"),
)
knowledge.insert(
    name="Active subscriptions",
    text_content=(
        "Business rule: a subscription is active when ended_at IS NULL. "
        "Validated query pattern: SELECT plan, count(*) FROM subscriptions "
        "WHERE ended_at IS NULL GROUP BY plan."
    ),
)

agent = Agent(
    model=OpenAIResponses(id="gpt-5.5"),
    tools=[SQLTools(db_url="postgresql+psycopg://readonly@warehouse/analytics")],
    knowledge=knowledge,
    search_knowledge=True,
    instructions="Retrieve relevant query patterns and table notes before writing SQL.",
)

agent.print_response("How many active subscriptions are on the Pro plan?")
```

With `knowledge` attached, `search_knowledge=True` exposes a search tool by default. The model chooses whether to call it. Instructions can request retrieval before SQL; if retrieval must happen for every request, perform it in application code before the run and supply its results. Set `search_knowledge=False` to remove the search tool.

## Context to curate [#context-to-curate]

A production data agent grounds each answer in several layers. The first set is curated and stored in a vector database. The rest are live.

| Layer                   | Source                                               | Curated?                                                                          |
| ----------------------- | ---------------------------------------------------- | --------------------------------------------------------------------------------- |
| Validated queries       | Known-good SQL for common questions                  | Yes, in `knowledge`                                                               |
| Table metadata          | What each table and column actually means            | Yes, in `knowledge`                                                               |
| Business rules          | Definitions: what "active", "MRR", "churn" mean here | Yes, in `knowledge`                                                               |
| Institutional knowledge | An MCP server into your wiki or docs                 | Live                                                                              |
| Learnings               | Fixes the agent captured from past errors            | Live, see [Self-correcting agents](/use-cases/data-agents/self-correcting-agents) |
| Runtime schema          | `describe_table` at query time                       | Live                                                                              |

## Start with validated queries [#start-with-validated-queries]

Validated queries give the agent a trusted starting point for recurring questions such as monthly recurring revenue. For a related request, the agent can retrieve a known-good query and adapt its structure. Store the question, SQL, tables used, and data-quality notes for queries your analysts already trust.

## Grounding vs raw text-to-SQL [#grounding-vs-raw-text-to-sql]

| Raw text-to-SQL                        | Grounded data agent                       |
| -------------------------------------- | ----------------------------------------- |
| Guesses column meaning from names      | Reads curated table metadata              |
| Generates each query from schema alone | Adapts a validated query when one matches |
| Infers business meaning                | Applies curated business definitions      |
| Depends on implicit assumptions        | Uses retrieved rules and query patterns   |

## Next steps [#next-steps]

| Task                             | Guide                                                                   |
| -------------------------------- | ----------------------------------------------------------------------- |
| Capture fixes as durable context | [Self-correcting agents](/use-cases/data-agents/self-correcting-agents) |
| Run the SQL safely               | [Safe data access](/use-cases/data-agents/safe-data-access)             |

## Developer Resources [#developer-resources]

* [Knowledge](/knowledge/overview)
* [Dash: six layers of context](/deploy/templates/dash/overview)
