<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Josh Melton on Medium]]></title>
        <description><![CDATA[Stories by Josh Melton on Medium]]></description>
        <link>https://medium.com/@joshlipemelton?source=rss-6ba46ca3b2d0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*7q3leUVWFpMMDAz5.jpg</url>
            <title>Stories by Josh Melton on Medium</title>
            <link>https://medium.com/@joshlipemelton?source=rss-6ba46ca3b2d0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 11:04:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joshlipemelton/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Operationalizing Operations Research]]></title>
            <link>https://medium.com/@joshlipemelton/operationalizing-operations-research-07701247cef1?source=rss-6ba46ca3b2d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/07701247cef1</guid>
            <category><![CDATA[operations-research]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Josh Melton]]></dc:creator>
            <pubDate>Sun, 03 May 2026 16:55:20 GMT</pubDate>
            <atom:updated>2026-05-07T13:53:20.374Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c_HTfiQBcL31_0bxhaz6uQ.png" /></figure><h4>A practical framework for OR Ops: treating optimization solvers with the discipline of production ML.</h4><p>Operations Research (OR) shows up wherever decisions are made under constraints. How many cases should we reorder this week? Which warehouse should serve which store? Which technicians should be scheduled for which shifts? Unlike machine learning, these are not prediction problems. They are decision problems, and, ironically, Operations Research workloads are often poorly operationalized because they are relegated to their own disparate systems.</p><p>This article walks through what good operationalization on a unified analytics platform looks like for OR, using a companion inventory <a href="https://github.com/josh-melton-db/mlflow-or-crash-course">optimization repo</a>. The example is a supply chain problem, but the pattern is portable to any OR workflow your business runs.</p><h3>What Is Operations Research?</h3><p>OR is the practice of using mathematical optimization, simulation, and analytical methods to improve decisions. Where ML predicts what will happen, OR prescribes what to do about it — computing the best course of action given a set of rules, limits, and tradeoffs. Routing trucks, staffing warehouses, scheduling maintenance, pricing products, and allocating capital are all OR problems. Each of these problems has the same shape:</p><ul><li><strong>Decision variables</strong>: the choices the solver can make</li><li><strong>Constraints</strong>: the rules the solution must satisfy</li><li><strong>Objective function</strong>: the quantity to maximize or minimize</li><li><strong>Parameters</strong>: the business inputs and solver settings that shape the run</li><li><strong>Metrics</strong>: measurements used to compare candidate runs (objective value, solve time, feasibility, fill rate, optimality gap)</li><li><strong>Outputs</strong>: the recommended decisions and their expected impact</li></ul><p>Those concepts strongly resemble ML experiment tracking, and the operational challenges for both are similar. Production ML and production OR both need versioned artifacts, tracked experiments, governed promotion, deployment surfaces, lineage, audit trails, and regression monitoring.</p><h3>Solvers as Models</h3><p>The comparison between ML and OR applies operationally, not mathematically, so it’s important to note the differences as well. ML training produces learned weights that generalize across many predictions, while an OR solver produces a decision for a single instance. You don’t evaluate an OR solve on held-out data, you re-solve a new instance. A solver configuration that wins on a small, easy week can lose badly during a December peak.</p><p>Despite their fundamental differences, however, ML and OR share operational challenges. OR and ML teams are often siloed into their own systems, working on different copies or exports of data than other teams. In large enterprises, managing and deploying ML and OR artifacts can be more difficult than creating them in the first place. These problems have already been solved for ML, and in the rest of this article we apply those solutions to OR.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*FQZt6P1hTLenzLFvfZq0Pg.png" /></figure><h3>The Scenario: Weekly Inventory Replenishment</h3><p>The companion repo uses a weekly distribution-center replenishment problem as a tractable example. The decision to make:</p><p>Given our current inventory, forecast demand, procurement budget, and storage capacity, how many cases of each SKU should we order this week?</p><p>For each SKU, the solver chooses an order quantity. SKU-level inputs include on-hand inventory, forecast demand, unit cost, unit margin, holding cost, stockout penalty, storage units per case, and a maximum order quantity. Scenario-level inputs add a procurement budget and a storage capacity.</p><p>The objective balances three outcomes: fulfill as much demand as possible, stay within budget and storage capacity, and avoid both excess inventory and stockouts. The formula is essentially:</p><pre>maximize sum(<br>    sell_cases_i * unit_margin_i<br>    - ending_inventory_i * holding_cost_i<br>    - shortage_cases_i * stockout_penalty_i<br>)</pre><p>Selling into demand is good. Carrying leftover inventory is mildly bad. Stockouts are usually worse. The solver turns those tradeoffs into a recommended order plan. The same shape generalizes well past inventory: a staffing optimizer might replace SKUs with shifts and certifications, a routing optimizer might replace cases with lanes and capacity, a pricing optimizer might replace order quantities with discount levels and margin targets. The lifecycle in the rest of this article applies in each case.</p><p>Today, most teams solve problems like this using one-off scripts, ad hoc notebooks, or purpose-built apps. That works for a single user, but it makes everything afterward harder. With robust OR ops, comparing solver configurations, promoting a winning version, reusing the same logic across batch and serving, reproducing a historical recommendation, and auditing why a particular plan was chosen are all tightly integrated with the rest of the data platform. For a single weekly internal script with one consumer, lightweight tooling may be enough. The pattern in this article becomes valuable when OR becomes a shared production capability that has to reach across the business. This reach stretches in three directions, and a unified data and AI platform lets a single artifact serve them all:</p><ul><li><strong>Across data domains.</strong> A single OR workflow may need inventory, pricing, supplier, promotions, customer demand, and even HR data (such as which warehouse staff are forklift-certified). A unified lakehouse means the solver consumes the same governed source of truth that powers the rest of your business, instead of forcing yet another copy.</li><li><strong>Across technical interfaces.</strong> OR consumes the outputs of machine learning (demand forecasting, time-to-failure, etc.) and data engineering pipelines, and OR’s outputs become consumable by reporting and AI agent tooling.</li><li><strong>Across audiences.</strong> Planners get recommendations. Analysts query inputs and outputs. Developers get an API. Data scientists compare configurations. Executives see aggregate impact. Auditors get a trail. Non-technical users reach the model through agents.</li></ul><p>The rest of the article shows how to achieve this unification.</p><h3>Wrap The Solver As An MLflow Model</h3><p>The cornerstone of the pattern is making the solver itself an MLflow model. MLflow’s Python model flavor was built for exactly this kind of custom inference logic. The companion repo uses <a href="https://mlflow.org/docs/latest/ml/model/models-from-code/">Models From Code</a>, where the model is defined in a small, readable Python file rather than pickled from a notebook session. That file defines a <em>PythonModel</em> class with a clear request contract. It validates the input, calls the selected solver library, and returns scenario-level metrics and SKU-level recommendations. The notebook then logs it:</p><pre>model_info = mlflow.pyfunc.log_model(<br>    name=model_name,<br>    python_model=str(model_script_path),<br>    registered_model_name=registered_model_name,<br>    signature=model_signature,<br>    input_example=[example_request],<br>    pip_requirements=build_model_requirements(champion_config[&quot;library&quot;]),<br>)</pre><p>The <em>build_model_requirements()</em> helper pins the dependency set for the selected solver library, so the registered artifact carries the exact Python and solver packages needed to reproduce that configuration. The optimizer also composes with other models. Since the demand forecast feeding our solver is itself an MLflow model, the two could be versioned and deployed together so a historical recommendation reproduces end-to-end. Similarly, the logic for warm starts or for handling failure modes such as infeasibility or out-of-tolerance results can be integrated directly into the <em>PythonModel</em>. For example, adding a status field to the response schema and the signature enables structured handling of infeasibility and other failure modes.</p><p>The solver is no longer just notebook code. It is a versioned artifact with an input example, an inferred signature, pinned dependencies, the actual Python source, and a registry entry in Unity Catalog. The rest of the operations process — tracking, benchmarking, scaling, deployment, and governance — hangs off of that artifact.</p><h3>Benchmark And Alias An Artifact</h3><p>Once the solver is a “model”, it plugs directly into standard MLOps processes. In our repo, the CPU notebook benchmarks OR-Tools CP-SAT against SciPy milp, which wraps HiGHS-backed mixed integer programming. The GPU companion benchmarks NVIDIA cuOpt configurations on serverless GPU compute against the CPU models. We used open source solvers, but the same pattern can integrate commercial solvers like Gurobi or CPLEX as well. Regardless of the source, MLflow logs solver parameters such as library, time limit, worker count, relative gap, and presolve. Next, it records the metrics that determine which configuration provides the highest ROI: objective value and its components, average and percentile solve times, feasibility, optimality gap, fill rate, shortage rate, budget utilization, and storage utilization. These are OR metrics, but the loop is the same loop ML teams already run: candidate runs, shared data, tracked parameters and metrics, and a defensible winner. MLflow gives that loop a parent run for the workflow and nested runs for each configuration.</p><p>Once a winner is chosen, the notebook registers it in Unity Catalog and assigns the Champion alias. Downstream systems do not bind to a particular run or version. They call Champion, and the team can promote a new version when the metrics support it. This is the same separation between experimentation and production that makes ML registries useful.</p><p>Importantly, OR differs from ML in that Champion is an alias, not a claim that there is a globally best solver for every possible week. In OR, the best solver configuration can depend on the problem instance. A setting that wins on small SKU counts may not win during peak demand, and a presolve or warm-start strategy that helps normal weeks can be less attractive under tight budgets, high stockout pressure, or near-infeasible inputs. A production benchmark should therefore use a representative scenario suite — normal weeks, peak weeks, sparse and large SKU sets, high stockout regimes, tight budgets, and near-infeasible cases. Mature teams may maintain different aliases for different types of scenarios, or add a lightweight router that selects a configuration from instance features. The point is not to crown a universal solver, but to make promotion explicit, evidence-based, and reproducible.</p><h3>Scale To Real Workloads</h3><p>OR problems get expensive fast. The Traveling Salesman Problem with just 20 cities has roughly 2.4 quintillion possible routes (20! = 2,432,902,008,176,640,000). Real planning problems usually involve thousands or millions of decision variables interacting under dozens of constraints. Solvers do not enumerate every option, but the search space explains why solver choice, runtime choice, and runtime budget all matter.</p><p>Production workloads typically fall into one of two broad categories:</p><ul><li><strong>Massive scheduled batch</strong>: nightly replenishment runs across thousands of locations, weekly route reoptimization for entire fleets, and monthly capital planning across hundreds of facilities.</li><li><strong>Spiky, low-latency real-time</strong>: planner-facing what-if calculations, agent tool calls, and customer-facing recommendations triggered by an API.</li></ul><p>The same MLflow Champion artifact can handle both. For batch, Spark’s <em>applyInPandas</em> loads the model once per worker and solves each scenario in parallel. For real-time, Model Serving auto-scales endpoints behind REST and SQL interfaces. Analysts can call the endpoint through <em>ai_query</em>, and applications and agents call the same endpoint through the serving API. The solver logic does not change between modes; only the surrounding runtime does.</p><p>The choice of runtime is itself a benchmarked decision. The repo includes a CPU vs GPU comparison for a sparse two-echelon distribution network LP — source-to-DC flows, DC-to-store flows, product/store demand, capacity constraints, throughput limits, and shortage penalties. The default problem size is about 80 products, 80 distribution centers, 250 stores, ~125k variables, and ~26k constraints. The CPU notebook solves it with SciPy linprog (HiGHS); the GPU companion solves it with cuOpt PDLP. Both runs log to a shared MLflow experiment. For this scenario, cuOpt wins on both speed (~10x) and price-performance (&gt;2x), and the gap widens with scale. The point here is not that GPUs always win — different problems will pick different runtimes. The point is that the comparison is a logged experiment, not tribal knowledge. Problem size, sparsity, solver versions, tolerances, and cost basis are all part of the run record. When inputs change, the team reruns the benchmark and promotes a new Champion with full evidence.</p><p>Critically, governance and lineage are built in. Solver inputs and outputs live in Unity Catalog-governed tables, models live in a Unity Catalog versioned registry, endpoints are managed alongside the model, and every recommendation is traceable to the MLflow experiment that justified its promotion. The unified platform answers questions about when/which data were accessed and by whom, which solver was used, and how to reproduce a historical decision, without requiring a separate compliance system for OR vs. the rest of the data platform.</p><h3>Try It Yourself</h3><p>The whole lifecycle — generate scenarios, persist inputs to Unity Catalog, benchmark OR-Tools against SciPy in MLflow, register a Champion, run Spark batch optimization, and optionally deploy a serving endpoint — lives in the <a href="https://github.com/josh-melton-db/mlflow-or-crash-course/blob/main/notebooks/inventory_optimization_crash_course.py">inventory_optimization_crash_course</a> notebook.</p><p>Clone the repo, try the <a href="https://github.com/josh-melton-db/mlflow-or-crash-course/tree/main/introduction">introduction</a>, run the crash course benchmark, register a Champion, and try calling it from a few of the available interfaces. Then explore cuOpt on serverless GPUs with the <a href="https://github.com/josh-melton-db/mlflow-or-crash-course/blob/main/notebooks/inventory_optimization_cuopt_gpu.py">inventory_optimization_cuopt_gpu</a> companion notebook.</p><p>OR solvers produce the decisions that move budgets, fill orders, route trucks, and staff facilities. They deserve the same operational rigor as production ML: versioned artifacts in a registry, tracked experiments with deterministic benchmarking, governed deployment across batch and real-time runtimes, and audit-ready lineage from inputs to recommendations. ML predicts. Reporting explains. Agents act. OR decides. All four deserve the same artifact discipline, and on a unified platform they can finally share it. That is OR Ops.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07701247cef1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[It’s Just Text]]></title>
            <link>https://medium.com/@joshlipemelton/its-just-text-8a9bac5e59d9?source=rss-6ba46ca3b2d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a9bac5e59d9</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[llmops]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <dc:creator><![CDATA[Josh Melton]]></dc:creator>
            <pubDate>Fri, 24 Apr 2026 16:50:01 GMT</pubDate>
            <atom:updated>2026-05-04T22:38:34.688Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i-kp9XKfS65aenJ5D-Aniw.png" /></figure><p><em>A field guide to PromptOps, and why MLflow (not Git) is the right system of record</em></p><p>The AI industry rides waves of hype: prompt engineering, then context engineering, then MCP, agent skills, Autoresearch, and harness engineering. Each wave gets more hype than the last, and it’s easy to feel constantly left behind by the latest trend.</p><p>The good news is that the substrate never changes. A prompt is text. A retrieved chunk is text. A memory summary is text. An MCP tool definition and the JSON it returns are text. A SKILL.md, AGENTS.md, SOUL.md, .cursorrules, CLAUDE.md, or any other instruction file is text. Source code, diffs, test logs, CLI output, plan steps, judge rubrics — all text. This observation is what makes PromptOps a durable discipline rather than a passing label. If your model behavior is determined by text — and it is — then that text needs to be versioned, traced, evaluated, optimized, promoted, and audited with the same care you’d apply to production code.</p><p>This post walks through the text-based waves of AI hype, shows where <a href="https://github.com/josh-melton-db/databricks-promptops-crash-course">this repo’s</a> PromptOps notebook fits, and argues that for the loop around the text, MLflow does what Git cannot.</p><h3>The Waves</h3><p>Each wave added a new kind of text to the agent’s input surface and a new way to assemble it.</p><h4>1. Prompt Engineering, RAG, and memory</h4><p>Someone writes a string or chat template and tries to get better behavior. Then they add retrieval — fetch the most relevant chunks from a vector store and inject them into the prompt. Then they add memory — summarize the last N turns, or the last day’s interactions, and inject that too. Prompt engineering, RAG, and memory are separate disciplines, but they’re really the same idea: assemble “better” or “more relevant” text into the request. A vector index is a typed lookup over text. A memory is just a stored text artifact retrieved into context on demand. A common challenge in this wave was objectively measuring what “better” or “relevant” means in the first place.</p><h4>2. MCP, CLIs, and code</h4><p>MCP is another proof point of the “everything is text” idea. An MCP server is essentially an API with an agent-friendly text interface bolted on top. The agent never sees HTTP routes or RPC stubs. It sees text descriptions of tools, text resource templates, and text responses returned from tool calls. CLIs work the same way. The command is text, stdout/stderr/exit codes are text, ` — help` and man pages are text. The agent doesn’t have a privileged channel into the OS — it has a text protocol. What MCP or CLIs standardize is not a new modality — they’re just a text interface over code. Again, the challenge becomes how to version and evaluate the text interface. What makes one <em>version</em> of an MCP “better” than another?</p><h4>3. The Markdown era</h4><p>Instead of one prompt, you author a portfolio of structured markdown that the agent treats as guidance — Anthropic’s `SKILL.md` standard, Cursor rules, the `AGENTS.md` convention, OpenAI’s instruction files, and the long tail of tool-specific configuration files are all variants of the same idea: the model’s behavior is configured by markdown that the model reads. Alexander Krentsel’s excellent <a href="https://docs.google.com/presentation/d/1vO8GHrJTJGBHO3qc2OTkuQcNx110f1t5juMbe9XVPaQ">OpenClaw deep-dive</a> makes this very explicit. In OpenClaw, the agent identity, persona, tooling preferences, and even safety rules live in a stack of .md files (IDENTITY.md, USER.md, SOUL.md, AGENTS.md, TOOLS.md, BOOTSTRAP.md). Krentsel’s observation: the “magic” isn’t a model upgrade; it’s the text the user (or the agent itself) wrote. The “vibes” are how you track whether the system is improving.</p><h4>4. Harness engineering</h4><p>Harness engineering is what happens when you put all of the above under a single runtime. Memory + tools (built-in, MCP, CLI) + skills/instruction markdown + an orchestration loop, all configurable, all introspectable. Claude Code, OpenClaw, NanoClaw, PyClaw, Cursor’s agent mode, and the rapidly growing pile of open agentic coding harnesses all sit here. The throughline, in Krentsel’s words: “<em>all systems boil down to LLM calls. The difference is the context provided.”</em></p><h4>5. The optimization-and-autoresearch arc — when the model writes the text</h4><p>Running through every era is a parallel trend: optimizing the production of text by the model itself.</p><ul><li><a href="https://dspy.ai/"><strong>DSPy</strong></a> treats prompts as compileable artifacts. You write a program; an optimizer searches for the prompt strings.</li><li><strong><em>GEPA</em></strong><em> -&gt; </em><a href="https://gepa-ai.github.io/gepa/blog/2026/02/18/introducing-optimize-anything"><em>optimize_anything</em></a> is the next step in that same line of thought. The optimize_anything tagline is “<em>if something can be serialized to a string and its quality measured, an LLM can reason about it and propose improvements.”</em></li><li><a href="https://github.com/karpathy/autoresearch"><strong>Autoresearch</strong></a> is the most vogue version right now. An agent autonomously plans, retrieves, synthesizes, and writes. The output is text (train.py), the control is text (program.md), and even the ‘observations’ — the logs and metrics the agent reads to decide its next move — are text.</li></ul><p>In each of these libraries, the human’s role shifts from being the writer to being the ‘Research Director’ managing the loop and defining what “better” means.</p><h3>So What?</h3><p>Operationalizing text underpins every one of these waves. Whether you are doing prompt engineering, building MCP tools, or running Karpathy-style Autoresearch, you eventually run into a wall of questions that traditional software tools simply cannot answer:</p><ul><li><strong>Traceability:</strong> Which specific version of the optimized prompt produced this exact trace?</li><li><strong>Evaluation:</strong> Did the latest GEPA optimization pass actually improve our domain-specific score, or did it just look better in the demo?</li><li><strong>Debugging:</strong> When the research agent regresses, which of its internal prompts — the planner, the rewriter, or the synthesizer — changed last, and which evaluation would have caught it?</li><li><strong>Governance:</strong> Which alias is prod pointing to right now, and which experiment run justifies that deployment?</li></ul><p>If you don’t know the answers, you aren’t engineering production-grade AI systems. The industry’s instinct is to reach for Git, but Git only tells you what changed, while MLflow tells you if the change worked. Prompt quality is only knowable through evaluation against datasets, comparison across runs, and promotion via aliases. We don’t put model weights in Git because Git can’t reason about a .safetensors file. Prompts and agentic &quot;skills&quot; work the same way, and they belong in the same place.</p><h4>PromptOps in Action</h4><p>To see this process end-to-end, <a href="https://github.com/josh-melton-db/databricks-promptops-crash-course/blob/main/notebooks/promptops_end_to_end.py">notebooks/promptops_end_to_end.py</a> is small enough to walk through in a single read on <a href="https://www.databricks.com/learn/free-edition">Databricks Free Edition</a>, and it covers every part of that loop.</p><p>Register a versioned prompt and assign deployment aliases — the commit_message, the URI, and the dev/prod/candidate aliases are how PromptOps gets operationalized:</p><pre>explainer_v1 = mlflow.genai.register_prompt(<br>    name=&quot;demos.prompts.tech_explainer&quot;,<br>    template=&quot;Explain {{concept}} in simple terms.&quot;,<br>    commit_message=&quot;v1: Basic single-variable explainer&quot;,<br>)<br>explainer_v2 = mlflow.genai.register_prompt(<br>    name=&quot;demos.prompts.tech_explainer&quot;,<br>    template=[<br>        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a technical writer … for a {{audience}} audience. Keep responses under 100 words.&quot;},<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Explain {{concept}}.&quot;},<br>    ],<br>    commit_message=&quot;v2: Chat-style with audience targeting and length constraint&quot;,<br>)<br>mlflow.genai.set_prompt_alias(&quot;demos.prompts.tech_explainer&quot;, alias=&quot;dev&quot;, version=explainer_v2.version)<br>mlflow.genai.set_prompt_alias(&quot;demos.prompts.tech_explainer&quot;, alias=&quot;prod&quot;, version=explainer_v1.version)</pre><p>Trace a call so the runtime behavior is captured against a specific prompt version:</p><pre>@mlflow.trace<br>def explain_concept(concept: str, audience: str = &quot;general&quot;) -&gt; str:<br>    &quot;&quot;&quot;Load a registered prompt and call the LLM.&quot;&quot;&quot;<br>    prompt = mlflow.genai.load_prompt(&quot;prompts:/demos.prompts.tech_explainer@dev&quot;)<br>    messages = prompt.format(concept=concept, audience=audience)<br>    response = client.chat.completions.create(<br>        model=GENERATION_MODEL,<br>        messages=messages,<br>        temperature=0.3,<br>        max_tokens=220,<br>    )<br>    return extract_text(response.choices[0].message.content)</pre><p>Score it with code metrics, an LLM judge, and a domain-specific guideline scorer:</p><pre>eval_results = mlflow.genai.evaluate(<br>    data=eval_data,<br>    predict_fn=explain_concept,<br>    scorers=[brevity, has_key_terms, explanation_quality, Correctness(model=JUDGE_MODEL)],<br>)</pre><p>Then close the loop: feed the <em>same scoring functions</em> back into a <a href="https://docs.databricks.com/aws/en/mlflow3/genai/prompt-version-mgmt/prompt-registry/automatically-optimize-prompts">prompt optimizer</a> that rewrites the text using the eval signal it just produced.</p><pre>multi_result = mlflow.genai.optimize_prompts(<br>    predict_fn=plan_and_explain,<br>    train_data=eval_records,<br>    prompt_uris=[plan_prompt.uri, explain_prompt.uri],<br>    optimizer=GepaPromptOptimizer(<br>        reflection_model=JUDGE_MODEL,<br>        max_metric_calls=MULTI_PROMPT_MAX_METRIC_CALLS,<br>        display_progress_bar=False,<br>    ),<br>    scorers=[brevity, has_key_terms, explanation_quality_opt, Correctness(model=JUDGE_MODEL)],<br>    aggregation=weighted_objective,<br>)</pre><p>And only promote when the metrics actually improve:</p><pre>def should_promote(result) -&gt; bool:<br>    return (<br>        result.initial_eval_score is not None<br>        and result.final_eval_score is not None<br>        and result.final_eval_score &gt; result.initial_eval_score<br>    )</pre><p>That’s a small notebook, but it has the entire operational shape of harness engineering: text artifact → trace → evaluation → optimizer → promotion gate.</p><h4>Riding The Harness Engineering Wave</h4><p>Krentsel’s presentation, linked above, has one line that should stick with anyone shipping an agentic system: “<em>the agent is becoming the interface for configuring itself.” </em>If you take that seriously, the question becomes: who governs the text the agent is generating about itself? If your harness can rewrite its own SKILL.md, update its own memory, or revise its own system prompt — and modern harnesses can — you need version control, traces, evaluations, and rollback aliases for text. Otherwise, the agent’s self-improvement is an unobservable spiral of subjectivity.</p><p>This is exactly the regime MLflow’s prompt registry, tracing, evaluation, and optimizer outputs were designed for. The more we “feel the AGI,” the more we need robust operationalization of the text around it.</p><h3>Try it Yourself</h3><p>If you want to try the loop on your own harness, the smallest useful exercise is:</p><ol><li>Open <a href="https://github.com/josh-melton-db/databricks-promptops-crash-course/blob/main/notebooks/promptops_end_to_end.py">notebooks/promptops_end_to_end.py</a> and run it top to bottom on Databricks serverless.</li><li>Pick one new criterion you care about — refusal on a forbidden topic, a formatting requirement, a tone constraint — and add it as a custom scorer or a new Guidelines rubric next to explanation_quality.</li><li>Re-run the multi-prompt GEPA optimization with your new scorer in the list.</li><li>Watch should_promote()— does your scorer change which version ships? Does the trace explain why?</li></ol><p>That’s the whole loop in one sitting: text artifact → trace → domain-specific eval → eval-driven optimization → promotion gate.</p><p>Whatever you call the latest wave — prompt engineering, MCP, the markdown era, harness engineering — the work is the same. You’re managing text. With MLflow, you can manage it optimally.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a9bac5e59d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mosaic AI Flywheel: Better, Cheaper, Faster AI Systems]]></title>
            <link>https://medium.com/@joshlipemelton/mosaic-ai-flywheel-better-cheaper-faster-ai-systems-98807d680164?source=rss-6ba46ca3b2d0------2</link>
            <guid isPermaLink="false">https://medium.com/p/98807d680164</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[dspy]]></category>
            <dc:creator><![CDATA[Josh Melton]]></dc:creator>
            <pubDate>Tue, 03 Sep 2024 18:05:04 GMT</pubDate>
            <atom:updated>2026-04-22T23:06:38.501Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LZEhjNJVaEEiqkR9.png" /></figure><p>In this article we’ll curate data with <a href="https://docs.databricks.com/en/generative-ai/retrieval-augmented-generation.html">Mosaic AI Agent Framework</a> to build more effective and efficient compound AI systems. With curated data, we’ll be able to fine tune our AI system using a (relatively) small language model in order to surpass the performance of a larger language model at a quarter of the cost. The improved outputs of our system will increase adoption, creating even more high quality data, further improving our system, and so on, building a flywheel for our Generative AI application to deliver immense value to our business.</p><p>Tech media often misrepresents AI progress through hyperbole about the capabilities of the latest models, an obsession with benchmark performance, and exaggerated claims about prompt engineering’s career prospects. In reality, however, just like data processing, reporting, and traditional machine learning systems before them, AI systems will be valuable to your business not because of generic models, benchmarks, or prompting strategies but because they’ve encapsulated something special about your business. This “something special” could be the proprietary data you’ve processed. It could be a distinctive insight into a domain-specific process. It could be a unique evaluation metric that guides your system towards success. In any case, AI systems will be valuable when you find something that your team is uniquely positioned to capitalize on.</p><p>For our demo, we’ll take synthetically generated data and run Retrieval Augmented Generation (RAG) on it. After some setup and the basic RAG example, we’ll use curated data to align our system to the feedback we receive from users. We’ll do this with <a href="https://docs.databricks.com/en/large-language-models/foundation-model-training/index.html">Mosaic AI Model Training</a> and <a href="https://dspy-docs.vercel.app/">DSPy</a>. Although we aim for a simple objective, getting a proof of concept DSPy up and running felt like a glimpse into the future of software development. Instead of writing imperative instructions and evaluating manually, DSPy allows you to abstract out the steps of your AI system and optimize each step’s prompt automatically. This abstraction makes it easy to put your “something special” into action. If you’re interested in AI, I’d highly recommend giving DSPy a try, and for an introduction try the previous <a href="https://community.databricks.com/t5/technical-blog/models-don-t-matter-building-compound-ai-systems-with-dspy-and/ba-p/75729">Models Don’t Matter</a> article or the excellent <a href="https://www.databricks.com/dataaisummit/session/prompt-engineering-dead-build-llm-applications-dspy-framework">Data AI Summit talk</a> “Prompt Engineering is Dead; Build LLM Applications with DSPy Framework”. With the rapid acceleration in the performance of open source models, most recently the release of Llama-3–405b, fine tuning and distillation will become a crucial part of any AI stack in order to build faster, cheaper, more specialized models. For more on Mosaic AI fine tuning or an intermediate DSPy example, read on!</p><p>To follow along with this demo in your environment, clone the “DSPy and Agent Framework” folder in <a href="https://github.com/josh-melton-db/blogs.git">this repo</a>. For the purposes of this article we’ll assume you’re familiar with setting up a basic RAG system on Databricks so we can focus on fine tuning, Agent Framework, and DSPy. For those who aren’t familiar with RAG on Databricks, take a look at our <a href="https://www.databricks.com/resources/demos/tutorials/data-science-and-ai/lakehouse-ai-deploy-your-llm-chatbot?itm_data=demo_center">Demo Center</a> “first step” example.</p><p>In the DSPy and Agent Framework’s 0_setup notebook, you can set the locations for the demo’s assets. You’ll also see an option to use pre-generated data or set a domain to generate data closer to your own use case. Regardless, this notebook writes the data into a Delta Lake table and saves the configuration which we’ll use as the foundation for our demo. In notebook one, we read the configuration and use it to set CDF on the table and create a vector search index on top. In notebook 2 we set the chain for MLflow. In notebook 3 we log the chain to MLflow, register to Unity Catalog, and deploy to Agent Framework, which is what we’ll use to curate our data. For more detail on what notebooks 2 and 3 are doing, check out the <a href="https://www.databricks.com/resources/demos/tutorials/data-science-and-ai/lakehouse-ai-deploy-your-llm-chatbot?itm_data=demo_center">Demo Center</a> “simple app” example or the <a href="https://ai-cookbook.io/nbs/5-hands-on-build-poc.html">AI Cookbook</a>.</p><p>In notebook 4, we generate sample questions and use Mosaic AI Agent Evalution’s automated judges to evaluate the models. We could also invite (potentially non-Databricks user) experts to review the responses of our models. Experts can mark good and bad responses, edit the responses to provide “golden examples,” and even mark whether the correct context has been retrieved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RK0ujQny5Kx_xKDx" /></figure><p>This is an extremely important point — now that we’ve curated our golden dataset with our automated judges and/or human experts, we’ve developed an invaluable and proprietary asset for our business. With the off-the-shelf llama-3–70b model plugged into our RAG chain, roughly 90% of our responses pass the evaluation of our LLM judges for relevance and correctness. Using our new golden dataset, we’ll aim to improve upon those metrics at a lower TCO. In addition to measures of safety, relevance, and correctness, MLflow provides a convenient log of all of the requests, responses, and evaluations for further inspection. Notably, these evaluations can be run on top of the inference tables logging all request/response pairs from our model serving endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2UGhDYlYGFUQp5ur" /></figure><p>Many companies are at this step today: they have retrieval of their documents, an LLM plugged in, and if they’re ahead of the curve they have the beginnings of evaluation, monitoring, and golden datasets. However, this often isn’t enough to deliver value to end users. After a brief “wow” moment, users of Generative AI systems often churn right back into their previous approaches to solving problems because there’s something not quite good enough about the system. It might be latency or cost, but usually the system is simply too generic even after RAG. In any case, we can dramatically alter the behavior of our system by aligning it to the outputs recorded in our golden dataset. For our example, we’ll aim to align our model to feedback that the responses need to be more concise, and that users like specific, numbered lists of issues to check on to resolve the ticket.</p><p>In notebook 5, we begin developing a more aligned system by fine tuning Llama-3–8b to align it to the golden dataset. By making it easy for our subject matter experts to define what a great response looks like, we’re now able to build a system that is uniquely qualified to deliver that great response. What’s more is that we can do this with a 9x smaller (and 4x cheaper) model than before. Notebook 5 largely copies the <a href="https://www.databricks.com/resources/demos/tutorials/data-science-and-ai/fine-tune-your-own-llm-on-databricks-for-specific-task-and-knowledge?itm_data=demo_center">Demo Center Example</a>, but with the added twist of adding in “distractor documents” as described in the <a href="https://arxiv.org/abs/2403.10131">RAFT paper</a>. RAFT, short for Retrieval Augmented Fine Tuning, is a process which includes both “oracle documents” and “distractor documents” in the prompt for the fine tuning example. While the training data for many open source models includes open internet text or question/answer pairs like “Prompt: What is the capital of France? Response: Paris,” adding the larger context of the documents and forcing the model to pick out the correct answer can noticeably improve the performance of the model for RAG use cases. Including a mix of distractor documents in the prompts for the fine tuning dataset was also shown to improve the model’s ability to discern the most relevant context for answering questions. By showing the model the curated dataset we can infuse it with new knowledge and create a more effective system that assists more users. Additionally, we maintain ownership of the model in the familiar system of MLflow. For more on Mosaic AI Model Training, try the Databricks <a href="https://docs.databricks.com/en/large-language-models/foundation-model-training/index.html">documentation</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uzhVRbflZvilLofF" /></figure><p>Now that we’ve fine tuned a model on our own data we can run a DSPy pipeline, again using the curated data, to determine the optimal prompt for the fine tuned model. The DSPy pipeline shown below adds some more color to the request in order to improve retrieval, then uses chain of thought reasoning to answer the question. According to MLflow’s LLM judges, using our fine tuned model without DSPy optimization gives us relevant responses to 100% of our test data but correct responses to just 80%. While this isn’t far off the 90% mark of Llama-3–70b and will greatly reduce the cost of our system, we’ve got room for improvement.</p><p>In notebook 6 we use DSPy’s MIPROv2 optimizer to automatically determine the best few-shot examples and prompting techniques to leverage. For example, MIPRO adds “high stakes scenarios” to motivate the model to do better. In our trial we generated data about car technician tickets, so DSPy encourages the system, “Imagine you are a leading expert in a critical field, and a team of engineers is relying on your response to troubleshoot a complex technical issue that could have catastrophic consequences if not resolved correctly.” Ultimately, DSPy uses a custom, user-defined metric to determine the best prompt out of numerous similar candidates. This metric is a crucial part of our DSPy pipeline, as it guides our model towards what good looks like and provides another opportunity to align our system to the needs of our users. In our example, we use our metric to aim for hypothetical user feedback demanding more concise answers in the form of numbered lists. Optimizing for a metric like this enables a massively more powerful approach than manual prompting and evaluation as it is faster, less subjective, and more effective. By automating the prompt optimization step we also lower the switching cost of changing models — each new model release no longer requires the hassle of reconfiguring and evaluating various prompting strategies, you can simply run your DSPy pipeline against the new model and rest assured that the prompt is optimal. By using the mixture of fine tuning and DSPy in our attempt we can hit 100% relevance and correctness rates as measured by Agent Evaluation. We do this with a model that is served for 4x cheaper per hour, albeit with a slight increase in the number of tokens per request and a nominal fine tuning and optimization cost up front. Importantly, as we refine our system we’ll improve the outputs, which creates more golden data, which allows us to refine our system even further.</p><pre>class QuestionAnswerAgent(dspy.Module):<br>  def __init__(self, rm):<br>    super().__init__()<br>    self.rm = rm<br>    self.query_expander = dspy.ChainOfThought(QueryExpand)<br>    self.answer_cot = dspy.ChainOfThought(QuestionAnswer)<br><br>  def forward(self, request): # stitch together the RAG chain<br>    expanded_question = self.query_expander(question=request).expanded_question<br>    docs = &quot; &quot;.join(self.rm(expanded_question).docs)<br>    return self.answer_cot(request=request+docs)<br><br>qa_agent = QuestionAnswerAgent(rm)<br>pred = qa_agent(dataset[0].request)<br>pred</pre><p>Returns:</p><pre>Prediction(<br>  rationale=&quot;Request: What can be adjusted to potentially resolve the decreased engine performance during high-speed cruise?\n\nReasoning: Let&#39;s think step by step in order to identify the possible causes of decreased engine performance and potential solutions. We need to analyze the data and observations made during the diagnosis, including the inconsistent spark plug firing sequence, decreased fuel delivery, and misfires.&quot;,<br>  response=&#39;1. Ignition coil dwell time\n2. Spark plug gap&#39;<br>)</pre><p>In conclusion, we’ve walked through an approach to creating proprietary, differentiated data assets for your organization. Mosaic AI Agent Framework allows us to curate a golden dataset for fine tuning and use with Mosaic AI Agent Evaluation. Mosaic AI Model Training allows us to run the fine tuning, while the open source DSPy framework automates our prompt engineering process. Ultimately we showed we can obtain top notch performance and retain ownership of the entirety of our system, including our data and a specialized language model. We were able to re-orient a vanilla RAG solution toward our users’ feedback, and can monitor the results over time using the inference tables of our model serving endpoint. Eventually, we can further refine our system using new requests and feedback. Overall, running the Mosaic AI suite of tools alongside open source frameworks creates a flywheel for cheaper, faster, and better compound AI systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98807d680164" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>