Skip to content

DS 302 · Module 1

Data Agent Architecture: Intent, Tools, Data, and Semantics

Start by deciding when an agent is justified at all, translate a request into an analysis plan before executing anything, give the agent narrow allowlisted tools, ground its metrics in a trusted semantic layer, then build a verifiable read-only prototype in a Guided Lab.

Start Section 1
0 / 5 completed
Sync my progressJoin a session to keep progress across devices and share it with your instructor

Info

After you join, your completed lesson numbers are sent to your instructor together with your learner code, so they can see your progress. Use the codes your instructor gave you, and do not enter your name, company secrets or other personal data. Progress is kept with the rest of that session's data.

Learning objectives

  • Define when an agent is justified; distinguish natural-language interface from autonomous analytical action
  • Translate a request into entities, metrics, filters, time range, plan, evidence requirements, and approval needs
  • Use allowlisted tools with narrow schemas; separate read from write/action tools
  • Ground metrics, dimensions, definitions, join paths, units, and policy in a trusted semantic layer
  • Build a read-only prototype that plans, queries, executes Python if needed, cites dataset versions, and verifies totals

What Is a Data Agent? Chatbot vs BI vs Workflow

40 min

What Is a Data Agent? Chatbot vs BI vs Workflow

Learning objective: define when an agent is justified; distinguish natural-language interface from autonomous analytical action.

A department head types "why did conversion drop in June" into a chat box and expects a trustworthy, sourced answer within a minute. A fixed BI dashboard cannot answer an open-ended follow-up question; a chatbot with no data access can only guess; a scheduled workflow can only run the report it was built for. A Data Agent sits between these: it understands the request in natural language, plans which data and tools it needs, executes a bounded set of read (and sometimes write) actions, and returns an answer with evidence. That extra capability is also extra risk, so the first design decision is not "how do we build the agent" but "is an agent even justified for this request, or is a dashboard or a fixed workflow safer and sufficient."

Chatbot vs BI dashboard vs workflow vs Data Agent
SystemCan it answer a novel question?Can it access governed data/tools?Typical risk
Chatbot (no data access)Sounds fluent, but may hallucinate numbersNoConfidently wrong answers
BI dashboardOnly pre-built views/filtersYes, but fixed and pre-approvedCannot answer open-ended questions
Scheduled workflowNo, runs the same steps every timeYes, but narrowly scoped to one jobNot flexible; still safe and auditable
Data AgentYes, plans dynamically per requestYes, through governed, permissioned toolsNeeds explicit verification, permissions, and approval controls
This course's dataset (a governed analytics sandbox queried through the agent)
import pandas as pd

# clean: a read-only query log against the governed analytics sandbox this course uses
df = pd.read_csv("DS302_Analytics_Package_Clean.csv", parse_dates=["event_time", "ingested_at"])
df.shape
df.dtypes
df[["run_id", "source_system", "batch_id", "metric", "value", "schema_version"]].head()

# Ask first: is a dynamically planned agent even needed here, or would a fixed dashboard answer this?
df["source_system"].unique()

Chatbot bolted onto data

"Just connect the chatbot to the database and let it answer anything." Nobody has decided which questions genuinely need dynamic planning, which tools it may call, or what evidence a trustworthy answer requires.

Justified Data Agent

Need for dynamic planning
The request genuinely varies enough that a fixed dashboard or workflow cannot cover it.
Governed access
The agent can only reach data/tools through explicit, permissioned interfaces, never raw unrestricted access.
Verifiable answers
Every answer can be traced back to a specific query, dataset version, and definition.
  • The scope of the question changes almost daily, and a new question cannot be assembled from an existing dashboard's filters.
  • The team needs to dynamically decide which of several data sources to check, rather than always querying the same fixed table.
  • The answer must cite a traceable query and dataset version, not just a single number.
  • The task has branching logic that requires human approval before it runs; a scheduled workflow cannot express that kind of conditional check.
  • If a fixed dashboard, report, or workflow can already answer most questions in an acceptable amount of time, an agent is not needed; adding one only adds a layer of risk without a matching benefit.
A real scenario: is an agent actually justified here?

A finance team asks every week which source system has the lowest batch completion rate, but the fields, time range, and source_system list they care about change almost every time. A fixed dashboard would need a pre-built view for every combination, which is expensive to maintain; this is the kind of scenario dynamic planning is built for, but the agent still needs narrow, read-only tools, not access to the whole database.

Info

Human, AI, Human: a person decides whether a request justifies an agent at all and which tools it may use; the agent plans and executes within those bounds; a person verifies the answer and remains responsible for decisions made from it.
Check yourself

A team wants to let a chatbot answer any question about their production database by giving it a general-purpose SQL tool with no restrictions. What is most fundamentally missing from this plan?

A team wants to let a chatbot answer any question about their production database by giving it a general-purpose SQL tool with no restrictions. What is most fundamentally missing from this plan?

Key takeaway: Completing the steps is not enough; the result must be verifiable, reproducible, and explainable.

Intent → Analysis Plan: Plan Before Execution

45 min

Intent → Analysis Plan: Plan Before Execution

Learning objective: translate a request into entities, metrics, filters, time range, plan, evidence requirements, and approval needs.

A learner asks the agent "how are we doing this quarter" and the agent immediately fires off a query. Doing what, for whom, over what date range, compared against what baseline? A vague request executed immediately produces a vague, unverifiable answer. Before an agent calls any tool, it should turn the request into an explicit analysis plan: which entities and metrics are involved, what filters and time range apply, what steps will produce the answer, what evidence is required to trust the result, and whether any step needs human approval before it runs.

From a vague request to an explicit analysis plan
# Vague: no plan, straight to execution
# "how are we doing this quarter" -> agent guesses a query and returns a number

# Planned: the request is decomposed before anything executes
plan = {
    "entities": ["source_system"],
    "metrics": ["conversion_rate", "active_users"],
    "filters": {"schema_version": "v2"},
    "time_range": "2026-Q2",
    "steps": ["load current-quarter rows", "validate against contract", "aggregate by source_system"],
    "evidence_required": ["row count", "dataset_version", "definition of conversion_rate"],
    "approval_needed": False  # read-only aggregate; would be True for a write/publish action
}
Six things a plan must resolve before execution
ElementQuestion it answers
EntitiesWhich dimensions (source system, department, time) does the question concern?
MetricsWhich trusted, defined metrics answer the question?
FiltersWhich subset of rows is actually in scope?
Time rangeWhat period, and compared against what baseline?
Evidence requirementsWhat must the answer cite to be trustworthy (row counts, dataset version, definitions)?
Approval needsDoes any step require human sign-off before it runs?
  1. Restate the request as a question
    Turn free text into a specific, checkable question before choosing any tool.
  2. Resolve entities, metrics, filters, time range
    Fill in each element explicitly; if information is missing, ask instead of guessing.
  3. List evidence requirements
    Decide up front what the final answer must cite to be considered trustworthy.
  4. Flag approval needs
    Mark any step that writes, publishes, or has consequential impact as needing human approval.
  • Interpreting "this quarter" as whatever 90-day window the agent picks, instead of the period the finance calendar actually defines.
  • Reusing one department's definition of "users" when a different department asked the question with its own definition in mind.
  • Presenting a single aggregated number as the final answer without ever requiring any evidence for it.
  • Quietly filling in a "reasonable-sounding" assumption for an underspecified request instead of asking the requester to clarify.
Before and after planning

The request "how is conversion this quarter" only becomes executable and verifiable once it is turned into entities=["source_system"], metrics=["conversion_rate"], filters={"schema_version": "v2"}, time_range="2026-Q2". Without even fixing schema_version, running the same question at different times could return two answers that cannot be compared.

Warning

An agent that executes before planning is not "faster", it is unverifiable. If nobody can point to which entities, metrics, filters, and evidence the answer rests on, the answer cannot be trusted regardless of how confidently it is phrased.
Check yourself

A learner asks a Data Agent "how are we doing this quarter" and the agent immediately returns a single number with no explanation. What is the most important thing missing?

A learner asks a Data Agent "how are we doing this quarter" and the agent immediately returns a single number with no explanation. What is the most important thing missing?

Key takeaway: Completing the steps is not enough; the result must be verifiable, reproducible, and explainable.

Tool Layer: SQL, Python, Retrieval, and APIs

45 min

Tool Layer: SQL, Python, Retrieval, and APIs

Learning objective: use allowlisted tools with narrow schemas; separate read from write/action tools.

A colleague gives the agent one general-purpose "run_sql" tool that accepts any query string, so it can also read it can also DROP a table, or read tables it was never meant to touch. A narrow tool layer is the boundary that keeps a Data Agent's capability matched to what was actually approved: instead of one all-powerful SQL tool, the agent gets several narrow tools, each with an explicit schema, a stated purpose, and a fixed read-only or write/action classification.

From one unrestricted tool to narrow, allowlisted tools
# Wrong: one tool that accepts arbitrary SQL, read or write, any table
def run_sql(query: str) -> pd.DataFrame:
    return db.execute(query)  # no allowlist, no read/write separation

# Right: narrow, purpose-built, read-only tools with explicit schemas
def query_metric_summary(source_system: str, metric: str, time_range: str) -> pd.DataFrame:
    """Read-only. Only queries the pre-approved analytics_sandbox view."""
    ALLOWED_SOURCE_SYSTEMS = {"crm", "billing", "support", "web_analytics", "ops"}
    if source_system not in ALLOWED_SOURCE_SYSTEMS:
        raise ValueError(f"source_system not allowlisted: {source_system}")
    return sandbox_view.query(source_system=source_system, metric=metric, time_range=time_range)

def publish_report(report_id: str, content: dict) -> None:
    """Write/action tool. Requires human approval before it runs (see Lesson 9)."""
    raise PermissionError("publish_report requires an approved run; see approval workflow")
Why narrow tool schemas reduce risk
Risk of a broad toolHow a narrow schema helps
Unintended write/delete through a "read" requestRead and write/action tools are separate functions with separate permissions
Query against an unapproved table or sourceAn explicit allowlist rejects anything outside the approved scope
Unpredictable parameters an agent could passA narrow, typed schema limits what the agent can even attempt to pass
No way to audit which tool caused a problemEach tool call is individually named and logged
  • Each tool does exactly one clearly named thing; the name itself states its scope.
  • Read tools and write/action tools are separate functions with their own permissions and their own allowlists.
  • Parameters use explicit types and enums instead of free-form strings that let the agent assemble its own query conditions.
  • Anything not explicitly approved, a source system, a table, a column, is denied by default rather than allowed by default.
  • Every tool call is logged with the caller, the parameters, and the dataset version, so it can be audited afterward.
A tool catalog that was split apart

Instead of one run_sql tool, this course's sandbox exposes three separate tools: query_metric_summary (read-only), list_source_systems (read-only), and publish_report (write/action, requires approval). Each has its own schema and classification, so the agent cannot use one tool to do what only another tool is approved to do.

Warning

A single "do anything" tool is convenient to build and dangerous to operate. If a tool's name does not describe exactly what it is allowed to touch, assume it is too broad.
Check yourself

An agent is given one general-purpose "run_sql" tool that can execute any query, read or write, against any table. What is the main risk of this design?

An agent is given one general-purpose "run_sql" tool that can execute any query, read or write, against any table. What is the main risk of this design?

Key takeaway: Completing the steps is not enough; the result must be verifiable, reproducible, and explainable.

Semantic Layer and Trusted Metrics

45 min

Semantic Layer and Trusted Metrics

Learning objective: ground metrics, dimensions, definitions, join paths, units, and policy in a trusted semantic layer.

Two departments ask the agent for "conversion rate" and get two different numbers, because one team's query includes refunded orders and the other's does not, and nobody wrote either definition down. Without a shared semantic layer, an agent free to invent its own SQL will silently invent its own definition of every metric, every time. A semantic layer fixes metric formulas, dimension definitions, join paths, units, and access policy in one place the agent must consult instead of guessing.

Metrics resolved through a semantic catalog instead of ad hoc SQL
SEMANTIC_METRICS = {
    "conversion_rate": {
        "formula": "converted_sessions / total_sessions",
        "unit": "ratio (0-1)",
        "owner": "analytics-platform-team",
        "grain": "source_system x batch_id"
    },
    "active_users": {
        "formula": "count(distinct entity_id where last_event <= 30 days)",
        "unit": "count",
        "owner": "analytics-platform-team",
        "grain": "source_system x batch_id"
    }
}

def resolve_metric(name: str) -> dict:
    if name not in SEMANTIC_METRICS:
        raise ValueError(f"metric not in semantic layer, cannot resolve a trusted definition: {name}")
    return SEMANTIC_METRICS[name]
What a semantic layer fixes so the agent does not improvise it
ElementWhy it must be fixed centrally
Metric formulasThe same metric name must mean the same calculation everywhere
Dimension definitionsCategories like "active" or "current quarter" must have one agreed meaning
Join pathsThe agent should not invent how tables relate to each other
UnitsA ratio reported as a percentage versus a fraction changes the answer by 100x
Access policyWhich roles may see which metrics/dimensions is enforced in the same place the definitions live

No semantic layer

  • Every team, sometimes every query, redefines the same metric name on its own.
  • Join paths are guessed by the agent, and different runs may relate tables differently.
  • Units get mixed (a ratio versus a percentage), and the answer can be off by 100x without anyone noticing.

Trusted semantic layer

  • Metric formulas, owners, and grain are defined centrally, so every query resolves to the same source.
  • Join paths are fixed by the semantic layer; the agent can only pick an approved path.
  • Units and access policy live alongside the definitions and are enforced consistently.
A discrepancy caused by no semantic layer

The billing team defines conversion_rate as converted_sessions / total_sessions, while marketing excludes refunded orders from the denominator; two reports presented to leadership the same day show different numbers. After adopting the semantic layer's resolve_metric, both teams' queries have to resolve through the same formula, and the discrepancy disappears.

Info

When an agent can only resolve a metric through the semantic layer, "conversion_rate" means the same thing no matter which department, session, or agent run asked for it.
Check yourself

Two departments ask a Data Agent for "conversion rate" on the same day and receive two different numbers, because the agent wrote a fresh SQL query each time. What is the underlying design gap?

Two departments ask a Data Agent for "conversion rate" on the same day and receive two different numbers, because the agent wrote a fresh SQL query each time. What is the underlying design gap?

Key takeaway: Completing the steps is not enough; the result must be verifiable, reproducible, and explainable.

Guided Lab: Verifiable Read-Only Data Agent

65 min

Guided Lab: Verifiable Read-Only Data Agent

Learning objective: with instructor guidance, build a read-only prototype that plans, queries, executes Python if needed, cites dataset versions, and verifies totals.

Info

Lab question: if a colleague asked your prototype the same question twice, would it produce a plan, a query, a dataset version, and a verification step every time, or would it just return a number?
  1. Plan
    Given a sample request, write out the entities, metrics, filters, time range, and evidence requirements before writing any query.
  2. Query (read-only)
    Call only the narrow, allowlisted read tool against the sandbox; never a general-purpose query tool.
  3. Execute Python if needed
    If aggregation is needed beyond the tool's own output, isolate it into a small, explicit function.
  4. Cite dataset version
    Record schema_version and the row count actually used, alongside the answer.
  5. Verify totals
    Cross-check at least one total (such as a row count or sum) against an independent expectation before presenting the answer.
Minimum content the Guided Lab should include (fill in your own results)
ItemWhat to report
Analysis planThe entities, metrics, filters, time range, and evidence requirements you wrote before querying
Read-only tool callWhich narrow tool you called and what allowlist it enforced
Dataset version citedThe schema_version and row count your answer is based on
Verification performedThe independent check you ran before trusting the total
Still needs human judgmentAt least one assumption or decision that still needs business confirmation
  • Presenting an aggregated number without recording the schema_version or row count behind it.
  • Running the query once and assuming it is correct, without a second independent check on the total.
  • Treating "the code ran without an error" as proof the logic is correct, without actually checking whether the output is plausible.
  • Skipping the self-check of whether someone else could re-run this and get the same answer.

Warning

"The query ran and returned a number" does not equal "the answer is verified." Every prototype answer needs a cited dataset version and an independent verification step, or it is not yet trustworthy.

Done

Before finishing, ask yourself: could someone else re-run your prototype's plan and query on the same dataset version and reach the same verified answer?
Check yourself

You finished the Guided Lab and your prototype returns an answer with a plan and a cited dataset version, but you never checked the returned total against an independent expectation. Does this count as completing this lesson's core skill?

You finished the Guided Lab and your prototype returns an answer with a plan and a cited dataset version, but you never checked the returned total against an independent expectation. Does this count as completing this lesson's core skill?

Key takeaway: Completing the steps is not enough; the result must be verifiable, reproducible, and explainable.

What next?