AI Analysis

Inside OpenAI's In-House Data Agent: From Question to Insight in Minutes

OpenAI built a bespoke internal AI data agent that lets any employee - not just data engineers - go from natural language question to verified insight in minutes. The agent is powered by GPT-5.2, uses Codex to deeply understand table semantics from source code, retrieves context via RAG over 70k datasets (600 PB), and continuously self-improves through a layered memory system. The post breaks down its six-layer context architecture, conversational reasoning loop, eval-driven quality assurance, and key lessons in agent design.

Key takeaways

  • OpenAI’s internal data platform has over 3.5k users, 70k datasets, and 600 PB of data - finding the right table and writing correct SQL was the biggest bottleneck.
  • The agent uses six layers of context: table usage metadata, human annotations, Codex-derived code enrichment, institutional knowledge (Slack/Docs/Notion), a self-learning memory system, and live runtime queries.
  • Codex enrichment is the secret weapon - by crawling the pipeline code that produces each table, the agent learns what the data actually contains, not just its schema shape.
  • A continuously learning memory system stores corrections and non-obvious filters, so the agent improves with every interaction instead of repeating mistakes.
  • Lessons learned: fewer tools beat more tools (less ambiguity), high-level guidance outperforms prescriptive prompts, and a table’s true meaning lives in the code that produces it.

Why this comes up in interviews

AI agents are becoming a core system design topic. This post gives you a real production architecture for RAG-based data agents at scale - including how to layer context sources, build self-improving memory, evaluate agent quality, and handle the security model. Use these patterns when asked to design an AI assistant, a data platform, or any system that combines LLMs with structured data retrieval.

Why a custom data agent? The table discovery bottleneck

OpenAI’s data platform serves 3.5k internal users across 70k datasets totaling 600 petabytes. The hardest part of data analysis wasn’t writing queries - it was finding the right table. Many tables look similar but differ in subtle ways: one includes logged-out users, another doesn’t; fields overlap but have different semantics. Analysts spent hours figuring out which table to use before writing a single line of SQL. Even with the right tables, producing correct results required reasoning about joins (many-to-many joins silently duplicate rows), filter pushdown order, and null handling. A 180-line SQL statement might look correct but produce wrong numbers because of a subtle join condition. OpenAI built a bespoke agent - not a generic chatbot - tailored to their specific data, permissions, and workflows to eliminate this bottleneck.

Interview angle

When designing a data platform, interviewers probe whether you understand the human bottlenecks, not just the technical ones. “Finding the right table” is a metadata discovery problem - and it’s where most data platforms fail. Strong candidates mention data catalogs, semantic search over schemas, and lineage tracking as solutions.

The six-layer context architecture

The agent’s accuracy depends entirely on context quality. Without it, even GPT-5 produces wrong results - misestimating user counts or misinterpreting internal terminology. OpenAI designed six layers of context, each filling a gap the previous layers can’t cover. Layer 1 (Table Usage): schema metadata like column names and types plus historical query patterns that reveal how tables are typically joined. Layer 2 (Human Annotations): curated descriptions from domain experts capturing business meaning, intent, and known caveats that can’t be inferred from schemas. Layer 3 (Codex Enrichment): code-level definitions derived by crawling the pipeline source code with Codex - revealing what data a table actually contains, its update frequency, granularity, and scope. Layer 4 (Institutional Knowledge): documents from Slack, Google Docs, and Notion containing launch context, incident reports, internal codenames, and canonical metric definitions. Layer 5 (Memory): corrections and learnings saved from previous conversations that persist across sessions. Layer 6 (Runtime Context): live queries to the data warehouse when no prior context exists or existing context is stale.

Diagram showing the six layers of context: table usage, human annotations, Codex enrichment, institutional knowledge, memory, and runtime context feeding into the GPT-5.2 agent
The six-layer context architecture. Each layer fills gaps the others can’t cover - from stable schema metadata at the bottom to live warehouse queries at the top.

Interview angle

This is a masterclass in RAG architecture design. Interviewers love asking “where does the context come from?” The strong answer layers multiple sources by reliability and freshness: static metadata → human curation → code analysis → organizational knowledge → learned corrections → live data. Each layer compensates for the blind spots of the ones above it.

Codex enrichment: meaning lives in code, not schemas

Schema metadata tells you column names and types. Query history tells you how a table is used. But neither tells you what the data actually means. OpenAI uses Codex to crawl the pipeline source code that produces each table, extracting a code-level definition that captures: what transformations are applied, how often the data refreshes, what scope the data covers (e.g., “excludes internal test accounts”), what level of granularity it provides, and how values are computed. This is the key differentiator. Two tables might have identical schemas - same column names, same types - but one excludes logged-out users and the other includes them. That distinction only exists in the ETL code that populates them. By making pipeline logic legible to the agent, Codex enrichment also shows how tables are used beyond SQL - in Spark jobs, Python scripts, and other data systems. This context refreshes automatically as code changes, so it stays current without manual maintenance.

Interview angle

If asked “how would you help analysts distinguish between similar tables?”, most candidates say metadata or documentation. The strong answer is: analyze the pipeline code that produces each table. This is the same principle behind data lineage tools like dbt’s documentation layer. Interviewers test whether you understand that schema is shape, but code is semantics.

Self-learning memory: corrections that persist

Memory is the layer that makes the agent improve over time instead of repeating the same mistakes. When a user corrects the agent - for example, teaching it that a specific analytics experiment requires matching against a particular string in an experiment gate, not a fuzzy match - the agent prompts the user to save that correction. Future conversations start from this improved baseline. Memories are scoped at two levels: global memories apply to all users (e.g., “this table excludes bot traffic”), and personal memories apply only to the individual user (e.g., “when I ask about growth, I mean week-over-week”). Users can also manually create and edit memories. The key design principle is that memory stores non-obvious constraints - the kind of filters and business rules that are critical for correctness but nearly impossible to infer from schemas, code, or documentation alone.

Interview angle

Agent memory is a hot interview topic. The design question is: what should be remembered vs. re-derived? OpenAI’s answer: only persist non-obvious corrections that can’t be inferred from other context layers. This avoids memory bloat and staleness. Scoping by global vs. personal is also a clean pattern - it maps to the distinction between organizational knowledge and individual preferences.

Closed-loop reasoning: self-correcting analysis

The agent doesn’t follow a fixed script. It evaluates its own intermediate results and course-corrects. If a SQL query returns zero rows - likely due to an incorrect join or filter - the agent investigates what went wrong, adjusts its approach, and retries. It retains full context across these self-correction loops, carrying learnings forward between steps. This closed-loop process shifts iteration from the user to the agent. Instead of the analyst running a query, eyeballing the results, tweaking the SQL, and repeating, the agent handles that entire feedback loop internally. The agent also handles multi-step analysis end-to-end: understanding the question, exploring relevant data, running queries, and synthesizing findings into a narrative. For ambiguous questions, it proactively asks clarifying questions. If no response comes, it applies sensible defaults (e.g., assuming the last 30 days as the date range) to stay non-blocking.

Circular flow diagram showing the closed-loop reasoning cycle: user question, explore data, generate SQL, execute and validate, with a self-correction loop back to diagnose and adjust when results look wrong
The agent’s closed-loop reasoning cycle. When intermediate results look wrong (e.g., zero rows from a bad join), the agent diagnoses the issue and retries - shifting iteration from the user to the agent.

Interview angle

When designing an AI agent, interviewers ask “what happens when it gets something wrong?” The weak answer is “the user corrects it.” The strong answer describes a self-correction loop: validate intermediate results, detect anomalies (zero rows, implausible counts), diagnose the root cause, and retry with an adjusted approach - all before surfacing results to the user. This is the ReAct (Reasoning + Acting) pattern in practice.

RAG pipeline: embeddings, retrieval, and daily enrichment

A daily offline pipeline aggregates all context layers - table usage, human annotations, and Codex-derived enrichment - into a single normalized representation per table. This enriched context is converted into embeddings using OpenAI’s Embeddings API and stored in a vector store. At query time, the agent uses retrieval-augmented generation (RAG): the user’s question is embedded, the most relevant table contexts are retrieved via similarity search, and only those contexts are injected into the prompt. This avoids scanning raw metadata across 70k datasets at runtime, keeping latency predictable and low. Runtime queries to the data warehouse are issued separately when the agent needs live data that isn’t covered by the pre-computed context - for example, when inspecting a newly created table or validating stale schema information.

Two-lane flow diagram showing the offline daily pipeline (enrich, embed, store) and the online query pipeline (embed question, similarity search, inject context into GPT-5.2) with a fallback to live warehouse queries
The RAG pipeline: a daily offline lane pre-computes embeddings from enriched context, while the online lane retrieves the most relevant context at query time via similarity search. Live warehouse queries serve as a freshness fallback.

Interview angle

RAG is the most commonly tested LLM architecture pattern. Know the full pipeline: offline enrichment → embedding → vector store → similarity retrieval → prompt injection. The key tradeoff is freshness vs. latency: pre-computed embeddings are fast but can go stale. OpenAI handles this with daily refresh plus a runtime fallback to live queries. When asked “how would you build X with an LLM?”, RAG with a freshness strategy is almost always part of the answer.

Evaluation: evals as unit tests for agent quality

Quality drift is inevitable in a continuously improving agent. OpenAI uses their Evals API to systematically measure and protect answer quality. The eval suite is built on curated question-answer pairs. Each question targets an important metric or analytical pattern, paired with a manually authored “golden” SQL query that produces the expected result. For each eval run, the agent receives the natural language question, generates SQL, executes it, and the output is compared against the golden SQL’s result. Importantly, evaluation doesn’t use naive string matching. Generated SQL can differ syntactically while being semantically correct, and result sets may include extra columns that don’t affect the answer. Both the SQL and the resulting data are fed into an LLM-based grader that produces a correctness score with an explanation. These evals run continuously in development to catch regressions and serve as canaries in production - functioning exactly like a unit test suite for non-deterministic output.

Interview angle

Agent evaluation is an emerging interview topic. The key insight: you can’t string-match LLM output, so you need semantic evaluation. The pattern is: golden input → agent output → execute both → compare results with an LLM grader. This is analogous to snapshot testing in frontend development, but with a semantic comparator instead of a diff. Candidates who mention eval-driven development for AI systems stand out.

Security model: pass-through permissions and transparency

The agent operates as a pure interface layer that inherits the requesting user’s existing permissions. It cannot access tables the user doesn’t already have permission to query. When access is missing, the agent flags it or falls back to alternative datasets the user is authorized to use. Institutional knowledge retrieved from Slack, Google Docs, and Notion goes through a retrieval service that handles access control and caching at runtime - ensuring the agent never surfaces documents a user shouldn’t see. For transparency, the agent exposes its reasoning process: it summarizes assumptions and execution steps alongside each answer, and links directly to underlying query results so users can inspect raw data and verify every step.

Interview angle

Security in AI systems is a growing interview area. The key principle is: the agent should never escalate privileges. Pass-through permissions mean the agent’s access is the intersection (not union) of its capabilities and the user’s permissions. Interviewers also test for “prompt injection” awareness - can a malicious document in the knowledge base trick the agent into leaking data? Mentioning access-controlled retrieval and result transparency signals security-aware design.

Lessons learned: less is more, guide goals not paths, meaning lives in code

Three hard-won lessons from building the agent. First, less is more with tools: early versions exposed the full tool set to the agent, but overlapping functionality confused it. Consolidating and restricting tools reduced ambiguity and improved reliability. Second, guide the goal, not the path: highly prescriptive prompts degraded results. Questions share a general analytical shape but differ enough in detail that rigid instructions pushed the agent down wrong paths. Shifting to high-level guidance and letting the model reason about execution paths produced better results. Third, meaning lives in code: schemas and query history describe shape and usage, but the true meaning of a table - its assumptions, freshness guarantees, and business intent - lives in the pipeline code that produces it. This is why Codex enrichment was the single biggest quality unlock.

Interview angle

These are directly applicable agent design principles. “Less is more with tools” maps to the interface segregation principle - agents perform better with fewer, well-scoped tools than many overlapping ones. “Guide goals, not paths” is the difference between imperative and declarative prompting. “Meaning lives in code” applies to any data catalog or metadata system design. Use these as concrete principles when asked “how would you build a reliable AI agent?”

Key concepts

Retrieval-Augmented Generation (RAG)

An architecture where an LLM retrieves relevant context from an external knowledge store (via embeddings and similarity search) before generating a response. This grounds the model’s output in actual data rather than relying solely on its training knowledge, dramatically reducing hallucinations.

Like an open-book exam: instead of answering from memory alone, you first look up the relevant reference material, then write your answer. The quality of your answer depends on both your reasoning ability and the quality of what you looked up.

Embeddings

Dense vector representations of text (or other data) that capture semantic meaning. Similar concepts end up close together in vector space. Used for similarity search: embed the user’s question, then find the stored documents whose embeddings are closest to it.

Like GPS coordinates for meaning. Two restaurants might have different names and addresses, but if they’re both “Italian fine dining in downtown,” their semantic coordinates are close together.

Data Lineage

The end-to-end trail of how data flows through a system: where it originates, what transformations are applied, and where it ends up. Upstream lineage tracks where a table’s data comes from; downstream lineage tracks what depends on it. Critical for understanding data quality and impact of changes.

Codex Enrichment

Using an AI code-understanding model (Codex) to analyze the source code of data pipelines and extract semantic information about what each table contains, how it’s computed, and what constraints apply. Goes beyond schema metadata to capture business logic embedded in code.

Like reading the recipe instead of just looking at the ingredient list. The ingredients (schema) tell you what’s in the dish, but the recipe (pipeline code) tells you how it was prepared, what was left out, and why.

Closed-Loop Reasoning

An agent architecture where the agent evaluates its own intermediate outputs, detects errors or anomalies, and self-corrects before presenting final results to the user. Shifts the debugging and iteration loop from the human to the agent.

Like a chef who tastes the dish while cooking and adjusts seasoning, rather than serving it to the customer and waiting for feedback to know if something is off.

Agent Memory

A persistence layer where an AI agent stores corrections, learned constraints, and non-obvious rules from previous interactions. Scoped at global (applies to all users) and personal (applies to one user) levels. Prevents the agent from repeating known mistakes across sessions.

Pass-Through Permissions

A security model where the agent inherits and enforces the requesting user’s existing access controls. The agent can never access resources the user can’t access directly, ensuring no privilege escalation occurs through the AI layer.

Like a personal assistant who can only open doors you’ve given them your keycard for. They can’t get into rooms you’re not authorized to enter, no matter how persuasive the request.

Eval-Driven Development

Using curated evaluation suites (question-answer pairs with golden outputs) to measure and protect AI agent quality. Evals run continuously like unit tests, catching regressions before they reach production. Uses semantic comparison rather than string matching since correct AI outputs can differ syntactically.

Check your understanding

OpenAI’s data platform has 70k datasets across 600 PB. What did they identify as the primary bottleneck for analysts?

  • Finding the right table among many similar-looking datasets whose subtle semantic differences only surface in pipeline code and domain context.
  • Slow query execution times on large tables caused by unoptimized storage formats and insufficient compute resources allocated to the warehouse.
  • Lack of SQL expertise among non-technical employees across Go-To-Market and Finance who needed data access for their workflows.
  • Insufficient data freshness caused by batch ETL pipelines that only updated tables once per day, making real-time analysis impossible.
Show answer

Finding the right table among many similar-looking datasets whose subtle semantic differences only surface in pipeline code and domain context.

The primary bottleneck was table discovery - many tables look structurally similar but differ in subtle ways (e.g., one includes logged-out users, another doesn’t). Analysts spent hours determining which table to use before writing any SQL. The agent solves this with six layers of context that help it understand what each table actually contains.

The agent’s context architecture has six layers. Why is Codex enrichment (Layer 3) considered the most impactful?

  • It provides real-time query results that are always fresher than the daily-refreshed metadata cached from the other five context layers.
  • It replaces the need for human annotations by automatically generating semantically rich table descriptions from historical usage patterns.
  • It analyzes the pipeline source code that produces each table, revealing semantics that schemas and query history cannot capture.
  • It embeds table schemas into high-dimensional vectors optimized for faster similarity search during the retrieval step of RAG.
Show answer

It analyzes the pipeline source code that produces each table, revealing semantics that schemas and query history cannot capture.

Two tables can have identical schemas but completely different semantics - one might exclude bot traffic, another might only include first-party ChatGPT data. These distinctions only exist in the ETL/pipeline code. Codex reads that code and extracts what the data actually contains, its update frequency, scope, and granularity - information that schema metadata and query history can’t provide.

The agent’s memory system stores corrections from previous conversations. What design principle governs what should be stored in memory vs. re-derived at runtime?

  • Memory stores all user interactions verbatim so the agent can replay full conversation context in future analytical sessions.
  • Memory stores pre-computed SQL templates and query plans for common analytical patterns to avoid the cost of regenerating them.
  • Memory stores corrections scoped at both global and personal levels, but only for constraints that cannot be inferred from the other five context layers.
  • Memory stores only globally applicable corrections; individual user preferences are encoded via per-user system prompt configuration.
Show answer

Memory stores corrections scoped at both global and personal levels, but only for constraints that cannot be inferred from the other five context layers.

Memory is specifically for non-obvious corrections - like learning that a particular analytics experiment requires matching a specific string in an experiment gate rather than fuzzy matching. If the information can be derived from schemas, code, or documentation, it belongs in those layers, not memory. This prevents memory bloat and staleness.

When the agent’s generated SQL returns zero rows, what does it do?

  • Applies a set of predefined fallback queries designed for each detected table pattern to guarantee non-empty results for the user.
  • Returns the empty result to the user with a diagnostic summary explaining which filters or joins might have caused the issue.
  • Logs the failed query and switches to a cached summary table that approximates the requested data at a lower level of granularity.
  • Investigates the root cause (e.g., incorrect join or filter), adjusts its approach, and retries while retaining full context from prior steps.
Show answer

Investigates the root cause (e.g., incorrect join or filter), adjusts its approach, and retries while retaining full context from prior steps.

The agent uses closed-loop reasoning: it evaluates intermediate results, detects anomalies like zero rows (often caused by incorrect joins or filters), diagnoses the cause, adjusts its approach, and retries. It retains full context across these self-correction loops, carrying learnings forward between steps. This shifts the debugging iteration from the user to the agent.

How does the agent’s eval system handle the fact that two semantically correct SQL queries can look syntactically different?

  • It normalizes all SQL to a canonical abstract syntax tree before performing a structural diff against the golden query.
  • It converts both queries to query execution plans and compares the plan trees for structural equivalence at each stage.
  • It only compares the final aggregate output values, ignoring the SQL structure and intermediate result shapes entirely.
  • It executes both queries, then feeds the SQL and result data into an LLM-based grader that scores correctness semantically.
Show answer

It executes both queries, then feeds the SQL and result data into an LLM-based grader that scores correctness semantically.

Naive string matching would fail because correct SQL can differ syntactically - different column ordering, alternative join syntax, or extra columns that don’t affect the answer. OpenAI’s approach: execute both queries, compare the SQL and result data, and feed everything into an LLM-based grader that produces a correctness score with an explanation. This is semantic evaluation, not syntactic matching.

Early in development, OpenAI exposed the full tool set to the agent. What problem did this cause?

  • Latency increased because the model had to evaluate each tool’s applicability sequentially before selecting the right one for the task.
  • Overlapping tool functionality created ambiguity, causing the agent to choose wrong tools or combine them incorrectly.
  • Security vulnerabilities arose because certain tools had elevated privilege levels that the agent could invoke without user consent.
  • The agent’s context window filled up with tool descriptions, leaving insufficient room for the actual data context and user query.
Show answer

Overlapping tool functionality created ambiguity, causing the agent to choose wrong tools or combine them incorrectly.

Overlapping functionality confused the agent. While redundant tools can be helpful for humans who manually choose which to use, agents struggle with ambiguity between tools that do similar things. Consolidating and restricting the tool set reduced confusion and improved reliability. This maps to the interface segregation principle in software design.

The agent retrieves institutional knowledge from Slack, Google Docs, and Notion. How is access control enforced on these documents?

  • Documents are pre-filtered during the daily embedding pipeline so that only organization-wide publicly shared documents are indexed and retrievable.
  • The agent verifies user permissions by cross-referencing the requesting user’s role against a centralized RBAC policy store before each query.
  • A retrieval service checks permissions and caches authorization decisions at runtime, ensuring the agent only surfaces documents the requesting user can access.
  • All institutional knowledge is treated as internal-public within the organization, so any authenticated employee can access any indexed document.
Show answer

A retrieval service checks permissions and caches authorization decisions at runtime, ensuring the agent only surfaces documents the requesting user can access.

The agent uses pass-through permissions - it can never access resources the user can’t access directly. Documents from Slack, Docs, and Notion are ingested with metadata and permissions, and a retrieval service enforces access control at runtime. This prevents privilege escalation through the AI layer.

OpenAI found that highly prescriptive prompting degraded the agent’s results. What approach worked better?

  • Replacing natural language prompts entirely with structured JSON schemas that constrained both the output format and execution steps.
  • Using few-shot examples curated from similar past queries instead of writing explicit step-by-step analytical instructions.
  • Providing high-level guidance about the analytical goal and letting the model’s reasoning determine the execution path.
  • Removing all system prompts and relying on the model’s pre-training combined with in-context table metadata to handle queries.
Show answer

Providing high-level guidance about the analytical goal and letting the model’s reasoning determine the execution path.

Rigid, step-by-step instructions often pushed the agent down incorrect paths because questions share a general analytical shape but differ enough in detail. Shifting to high-level goal-oriented guidance (what to achieve, not how to achieve it) and letting GPT-5.2’s reasoning choose the execution path produced more robust and accurate results. This is the difference between imperative and declarative prompting.

The daily offline pipeline aggregates context from multiple layers into embeddings. Why not skip the offline pipeline and retrieve raw metadata at query time instead?

  • Pre-computing embeddings allows the system to apply normalization and deduplication that would be too expensive to perform on raw metadata at query time.
  • Embedding and retrieving pre-computed context via RAG keeps latency predictable across 70k datasets, whereas scanning raw metadata at runtime would be prohibitively slow.
  • The offline pipeline enables cross-table relationship inference by comparing embedding vectors, which isn’t possible with isolated raw metadata records.
  • Raw metadata lacks the semantic annotations added during the enrichment pipeline, making it insufficient for accurate table retrieval on its own.
Show answer

Embedding and retrieving pre-computed context via RAG keeps latency predictable across 70k datasets, whereas scanning raw metadata at runtime would be prohibitively slow.

With 70k datasets, scanning raw metadata at query time would be slow and unpredictable. The daily pipeline normalizes, enriches, and pre-computes embeddings so that at query time, the agent only needs a fast vector similarity search to pull the most relevant context. Runtime queries to the warehouse are reserved for cases where pre-computed context is missing or stale.

The agent is deployed across Slack, a web interface, IDEs, Codex CLI (via MCP), and ChatGPT (via MCP). What architectural pattern does this multi-surface deployment most directly require?

  • Event sourcing, where all interactions across surfaces are stored as an immutable event log that any surface can replay to reconstruct state.
  • A unified backend service with a single API, keeping surface-specific rendering and interaction logic in thin client adapters.
  • Separate fine-tuned model variants for each surface, optimized for the specific interaction patterns of chat, CLI, and IDE contexts.
  • A shared distributed cache layer that synchronizes conversation state across all surfaces so users can switch mid-conversation seamlessly.
Show answer

A unified backend service with a single API, keeping surface-specific rendering and interaction logic in thin client adapters.

Multi-surface deployment strongly implies a clean separation between the agent’s core reasoning (a backend service with a unified API) and the surface-specific adapters that handle Slack formatting, web UI rendering, IDE integration, and MCP protocol. This is the backend-for-frontend (BFF) pattern applied to AI agents. It also means the agent’s context, memory, and permissions must be surface-agnostic.

#AI Agents #System Design #Data Engineering #RAG

Liked this? Engineer's Codex sends one deep dive and a link roundup every week.

No spam. Unsubscribe anytime.