From Prototype to Production with MLflow for GenAI
Introduction
- Advanced Data Engineering with
- Design databases and pipelines optimized for the Lakehouse Platform.
- Implement efficient incremental data processing to validate and enrich data driving business decisions and applications.
- Leverage native features for managing access to sensitive data and fulfilling right-to-be-forgotten requests.
- Manage error troubleshooting, code promotion, task orchestration, and production job monitoring using tools.
Modules
- Architecting for the Lakehouse
- Bronze Ingestion Patterns
- Promoting to Silver
- Gold Query Layer
- Storing Data Securely
- Propagating Updates and Deletes
- Orchestration and Scheduling
Our Company: moovio
- Inputs: Structured, Semi-Structured and Unstructured Data
- Processing: Raw data streams processed through transformation engines
- Outputs: Streaming Analytics, BI, Data Science, and Machine Learning
The Lakehouse Architecture and Delta Lake
Architecting for the Lakehouse
- Adopting the Lakehouse Architecture
- Lakehouse Medallion Architecture
- Streaming Design Patterns
The Databricks Lakehouse Platform
- One platform to unify all of your data, analytics, and AI workloads
- Unifies Data Lake and Data Warehouse capabilities
- Core pillars: Simple, Open, Collaborative
- Workloads: Data Engineering, BI and SQL Analytics, Data Science and ML, Real-Time Data Applications
- Management and security: Data Management and Governance, Platform Security & Administration
- Storage foundation: Open Data Lake supporting unstructured, semi-structured, structured, and streaming data
Delta Lake
- Bridges Data Lake and Data Warehouse
- Better reliability with transactions
- 48x faster data processing with indexing
- Data governance at scale with fine-grained access control lists
ACID Transactions
- Atomicity
- Consistency
- Isolation
- Durability
- Delta Lake provides ACID guarantees scoped to tables
Problems Solved by ACID
- Hard to append data
- Modification of existing data difficult
- Jobs failing mid way
- Real-time operations hard
- Costly to keep historical data versions
The Medallion Architecture: Bronze Layer
Overview
- The Lakehouse Medallion Architecture
- Multi-hop Pipeline (flow from Source to Bronze, Silver, and Gold)
- Source: Files or integrated systems
- Bronze: Raw data and metadata
- Silver: Validated data with atomic grain
- Gold: Refined, aggregated data
Bronze Layer
- Bronze layer replaces the traditional data lake
- Represents the full, unprocessed history of the data
- Captures the provenance (what, when, and from where) of data loaded into the lakehouse
- Data is stored efficiently using Delta Lake
- If downstream layers discover later they need to ingest more, they can come back to the Bronze source to obtain it.
Bronze Layer Guiding Principles
- The goal of this layer is data capture and provenance:
- Capture exactly what is ingested, without parsing or change.
- Typically a Delta Lake table with these fields in each row: Date received/ingested, Data source (filename, external system, etc), Text field with raw unparsed JSON, CSV, or other data, and Other metadata
- Should be append only (batch or streaming)
- Plan ahead if data must be deleted for regulatory purposes
Processing Deletes
- Retain all records when possible
- Soft-deletes if necessary
- Hard-deletes may be required by regulatory processes
Bronze Ingestion Patterns
- Streaming Design Patterns
- Auto Load to Multiplex Bronze
- Streaming from Multiplex Bronze
Singleplex vs. Multiplex Ingestion
- Raw data topics mapped individually to Delta Lake tables (Batch/Structured Streaming)
- Multiple raw data topics mapped to a single multiplexed Delta Lake table (Structured Streaming)
Anti-Patterns
- Data retention limited by Kafka; expensive to keep full history
- All processing happens on ingest
- If stream gets too far behind, data is lost
- Cannot recover data (no history to replay)
- Bypassing Bronze via direct parsing, transformation, and validation to Silver is not recommended
Delta Lake Bronze
- Ingest raw data and metadata into an ingested bronze data table
- Parse, transform, and validate to output enriched silver data across multiple topics
- Notebook: Auto Load to Multiplex Bronze
- Notebook: Streaming from Multiplex Bronze
The Medallion Architecture: Silver Layer
Silver Layer Importance
- Easier to query than the non-curated Bronze "data lake"
- Data is clean
- Transactions have ACID guarantees
- Represents the "Enterprise Data Model"
- Captures the full history of business action modeled
- Each record processed is preserved
- All records can be efficiently queried
- Reduces data storage complexity, latency, and redundancy
- Built for both ETL throughput AND analytic query performance
Silver Layer Guiding Principles
- Uses Delta Lake tables (with SQL table names)
- Preserves grain of original data (no aggregation)
- Eliminates duplicate records
- Production schema enforced
- Data quality checks passed
- Corrupt data quarantined
- Data stored to support production workloads
- Optimized for long-term retention and ad-hoc queries
Promoting to Silver
- Streaming Deduplication
- Quality Enforcement
- Slowly Changing Dimensions
- Streaming Joins and Statefulness
- Validate data quality and schema
- Enrich and transform data
- Optimize data layout and storage for downstream queries
- Provide single source of truth for analytics
Schema Enforcement & Evolution
- Enforcement prevents bad records from entering table
- Mismatch in type or field name
- Evolution allows new fields to be added
- Useful when schema changes in production/new fields added to nested data
- Cannot use evolution to remove fields
- All previous records will show newly added field as Null
- For previously written records, the underlying file isn't modified
- The additional field is simply defined in the metadata and dynamically read as null
The Medallion Architecture: Gold Layer
Gold Layer Importance
- Powers ML applications, reporting, dashboards, ad hoc analytics
- Reduces costs associated with ad hoc queries on silver tables
- Allows fine grained permissions
- Reduces strain on production systems
- Shifts query updates to production workloads
MLflow for GenAI: Evaluation Metrics and Judges
Built-in LLM Judges
- RelevanceToQuery: Evaluates if the response is relevant to the user's request (no ground truth required)
- Safety: Evaluates if the response is free from harmful content (no ground truth required)
- Correctness: Evaluates if the answer is correct versus ground truth (requires ground truth)
- Fluency: Evaluates if the response is grammatically correct and natural (no ground truth required)
- Accuracy / Completeness: Evaluates if all questions in the prompt were addressed (requires ground truth)
- Equivalence: Evaluates if the response is equivalent to the expected output (requires ground truth)
- Groundedness: Evaluates if the response is grounded in context or hallucinating (no ground truth required)
- RetrievalRelevance: Evaluates if the retrieved context is relevant to the query (no ground truth required)
- RetrievalSufficiency: Evaluates if the context has all needed info (requires ground truth)
- ToolCallCorrectness: Evaluates if calls and arguments are correct for the query (requires ground truth)
- ToolCallEfficiency: Evaluates if tool usage is efficient without redundancy (no ground truth required)
- Guidelines: Evaluates if the response meets natural language criteria uniformly across all rows (no ground truth required)
- ExpectationsGuidelines: Evaluates per-example criteria from domain experts (no ground truth required)
Multi-turn Conversation Judges
- ConversationCompleteness: Did the agent address all user questions throughout?
- UserFrustration: Did the user become frustrated and was it resolved?
- KnowledgeRetention: Does the agent retain info from earlier in the conversation?
- ConversationalGuidelines: Do responses comply with guidelines across all turns?
- ConversationalRoleAdherence: Does the assistant maintain its assigned role throughout?
- ConversationalSafety: Are responses safe and free of harmful content throughout?
- ConversationalToolCallEfficiency: Was tool usage across the conversation efficient?
- Tag traces with session IDs
- MLflow automatically groups traces by session and passes full conversation history to the judge
- Custom multi-turn judges can be created with specific instructions referencing the conversation
Custom Judges and Guidelines
- Evaluate whether response meets your specified criteria
- Enable domain experts to write criteria without coding
- Rapidly test new criteria
- Example defines a clarity guideline requiring the response to be clear, coherent, and concise
- Define custom judges declaratively
- Specify instructions and model parameters for custom evaluation
- Incorporate custom judges into evaluation runs
Scorer Best Practices
- Be specific and measurable rather than providing general directions
- Use clear pass/fail conditions instead of vague formatting requests
- Reference context explicitly to ensure accurate validation
- A poorly written scorer gives false confidence and is worse than no scorer
- Invest time in refining scorer prompts
Running Evaluations
- Enable developers to systematically test new versions of the agent
- Execute evaluations using datasets, agent functions, and defined judges
- Combine built-in judges for relevance and tool calls with custom domain-specific judges
- Evaluate from a dataset by passing the dataset, predict function, and scorers
- Evaluate from existing traces by passing the traces and scorers
- For conversations, tag traces with session IDs to enable grouping and session-level scoring
Judge Alignment and Review
- Compare different agent versions using the UI
- Review metrics such as relevance and latency
- Filter, sort, and group evaluation results to analyze performance
- LLM judges are effective only if they align with human expert preferences
- Auto-align judges to match expert feedback automatically
- Applicable to both built-in and custom judge types
- Create and manage judges for evaluating responses with human feedback alignment
- Select templates for custom, relevance, safety, or correctness evaluation
- Define quality judges with specific evaluation criteria and rating scales
- Automatically optimize alignment using framework optimizers and traces containing feedback
MLflow for GenAI: Agent Optimization and Workflow
The Self-Improving Agent Loop
- Coding assistants and MLflow enable continuous agent improvement
- Setup tracing
- Run agent
- Find issues
- Test via judges
- Fix code
- Verify and repeat
Skills and MCP Server Integration
- Add skills via command line to teach coding agents specific knowledge
- Setup tracing, run evaluations, and analyze traces
- MCP Server provides structured access from any IDE
- Search and analyze traces
- Log feedback and assessments
- Run evaluation workflows
- Command-line interfaces provide direct, scriptable access with identical capabilities
Iteration Workflow
- Navigate from trace analysis to verified fix in a single conversation
- Agent runs and captures traces automatically
- Coding assistant analyzes traces to identify silent tool failures
- Create a scorer to quantify the identified issue
- Developer fixes the agent code by adding fallback logic
- Re-run evaluation to confirm improvement via the scorer
- Repeat the process for subsequent issues
Prompt Optimization
- Manage and automate prompt engineering with Unity Catalog
- Track and manage multiple versions of system and user prompts
- Automatically optimize prompts using labeled data
- Register original prompts and run optimization functions to improve output quality
GEPA (Genetic Pareto) Optimizer
- Utilizes natural language reflection learning from academic research
- Achieves significantly cheaper inference while maintaining high quality compared to leading proprietary models
- Declarative framework integration enables structured prompt optimization
- Directly integrates academic research into production systems
- Core components and catalogs prioritize open source availability over proprietary alternatives
- Builds state-of-the-art enterprise agents efficiently by automatically optimizing prompts along a quality-cost frontier
MLflow for GenAI: Production Monitoring
Production Monitoring Overview
- Release Agent to production and monitor quality in production as the final stage of the agent development lifecycle
- Supported by AI/BI dashboards and experiment tracking alongside tracing, labeling, evaluation datasets, prompt registry, prompt optimization, LLM judges, and evaluation UIs
Key Monitoring Metrics
- Operational Metrics: Performance and reliability, and resource utilization
- Quality Metrics: Response quality, safety and compliance, user experience quality, and domain-specific quality
- Business Impact: User engagement and behavior, operational efficiency, and cost-benefit analysis
Deployment Paths
- Self-Hosted Tracking Server: Good for POCs and small deployments; scaling requires PostgreSQL/MySQL and indexing
- OpenTelemetry Integration: Supports agents running anywhere, routing into an existing observability stack (such as Datadog, New Relic, or Jaeger) or into MLflow for full evaluation and governance
- Managed Monitoring: Provides automated operational metrics (latency, errors, token costs) and automated quality metrics (correctness, safety, context sufficiency)
Tracing and Dashboards
- Stores traces in Delta tables with Unity Catalog and includes built-in dashboards and SQL-based alerts
- Monitor application traces with Unity Catalog for both internally deployed and external applications
- Internal deployments route requests and responses through a Model Serving application, logging inference data via AI Gateway to an Inference Delta table and sending traces to an MLflow tracking server
- External applications send traces directly to the MLflow tracking server
- Production monitoring writes trace data into a Monitoring Delta table
Continuous Feedback Loop
- Use the same tracing in production as in development to run anywhere and trace in MLflow
- Use APIs to record end-user feedback such as thumbs up/down and free-form feedback
- Automatically run LLM judges on online traces with configurable sampling rates and filtering
- Configure monitor settings including serving endpoint, trace archive table, AI judges (safety, relevance to query, groundedness, chunk relevance), custom guidelines, and sample rate
- Add production traces to evaluation datasets to close the loop between production and development
Ingestion and Version Control
- Production-grade, governed MLflow for enterprise GenAI
- Zerobus Ingest captures terabytes of GenAI traces, feedback, and telemetry from production agents in real time
- Ingests OpenTelemetry data from producers including cloud apps, edge apps, and IoT devices directly into Unity Catalog
- Delivers high throughput, near real-time ingestion, and low total cost of ownership (TCO)
- Built-in version control across agents, prompts, and evaluation datasets
- Agent versions are reproducible with exact prompts, models, and datasets
Production Evaluation Rules
- Run the same scorers from development continuously on live production traffic without rewriting
- Register a scorer and start continuous background evaluation with a sampling configuration and optional trace status filter strings
- Assessments automatically attach to traces, appear in the UI, and are queryable in Delta tables
- Maximum of 20 scorers per experiment; start sampling at 10-20% and scale up as needed
- For custom scorers, import packages inline rather than at the top of the file to ensure proper serialization
- Design production scorers to handle missing expectations since ground truth is unavailable in production
- Use backfill scorers for retroactive evaluation on historical traces
Action Points
- Continuous quality improvement lifecycle connecting development testing and production monitoring
- End users interact with the application, generating traces and feedback sent to production monitoring
- Production monitoring and domain expert inputs feed into evaluation sets used during development testing
- LLM judges evaluate quality across both development testing and production monitoring before deploying new versions
- Choose an integration path based on existing infrastructure, installing only mlflow-tracing to keep production lightweight and configuring async logging to avoid latency overhead
- Set up SQL alerts on quality, cost, and drift metrics
- Configure automatic evaluation and enable sampling for high-volume applications
- Add rich context such as user, session, and environment tags for better traceability
- Set up an AI/BI dashboard to track trace quality
- Link business KPIs such as Customer Satisfaction (CSAT) directly to agent performance across the GenAI application lifecycle
- Track metrics across resolution time, agent performance, cost impact, and compliance
- Compare operational metrics such as daily CSAT with and without the AI agent
Phased Adoption Strategy and Takeaways
Strategic Value
- Helps move past initial vibe coding by debugging cost and quality issues
- Improves agent quality and lowers costs through automated prompt optimization, LLM switching, experiment tracking, and automated evaluations
- Closes the feedback loop automatically using coding assistants with MLflow Skills and MCP
- Get started by enabling automatic tracing, running evaluations, optimizing prompts, aligning LLM judges, and connecting coding assistants via MCP
Adoption Phases
- Start small, build confidence, and scale with evidence across four adoption phases
- Foundation: Enable tracing on the agent, connect the dev environment, inspect traces manually via the Trace UI, and identify initial quality gaps
- Early Eval: Build an initial evaluation dataset of 30-50 examples, run built-in judges, set up the Prompt Registry, and establish baseline metrics
- Domain Quality: Engage SMEs via the review app for labeling, build and align Guidelines judges with feedback, and run prompt optimization
- Production: Enable production tracing, configure automatic evaluation with sampling, build AI/BI dashboards backed by Delta tables, and close the feedback loop
Key Takeaways
- Start Simple, Scale Gradually: Begin with auto-instrumentation, add custom traces for business logic, and scale monitoring based on ROI
- Quality over Quantity: Deeply monitor 10% of traffic rather than poorly monitoring 100%, focus on actionable metrics, and iterate based on production learnings
- Build for Production from Day 1: Implement privacy controls early, design for scale with sampling and retention policies, and plan for cost optimization
Top comments (0)