<?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 Charles Menguy on Medium]]></title>
        <description><![CDATA[Stories by Charles Menguy on Medium]]></description>
        <link>https://medium.com/@menguy.charles?source=rss-13004ed1beac------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qTJsBPXzF2n7PhzIJ6DtHQ.png</url>
            <title>Stories by Charles Menguy on Medium</title>
            <link>https://medium.com/@menguy.charles?source=rss-13004ed1beac------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 22:24:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@menguy.charles/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[From Jira to Pull Request: Building an AI Bug-Fix Agent]]></title>
            <link>https://levelup.gitconnected.com/from-jira-to-pull-request-building-an-ai-bug-fix-agent-5eba67cfd34a?source=rss-13004ed1beac------2</link>
            <guid isPermaLink="false">https://medium.com/p/5eba67cfd34a</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[code-generation]]></category>
            <dc:creator><![CDATA[Charles Menguy]]></dc:creator>
            <pubDate>Fri, 10 Apr 2026 03:21:32 GMT</pubDate>
            <atom:updated>2026-04-10T03:21:32.160Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>End-to-end AI bug-fix pipeline: tree-sitter code indexing, hybrid retrieval (vector + BM25), and a ReAct agent loop that processes a ticket and generates a fix.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eCeJPuLL020dZSFXRKpOqQ.png" /></figure><p><a href="https://colab.research.google.com/github/cmenguy/cmenguy.github.io/blob/main/notebooks/2026-04-08-jira-to-pr.ipynb">Run in Google Colab</a> | <a href="https://github.com/cmenguy/cmenguy.github.io/blob/main/notebooks/2026-04-08-jira-to-pr.ipynb">View on GitHub</a></p><p>In <a href="https://medium.com/@menguy.charles/build-your-own-copilot-in-pure-python-7767feaeeeba">Part 1</a> I built a Copilot clone for inline code completion. In <a href="https://medium.com/gitconnected/nl2code-with-agents-from-english-to-production-python-d7cc7bc37501">Part 2</a> I built an NL2Code agent that generates full scripts from English descriptions. Both of those posts are about writing new code. This one goes the other direction: reading a bug ticket, finding the broken code, fixing it, and shipping a pull request. No human in the loop.</p><p>The trigger was a discussion at work about our move to a monorepo. The main motivation for the migration is that AI tools like Claude Code work best when they have all the context in one place: one repo, one dependency graph, one search index. But the flip side is that a monorepo with dozens of contributors generates a lot of GitHub issues and PRs. We started looking at how large open-source projects like Kubernetes and OpenClaw handle that volume, and the conversation landed on automated PR generation for routine bug fixes. The question that stuck with me was: what would it take to go from a Jira ticket saying “NullPointerException in UserService.getProfile()” to a pull request that actually fixes the bug, with no human touching the keyboard in between? I spent the past few weeks building one to find out.</p><p>This is <strong>Part 3 of a 3-part series</strong> on AI-assisted code generation. <a href="https://ai-terminal.net/llm/ai-engineering/code-gen/2026/03/04/build-your-own-copilot/">Part 1</a> covered inline completion (FIM, code models, LoRA fine-tuning). <a href="https://ai-terminal.net/llm/ai-engineering/code-gen/agents/2026/03/09/nl2code-agents/">Part 2</a> covered NL2Code with agents. This post covers the fix side: ingesting a bug ticket, building a searchable knowledge base from the repo, and running a single-agent loop that investigates, patches, tests, and opens a PR.</p><h3>1. Why a Single Agent</h3><p>The obvious architecture for “ticket → PR” is a pipeline of specialized agents. A Triage agent reads the ticket and classifies it. A Planning agent decides what to investigate. A CodeGen agent writes the fix. A Review agent checks the fix. Clean separation of concerns.</p><p>The problem is information loss. Every hand-off between agents requires serializing one agent’s findings into a summary that the next agent consumes. Summaries drop details. The CodeGen agent can’t go back and re-read the stack trace because it only received the Planning agent’s distilled version of it. If the fix attempt reveals that the initial diagnosis was wrong, there’s no way to pivot without restarting the entire pipeline.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e02d00f021735a52f956c4756f9b22a6/href">https://medium.com/media/e02d00f021735a52f956c4756f9b22a6/href</a></iframe><p>A single agent running inside a harness maintains one continuous context window across the entire lifecycle of a ticket. It can re-read the stack trace while writing code. It can change its diagnosis mid-implementation when the code contradicts its initial theory. It can skip investigation steps when the stack trace is already definitive. This mirrors how an experienced engineer actually works: you hold the full problem in your head and fluidly move between investigation, planning, and implementation. You don’t hand off a memo to a different person at each step.</p><p>The trade-off is context window pressure. A 200k-token window fills faster than you’d think when you’re reading full files and collecting search results. I’ll cover how the harness manages that later.</p><h3>2. Architecture: The 30-Second Version</h3><p>Here’s the full system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C69HYggM0RSKveHcHCMt8w.png" /></figure><p>Tickets come in from any source. They get normalized into a standard schema, queued by priority, and dispatched to a worker pod running the agentic harness. The harness gives the agent a set of skills (search, read, edit, test, etc.) and manages context, checkpoints, and permissions. The Knowledge Layer is what makes the agent’s search skills useful. Without it, search_code(&quot;getProfile&quot;) returns nothing.</p><p>Let me build each piece.</p><h3>3. Building the Knowledge Base</h3><p>The agent is only as good as what it can search. If a developer files a ticket about a NullPointerException in UserService.getProfile(), the agent needs to find the actual code for that method, understand what it does, find who calls it, and look up whether anyone has fixed a similar bug before. All of that depends on the Knowledge Layer being populated and fresh.</p><h4>3.1 Parsing Code with tree-sitter</h4><p>The first step is turning source files into structured records. Raw text files are useless for search: you’d be embedding entire files and hoping cosine similarity lands on the right 10-line function in a 500-line file. Instead, we parse each file into its AST and extract every named declaration (function, method, class) as a separate record.</p><p><a href="https://github.com/tree-sitter/tree-sitter">tree-sitter</a> handles this across languages. It produces a concrete syntax tree that we walk to extract symbols with their metadata.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/efac2dc2c8ad6cc5fb49c18d46ac4c50/href">https://medium.com/media/efac2dc2c8ad6cc5fb49c18d46ac4c50/href</a></iframe><p>Given a source file, we parse it and walk the tree to find function and class definitions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66c2d1bc9ac62a7b4b302eae8b716f02/href">https://medium.com/media/66c2d1bc9ac62a7b4b302eae8b716f02/href</a></iframe><p>The _extract_function helper pulls out everything we need for a single symbol:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eea104979d64d01cb58c86fd05e347b4/href">https://medium.com/media/eea104979d64d01cb58c86fd05e347b4/href</a></iframe><p>For a Java file like UserService.java, the parser would emit a record for each method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85c39446330ae59d476586e685e037c9/href">https://medium.com/media/85c39446330ae59d476586e685e037c9/href</a></iframe><h4>3.2 Chunking at AST Boundaries</h4><p>Each parsed symbol becomes one chunk. This is the right granularity for code search: when a ticket mentions getProfile, you want to retrieve that specific method, not the entire 800-line UserService.java file.</p><p>Two exceptions handle edge cases:</p><p><strong>Large functions.</strong> If a function body exceeds 400 tokens, split it into overlapping sub-chunks of 400 tokens each with 80-token overlap. Attach the parent function metadata (name, class, file) to every sub-chunk so retrieval results are always locatable.</p><p><strong>Class-level summaries.</strong> In addition to per-method chunks, emit one chunk per class containing only the declaration, field declarations, and constructor signatures (no method bodies). This lets queries like “what fields does UserService have?” hit a compact chunk instead of wading through all method bodies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0875c2c09a7525e268e053d088bdc0c6/href">https://medium.com/media/0875c2c09a7525e268e053d088bdc0c6/href</a></iframe><h4>3.3 The Enrichment Trick</h4><p>This is the most important design decision in the entire indexing pipeline. What text string you pass to the embedding model determines retrieval quality. Embedding raw source code performs poorly because ticket queries are natural language (“NullPointerException when fetching user profile from cache”) and code is, well, code. The semantic gap between a bug report and a function body is huge.</p><p>The fix is to assemble an <strong>enriched text string</strong> per chunk that combines natural language context with the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b73d58b023ae19f01bfaf814d1e40b0/href">https://medium.com/media/6b73d58b023ae19f01bfaf814d1e40b0/href</a></iframe><p>Why this works: the ticket query “NullPointerException when fetching user profile from cache” is natural language. The enriched string contains the docstring (“Returns null on cache miss”) which bridges the semantic gap. The class and method name provide symbol-level anchoring. The full source is there so the embedding also captures code-level patterns.</p><p>Here’s the template:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfd44cd9d440e144dc49489db027589e/href">https://medium.com/media/dfd44cd9d440e144dc49489db027589e/href</a></iframe><p>Without enrichment, the embedding model sees public User getProfile(String userId) { User user = cache.get(userId); return user; } and has no idea that this function relates to &quot;user profile cache miss.&quot; With enrichment, the docstring, class name, and method signature all contribute semantic signal that the embedding model can use to connect the dots.</p><h4>3.4 Embedding and Storage</h4><p>For the embedding model, I’m using OpenAI’s text-embedding-3-large. The reasoning: since the enriched input strings are a hybrid of natural language and code (not raw code), a general-purpose embedding model handles them well. A code-specialized model like voyage-code-2 would give marginal gains on raw code syntax, but the natural language portions (docstrings, signatures, file paths) are where the ticket-to-code bridge happens. Using the same vendor as the LLM also means one API key, one billing relationship, one rate-limit budget.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/666d7c9c4a6bc0e4dfe1061f28accdeb/href">https://medium.com/media/666d7c9c4a6bc0e4dfe1061f28accdeb/href</a></iframe><p>Each chunk gets stored in three places, each optimized for a different query pattern:</p><p><strong>pgvector</strong> for semantic search. When the agent searches “cache miss null pointer”, the query gets embedded and we find the nearest chunks by cosine similarity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2762d3fd859a0014e34d8aac02205499/href">https://medium.com/media/2762d3fd859a0014e34d8aac02205499/href</a></iframe><p><strong>Elasticsearch</strong> for BM25 keyword search. When the agent searches getProfile, we want exact identifier matching, not fuzzy semantic similarity. The text field is tokenized source code stripped of punctuation so BM25 matches on identifiers like getProfile, userId, cache.</p><p><strong>Postgres</strong> for the dependency graph. Who calls getProfile? What does UserService import? This is where the graph queries live.</p><h4>3.5 Building the Dependency Graph</h4><p>Embedding search answers “what code is semantically related to this ticket?” but it can’t answer “who calls getProfile?&quot; or &quot;what does UserService depend on?&quot;. Those are graph traversal questions, and they come up constantly during bug investigation. If the agent changes getProfile&#39;s return type from User to Optional&lt;User&gt;, it needs to find every caller and update them.</p><p>The dependency graph is extracted during the same tree-sitter parse pass that produces symbol records. For each function body, we walk the AST looking for call expressions and attribute accesses, then resolve them against the symbols we’ve already extracted from the same repo.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ec32cd930e135f15fd4fabb47095beb/href">https://medium.com/media/5ec32cd930e135f15fd4fabb47095beb/href</a></iframe><p>For UserController.get_user(), parsing the body finds self.user_service.get_profile(user_id), which we resolve to the symbol UserService.get_profile. For UserService.get_profile(), we find self.cache.get(user_id), resolved to UserCache.get.</p><p>The resolution step matches raw call text against the known symbol table for the repo. self.user_service.get_profile gets resolved by checking the class&#39;s __init__ to find that self.user_service is a UserService instance, then looking up UserService.get_profile in the symbol index. For cases where static analysis can&#39;t resolve the type (dynamic dispatch, duck typing), we fall back to a name-based heuristic: match get_profile against all symbols named get_profile in the repo and rank by file proximity.</p><p>Each resolved call becomes a row in Postgres:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38746ea1b46d2864acce30b9a78f4cd5/href">https://medium.com/media/38746ea1b46d2864acce30b9a78f4cd5/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e28fb68edf87b654873983c479339540/href">https://medium.com/media/e28fb68edf87b654873983c479339540/href</a></iframe><p>The agent queries this graph through a get_callers skill:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f970cf305b0ab80e8724f087a8f08436/href">https://medium.com/media/f970cf305b0ab80e8724f087a8f08436/href</a></iframe><p>When the agent runs get_callers(&quot;UserService.get_profile&quot;, &quot;org/svc&quot;), it gets back:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4df18ce0633328c30e956b0875d1cfac/href">https://medium.com/media/4df18ce0633328c30e956b0875d1cfac/href</a></iframe><p>That’s two callers to check when changing the return type. Without this graph, the agent would have to do a text search for “get_profile” across the entire repo and parse the results to figure out which matches are actual call sites vs. comments or string literals. The graph makes it a single indexed query.</p><p>The reverse direction is useful too. get_dependencies(&quot;UserService.get_profile&quot;, &quot;org/svc&quot;) tells the agent what get_profile itself depends on (in this case, UserCache.get), which helps when tracing the root cause upstream.</p><h4>3.6 Hybrid Retrieval</h4><p>Neither vector search nor keyword search is good enough on its own. Vector search finds semantically similar code but misses exact identifier matches. BM25 finds exact identifiers but doesn’t understand that “cache miss” relates to cache.get() returning null. The solution is to run both and fuse the results.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0539c2ef3b2c79dad14033e8dd98cf37/href">https://medium.com/media/0539c2ef3b2c79dad14033e8dd98cf37/href</a></iframe><p>Reciprocal rank fusion (RRF) combines the two ranked lists without needing to normalize scores across different systems:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/393a00c1c72894fe55ec32e60b8ae383/href">https://medium.com/media/393a00c1c72894fe55ec32e60b8ae383/href</a></iframe><p>When the agent queries “NullPointerException getProfile cache”, vector search ranks the getProfile chunk high because the enriched embedding matches the semantic meaning. BM25 also ranks it high because &quot;getProfile&quot; and &quot;cache&quot; appear literally in the source. Chunks that score well on both end up at the top.</p><h4>3.7 Keeping It Fresh</h4><p>The knowledge base is useless if it falls behind the code. Every git push to a registered repo triggers a webhook that runs incremental re-indexing:</p><ol><li>git diff --name-only {before_sha}..{after_sha} to get changed files</li><li>For each changed file: re-parse, diff against stored symbols, update only what changed</li><li>New symbols: add chunks, embed, upsert</li><li>Modified symbols: re-embed, upsert (overwrite by chunk_id)</li><li>Deleted symbols: delete from all three stores</li><li>Update last_indexed_sha in the repo registry</li></ol><p>A typical push touching 3–5 files completes in under 10 seconds. The code index is always within one push of being current.</p><h4>3.8 Learning from Past Fixes</h4><p>Two additional indexes give the agent a memory of past work:</p><p><strong>Ticket history.</strong> Past tickets are embedded as &quot;{title}\n\n{description}&quot; and stored. When a new ticket arrives, search_similar_tickets() retrieves past tickets with similar error messages. If someone already filed and fixed &quot;NPE in UserService&quot; three months ago, the agent gets a head start.</p><p><strong>Merged PR store.</strong> Merged PRs linked to bug tickets are stored as &quot;{pr_title}\n\n{pr_description}\n\n{diff_summary}&quot;. The diff summary (not the raw diff) is what gets embedded, because raw diffs are noisy for similarity search. A one-paragraph human-readable summary of what changed and why produces much better recall.</p><h3>4. The Agentic Harness</h3><p>The harness is the runtime that wraps the LLM. It manages the loop, executes skill calls, enforces permissions, and maintains state. The reasoning about what to do lives entirely inside the LLM.</p><h4>4.1 Skills and Permissions</h4><p>The agent has access to a registry of skills, each with a name, input schema, and permission level:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c06a143516941fcbba5de83820576a04/href">https://medium.com/media/c06a143516941fcbba5de83820576a04/href</a></iframe><p>The full registry is injected into the system prompt so the agent always knows what it can do:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a9fb5408b20fb0a70ac13904b1d3c0d/href">https://medium.com/media/2a9fb5408b20fb0a70ac13904b1d3c0d/href</a></iframe><h4>4.2 The System Prompt</h4><p>The system prompt defines methodology and constraints. This is the most important design surface in a single-agent system.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ed2d04ec155dc4880e31e6d8a561b1f/href">https://medium.com/media/7ed2d04ec155dc4880e31e6d8a561b1f/href</a></iframe><h4>4.3 Context Management</h4><p>With a single agent holding everything in one context, window management is the critical engineering problem. A 200k-token window fills fast:</p><ul><li>A single Java file: ~2,000 tokens</li><li>A test suite: ~5,000 tokens</li><li>A search_code result: ~3,000 tokens</li><li>30 steps of history: ~15,000 tokens</li></ul><p>The harness uses three strategies:</p><p><strong>Scratchpad (pinned memory).</strong> The agent writes key findings via remember(). The scratchpad is always present in the context, never compressed. It acts as working memory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be47ff322c7853d088ed829b05db1283/href">https://medium.com/media/be47ff322c7853d088ed829b05db1283/href</a></iframe><p><strong>Rolling compression.</strong> Tool results older than 10 steps get replaced with agent-written summaries. A 300-line file read becomes: [UserService.java read at step 3. Key: getProfile() at line 143 returns raw User from cache.get(). No null check.]</p><p><strong>Selective re-read.</strong> Instead of keeping large files in context, the agent re-reads only the specific lines it needs. read_file(&quot;UserService.java&quot;, start=140, end=155) is cheap and targeted.</p><h3>5. End-to-End: Fixing a NullPointerException</h3><p>Let me walk through the full flow. A developer files a Jira ticket: “NullPointerException in UserService.getProfile() after cache miss. Stack trace: UserService.java:143”.</p><h4>5.1 Ticket Ingestion</h4><p>Jira fires a webhook. The Ingestion Service normalizes it into a TicketEvent:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ee614086ccd0c5bae272afd55efd148/href">https://medium.com/media/3ee614086ccd0c5bae272afd55efd148/href</a></iframe><p>The dispatcher creates a session, clones the repo into a sandbox, creates branch fix/PROJ-1234-auto, and starts the agent loop.</p><h4>5.2 The Agent Loop</h4><p>Here’s the actual execution trace. Each step is one iteration of the THINK → ACT → OBSERVE loop.</p><p><strong>Investigation phase:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41d310fe8be9437a0aeddebc1961eafb/href">https://medium.com/media/41d310fe8be9437a0aeddebc1961eafb/href</a></iframe><p>Seven steps. The agent read one file, ran one search, checked past tickets, and pinned its diagnosis. A multi-agent pipeline would have burned three full context windows to reach the same conclusion.</p><p><strong>Implementation phase:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fbcb996d75e8ce864b02bd0cc0cdb9d/href">https://medium.com/media/7fbcb996d75e8ce864b02bd0cc0cdb9d/href</a></iframe><p>Notice how the agent caught the missing import by running the linter immediately after editing, then fixed it in the next step. This is the self-correction loop that makes the single-agent pattern work. No orchestrator needed.</p><p><strong>Validation phase:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0776faad97636589da52faef0718e8d5/href">https://medium.com/media/0776faad97636589da52faef0718e8d5/href</a></iframe><p>The test failure at step 21 is the kind of thing that trips up pipeline architectures. The CodeGen agent in a multi-agent system would need to signal back to a test-fixing agent, which would need access to the original diagnosis context to understand why the return type changed. Here, the agent just reads the failure message, understands it immediately (it made the change that caused the failure), and fixes it.</p><p><strong>PR creation:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30af07c17931ac916901c894e7f129e7/href">https://medium.com/media/30af07c17931ac916901c894e7f129e7/href</a></iframe><p><strong>Total: 29 skill calls, ~48k tokens, roughly $0.60, about 3 minutes</strong> from ticket creation to PR ready for review.</p><h3>6. The Pieces You Can Build Today</h3><p>The full system has a lot of infrastructure (Kafka, sandboxed containers, webhook services). But the core building blocks are surprisingly accessible. The companion notebook implements three of them end-to-end:</p><ol><li><strong>Code indexing with tree-sitter</strong>: parse a Python repo, extract functions, chunk at AST boundaries</li><li><strong>Hybrid retrieval</strong>: embed chunks with OpenAI, build a BM25 index with rank_bm25, fuse results with RRF</li><li><strong>A simplified agent loop</strong>: process a sample ticket against the indexed repo using a ReAct loop with tool calls</li></ol><p>The gap between the notebook version and the production system is mostly operational: container orchestration, webhook plumbing, and the persistence layer. The intelligence (how to index code, how to search it, how to reason about bugs) is all in the notebook.</p><p>What I’d explore next: feeding the agent’s merged PRs back into the knowledge base so it learns from its own fixes over time. If the agent fixed three NPE-from-cache-miss bugs last month, the fourth one should be faster.</p><p><em>Originally published on </em><a href="https://ai-terminal.net/llm/ai-engineering/code-gen/2026/04/08/jira-to-pr/"><em>AI Terminal</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5eba67cfd34a" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/from-jira-to-pull-request-building-an-ai-bug-fix-agent-5eba67cfd34a">From Jira to Pull Request: Building an AI Bug-Fix Agent</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NL2Code with Agents: From English to Production Python]]></title>
            <link>https://levelup.gitconnected.com/nl2code-with-agents-from-english-to-production-python-d7cc7bc37501?source=rss-13004ed1beac------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7cc7bc37501</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Charles Menguy]]></dc:creator>
            <pubDate>Mon, 16 Mar 2026 15:53:01 GMT</pubDate>
            <atom:updated>2026-03-16T17:13:44.213Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>End-to-end NL2Code pipeline: prompt-based, ReAct, and CodeAct agents generating marketing analytics code from plain English.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kKVOj6VL7gNclO3C6-TOeA.png" /></figure><p><a href="https://colab.research.google.com/github/cmenguy/cmenguy.github.io/blob/main/notebooks/2026-03-09-nl2code-agents.ipynb">Run in Google Colab</a> | <a href="https://github.com/cmenguy/cmenguy.github.io/blob/main/notebooks/2026-03-09-nl2code-agents.ipynb">View on GitHub</a></p><p>In <a href="https://ai-terminal.net/llm/ai-engineering/code-gen/2026/03/04/build-your-own-copilot/">Part 1</a> I built a Copilot clone that does inline code completion. Fine-tuned it on our codebase, got it generating completions that actually follow our patterns. That was the easy half of the code generation story.</p><p>The harder half is what our marketing team actually asks for. They don’t want autocomplete. They want to describe a problem in English (“build me a lookalike audience model from this seed list and score every user in our CDP”) and get back working Python that plugs into our existing data pipelines. The code I shipped in Part 1 would see that request and spit out a generic scikit-learn script that imports libraries we don’t use and writes to a CSV file instead of our Snowflake warehouse. Technically correct. Completely useless in production.</p><p>I’d been building a hardcoded agent for this at work. It followed a fixed sequence: parse the request, pick from a library of pre-built code templates, fill in the blanks. It worked for the five or six patterns we had encoded. But every new request type meant writing more templates. The marketing analytics team kept asking for things slightly outside the templates (“can you also add a holdout group?” or “run this on the EU segment only”), and the agent would just fail. What I wanted was something that could reason about the problem, figure out what code to write, and adapt when the requirements shifted. Not a template engine with an LLM on top, but an actual NL2Code system.</p><p>This post is <strong>Part 2 of a 3-part series</strong> on AI-assisted code generation. <a href="https://ai-terminal.net/llm/ai-engineering/code-gen/2026/03/04/build-your-own-copilot/">Part 1</a> covered inline completion (FIM, code models, LoRA fine-tuning). This post covers NL2Code: instruction-following code generation where you describe what you want and an agent writes it. Part 3 will cover the other side: AI-assisted bug detection and fix suggestion.</p><h3>1. The Problem: Marketing Audience Builder</h3><p>Let me use a concrete example that I’ll carry through the entire post. Our marketing analytics team needs to build lookalike audiences. The workflow:</p><ol><li>Start with a <strong>seed list</strong> of high-value customers (say, users who spent &gt;$500 in the last 90 days)</li><li>Pull <strong>user features</strong> from the CDP (customer data platform): demographics, browsing behavior, purchase history</li><li>Build a <strong>similarity model</strong> that scores every user in the database against the seed list</li><li>Output a <strong>scored audience file</strong> that the campaign platform can ingest, with a holdout group for measurement</li></ol><p>In plain English, the request looks like this:</p><blockquote><em>“Build a lookalike audience from seed list </em><em>high_value_q1.csv. Use purchase frequency, average order value, and days since last purchase as features. Score all users in the </em><em>user_features table. Output the top 10% as the target audience with a 20% holdout group. Write results to </em><em>lookalike_audience_scored.parquet.&quot;</em></blockquote><p>This is a well-defined data science task. A senior engineer could write it in 30 minutes. The question is whether an LLM can write it in 30 seconds, and whether that code is good enough to actually run.</p><p>I’ll walk through four approaches, each one more capable than the last, with real code and honest tradeoffs.</p><h3>2. Approach 1: Single-Shot Prompting</h3><p>The simplest thing that could work. Give the LLM the request, some context about our codebase, and ask it to write the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75585eb8e948f028a61a598f22a81d16/href">https://medium.com/media/75585eb8e948f028a61a598f22a81d16/href</a></iframe><p>Let’s test it with our marketing request:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/046c2ad52272e159dde79e1e971d01f9/href">https://medium.com/media/046c2ad52272e159dde79e1e971d01f9/href</a></iframe><p>The model produces something like this (cleaned up from an actual run):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5e4c499af409907eae929b7b4cc10d9/href">https://medium.com/media/e5e4c499af409907eae929b7b4cc10d9/href</a></iframe><p>This is… decent. The model picked NearestNeighbors with cosine distance, which is a reasonable choice. It handles the scaler correctly (fit on seed, transform both). The holdout logic works.</p><p>But there are real problems:</p><p><strong>No reproducibility.</strong> np.random.rand without a seed means the holdout group changes every run. Any marketer who re-runs this will get different results and wonder why their numbers shifted.</p><p><strong>No validation.</strong> What if the feature columns don’t exist in the data? What if the seed file is empty? Production code needs guardrails.</p><p><strong>No connection to our infra.</strong> This reads from local files. Our data lives in Snowflake. The output goes to S3, not a local parquet file. The model has no idea about our stack.</p><p><strong>Hardcoded feature names.</strong> The feature columns are string literals. If the user specifies different features in the next request, the model might or might not pick them up.</p><p>Single-shot prompting works for throwaway scripts. For anything that touches production, you need more.</p><h4>2.1 When Single-Shot Is Enough</h4><p>Be honest about when simple works. Single-shot is fine for:</p><ul><li>Exploratory data analysis in a notebook</li><li>One-off data transformations you’ll run once</li><li>Prototyping an algorithm before writing production code</li></ul><p>The failure mode is people using single-shot for production code and then spending more time debugging the output than they would have spent writing it themselves.</p><h3>3. Approach 2: Prompt Chaining with Validation</h3><p>The next step: break the problem into stages and validate the output before moving on.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/550aba2a2c788c49429e0ab14d4ea3db/href">https://medium.com/media/550aba2a2c788c49429e0ab14d4ea3db/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b830ff9bb1185ff303a5d5e974f6e2b/href">https://medium.com/media/3b830ff9bb1185ff303a5d5e974f6e2b/href</a></iframe><p>This is better. The plan step forces the model to think about structure before writing code. The review step catches some of the issues (it usually adds random_state=42 and basic column validation). The code-per-step approach keeps each generation focused.</p><p>But it’s still a fixed pipeline. The model plans, codes, reviews, and you get the output. If the review step finds a fundamental design problem (wrong algorithm choice, missing a join between two tables), it can only patch the existing code. It can’t go back and re-plan.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd2461185488c8da7a34c7c7b8c219c6/href">https://medium.com/media/dd2461185488c8da7a34c7c7b8c219c6/href</a></iframe><h3>4. Approach 3: ReAct Agent with Tool Use</h3><p>This is where things get interesting. Instead of a fixed pipeline, give the LLM tools and let it decide what to do at each step.</p><p>The <a href="https://arxiv.org/abs/2210.03629">ReAct pattern</a> (Yao et al., 2022) interleaves reasoning and acting. The agent thinks about what to do, takes an action (calls a tool), observes the result, and decides what to do next. For NL2Code, the tools are things like “read a file,” “check if a column exists,” “run a code snippet,” and “write output.”</p><p>Here’s the tool set:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/130752d4b044fc12332533627b680221/href">https://medium.com/media/130752d4b044fc12332533627b680221/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49bbfa128393e1f709692d902c11ebcf/href">https://medium.com/media/49bbfa128393e1f709692d902c11ebcf/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7aa7b7663fdc2fd2656efcebea40d802/href">https://medium.com/media/7aa7b7663fdc2fd2656efcebea40d802/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d978ce8d957e3af0b683514dfd5e3aa/href">https://medium.com/media/4d978ce8d957e3af0b683514dfd5e3aa/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a5af077ad7bb6e6edb0d51a82ece193/href">https://medium.com/media/4a5af077ad7bb6e6edb0d51a82ece193/href</a></iframe><p>Now the agent loop. This is the core of the ReAct pattern:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e03ed8cd9438421a3aa931e810eee11/href">https://medium.com/media/9e03ed8cd9438421a3aa931e810eee11/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e87809a35532b10d6527c60ea7b33a3/href">https://medium.com/media/1e87809a35532b10d6527c60ea7b33a3/href</a></iframe><p>When you run this on our marketing request, the agent typically:</p><ol><li><strong>Reads the seed file schema</strong> to discover actual column names</li><li><strong>Reads the user features schema</strong> to verify the feature columns exist</li><li><strong>Runs a test snippet</strong> to check data shapes and distributions</li><li><strong>Writes the full script</strong> with validated column names and proper error handling</li><li><strong>Runs the script</strong> to verify it executes without errors</li><li><strong>Fixes any issues</strong> from the test run (missing columns, type mismatches)</li></ol><p>This is a huge improvement. The agent adapts to what it finds in the data. If the seed file has avg_order_val instead of average_order_value, the agent notices and uses the correct column name. If there are nulls in a feature column, the agent adds imputation logic.</p><p>But ReAct has a structural limitation for code generation: every piece of code is a string inside a tool call. The agent writes code, sends it to run_python as a string, reads back the output. There&#39;s no persistent execution environment. Each run_python call starts fresh. The agent can&#39;t build up state incrementally.</p><h3>5. Approach 4: CodeAct Agent</h3><p>This is the approach I ended up using in production. <a href="https://arxiv.org/abs/2402.01030">CodeAct</a> (Wang et al., 2024) flips the tool-use model: instead of the agent calling tools through a JSON API, <strong>the agent writes and executes code directly as its action space</strong>. The code itself is the tool.</p><p>The key insight: for code generation tasks, the most natural “action” an agent can take is writing and running code. Instead of having a run_python tool that takes a code string, the agent just writes Python in a persistent Jupyter-like environment where state carries across turns.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b49001bc3ada112a7c747c031849bfb/href">https://medium.com/media/4b49001bc3ada112a7c747c031849bfb/href</a></iframe><p>The agent loop is simpler than ReAct because there’s only one “tool”: execute code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c93ffeb4f0a34f36b65534cb4847ddf/href">https://medium.com/media/7c93ffeb4f0a34f36b65534cb4847ddf/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c19a6b817cdd9a71fb616f896fd191d7/href">https://medium.com/media/c19a6b817cdd9a71fb616f896fd191d7/href</a></iframe><p>Here’s what a typical CodeAct session looks like for our marketing problem. The agent’s first move is to inspect the data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46bdee7ad19bcf5e370b7eca739472c1/href">https://medium.com/media/46bdee7ad19bcf5e370b7eca739472c1/href</a></iframe><p>The agent sees the actual column names and data types. If the columns are purch_freq, avg_ov, and days_last_purch (as they often are in real marketing data where someone truncated names to fit a legacy system), the agent adapts.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ace09773e657108e29679c08cc3daf02/href">https://medium.com/media/ace09773e657108e29679c08cc3daf02/href</a></iframe><p>Then it builds incrementally:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f63a5fc80fabc12462679d6a154aaf9/href">https://medium.com/media/1f63a5fc80fabc12462679d6a154aaf9/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a8c433ab4a054ffe781b506d825b2ae/href">https://medium.com/media/2a8c433ab4a054ffe781b506d825b2ae/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/efd123f4a9d78ae2e4efc406fb0aa979/href">https://medium.com/media/efd123f4a9d78ae2e4efc406fb0aa979/href</a></iframe><p>The agent tests each function before moving on. If score_users throws an error because the seed list only has 3 users and n_neighbors=5, the agent sees the error, adjusts the parameter, and re-runs. This self-correction loop is the main advantage over chained prompting.</p><p>Finally, the agent writes the complete script:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e164e5ac232c00452ff38e9664b2a64e/href">https://medium.com/media/e164e5ac232c00452ff38e9664b2a64e/href</a></iframe><p>Notice what the CodeAct agent does that the other approaches don’t:</p><ul><li><strong>Discovers actual column names</strong> from the data before writing code</li><li><strong>Handles the </strong><strong>n_neighbors edge case</strong> by using min(n_neighbors, len(seed))</li><li><strong>Adds null handling</strong> because it saw nulls in the data</li><li><strong>Uses a random seed</strong> for reproducibility</li><li><strong>Tests each function</strong> before combining them</li><li><strong>Validates column existence</strong> with explicit error messages</li></ul><h3>6. Why CodeAct Beats ReAct for Code Generation</h3><p>The difference between ReAct and CodeAct for this problem comes down to state management.</p><p>In ReAct, the agent passes code strings to a run_python tool. Each execution is isolated. If the agent defines a function in step 3, it can&#39;t call that function in step 4 unless it re-includes the entire definition. The agent ends up carrying around massive code strings, and the context window fills up fast.</p><p>In CodeAct, the environment is persistent. import pandas as pd in step 1 means pd is available in every subsequent step. The agent can build up a solution the same way a human would in a Jupyter notebook: import things, explore data, define helpers, test them, compose the final result.</p><p>Here’s the practical impact:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04ced8542e6eadc3b292f76e2d3bc91c/href">https://medium.com/media/04ced8542e6eadc3b292f76e2d3bc91c/href</a></iframe><p>The self-correction rate is the big one. When CodeAct runs a snippet and gets an error, the traceback appears in the same environment where all the variables are still alive. The agent can inspect the problematic dataframe, print its dtypes, and fix the issue. When ReAct gets an error, it’s working blind because the execution context is gone.</p><h3>7. Making It Production-Ready</h3><p>The CodeAct agent above works for demos. For production, there are three problems to solve: safety, context, and reliability.</p><h4>7.1 Sandboxing Execution</h4><p>Letting an LLM run arbitrary Python on your infrastructure is a terrible idea without sandboxing. The agent could import os; os.system(&quot;rm -rf /&quot;) or read sensitive environment variables. You need a sandbox.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/561779014c5bbc1caab0692bf1715d06/href">https://medium.com/media/561779014c5bbc1caab0692bf1715d06/href</a></iframe><p>This is a minimal sandbox. For production, use Docker containers, gVisor, or a dedicated code execution service like <a href="https://e2b.dev/">E2B</a> or <a href="https://modal.com/">Modal</a>. The subprocess approach here blocks the most obvious attacks but isn’t airtight.</p><h4>7.2 Injecting Codebase Context</h4><p>The marketing analytics team has internal libraries. There’s a cdp_client module for querying the customer data platform, an audience_io module for writing audience files in the format the campaign platform expects, and a metrics module for computing standard marketing metrics (LTV, RFM scores, etc.).</p><p>The agent needs to know about these. Two approaches work:</p><p><strong>API summaries in the system prompt:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bd7d446bfe701e1e19f646ef78df1ba/href">https://medium.com/media/3bd7d446bfe701e1e19f646ef78df1ba/href</a></iframe><p><strong>Retrieval-augmented context (for larger codebases):</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de44de1bc8dce0ad61f6240a831fce4c/href">https://medium.com/media/de44de1bc8dce0ad61f6240a831fce4c/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/111a5cdcbc7a75d805b205196ca597ae/href">https://medium.com/media/111a5cdcbc7a75d805b205196ca597ae/href</a></iframe><p>With codebase context, the agent generates code that uses cdp_client.query() instead of pd.read_parquet(), calls audience_io.write_audience() instead of to_parquet(), and follows the patterns it sees in the retrieved code.</p><h4>7.3 Reliability: Retry and Validate</h4><p>LLM agents fail. They hallucinate function signatures, get stuck in loops, produce code that doesn’t run. You need a reliability layer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f551fa3103a084594b734a706cfb35b/href">https://medium.com/media/7f551fa3103a084594b734a706cfb35b/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dec52d4743b9294d44a8c89b49e4d450/href">https://medium.com/media/dec52d4743b9294d44a8c89b49e4d450/href</a></iframe><p>In practice, the CodeAct agent produces valid code on the first try about 85% of the time. With one retry, that goes to ~95%. The remaining 5% are usually requests that are genuinely ambiguous or require domain knowledge the agent doesn’t have.</p><h3>8. Head-to-Head: All Four Approaches</h3><p>Let me put all four approaches through the same set of five marketing requests and compare results. These are real request patterns from our team:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83fe56db6b6f22fb892ca79a4de70a7b/href">https://medium.com/media/83fe56db6b6f22fb892ca79a4de70a7b/href</a></iframe><p>And the aggregate metrics:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d23bc95f40bd155a2c1f0e86134212a/href">https://medium.com/media/0d23bc95f40bd155a2c1f0e86134212a/href</a></iframe><p>CodeAct wins on correctness while being faster and cheaper than ReAct. The speed advantage comes from needing fewer steps (persistent state means less re-computation). The cost advantage comes from shorter context windows (no repeated code blocks).</p><p>The one place single-shot wins is latency. If you need code in 5 seconds and “good enough” is acceptable, single-shot is hard to beat. For production code that needs to actually work, the extra 25 seconds of CodeAct is worth it.</p><h3>9. Extending to Other Domains</h3><p>The marketing audience builder is one example, but the pattern works for any domain where non-engineers need to request code from a system. Here’s how the CodeAct approach applies to three other cases I’ve seen at work:</p><p><strong>Data engineering:</strong> “Create an Airflow DAG that runs the customer churn model daily, reads from the user_events table, writes predictions to churn_scores, and sends a Slack alert if the model&#39;s AUC drops below 0.75.&quot; The agent inspects the existing DAG templates in the repo, follows the team&#39;s naming conventions, and wires up the Slack notification correctly.</p><p><strong>Finance analytics:</strong> “Backtest a momentum strategy on the S&amp;P 500. Use a 12-month lookback, rebalance monthly, hold the top decile. Compare against buy-and-hold.” The agent pulls price data, implements the strategy, runs the backtest, and generates a comparison chart.</p><p><strong>Product analytics:</strong> “Build a retention cohort analysis. Group users by signup month, track weekly active status for 12 weeks, output a heatmap.” The agent queries the events table, pivots the data into cohort format, and generates the visualization.</p><p>The common thread: a domain expert describes what they want, and the agent writes code that fits the team’s stack. The CodeAct pattern handles all of these because the agent can inspect real data, test incrementally, and adapt to what it finds.</p><h3>10. What I’d Do Differently Next Time</h3><p>After running this in production for a few weeks, some lessons:</p><p><strong>Start with the system prompt, not the agent loop.</strong> I spent too long tweaking the ReAct/CodeAct loop mechanics and not enough time on the system prompt that teaches the agent about our codebase. The quality of the codebase context in the prompt matters more than the agent architecture.</p><p><strong>Log everything.</strong> Every agent step, every code execution, every error. When the agent generates bad code, you need to trace back through its reasoning to understand why. I built a simple logging layer that writes the full conversation to a JSONL file. It’s been the most useful debugging tool.</p><p><strong>Let humans edit, not just approve.</strong> The first version had a binary approve/reject flow. Users would reject code, the agent would retry, and everyone was frustrated. The current version shows the generated code in an editor where users can make small edits before running. Most of the time they change one or two lines (a parameter value, a column name) and approve. That’s a much better UX than regenerating from scratch.</p><p><strong>Evaluation is the hard part.</strong> Measuring whether generated code is “correct” is genuinely difficult. It’s not like code completion where you can compute edit distance against a known answer. For NL2Code, there are many valid solutions. I ended up using a combination of: (1) does it parse, (2) does it run on test data, (3) does a human reviewer rate it as correct. The human review is the bottleneck.</p><p>Next up in Part 3: we flip the direction entirely. Instead of generating new code from English descriptions, we’ll build a system that reads existing code, spots bugs and anti-patterns, and proposes fixes. Same agent architecture, very different evaluation problem.</p><p><em>Originally published on </em><a href="https://ai-terminal.net/llm/ai-engineering/code-gen/agents/2026/03/09/nl2code-agents/"><em>AI Terminal</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7cc7bc37501" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/nl2code-with-agents-from-english-to-production-python-d7cc7bc37501">NL2Code with Agents: From English to Production Python</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Your Own Copilot in Pure Python]]></title>
            <link>https://medium.com/@menguy.charles/build-your-own-copilot-in-pure-python-7767feaeeeba?source=rss-13004ed1beac------2</link>
            <guid isPermaLink="false">https://medium.com/p/7767feaeeeba</guid>
            <category><![CDATA[code-generation]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Charles Menguy]]></dc:creator>
            <pubDate>Sat, 07 Mar 2026 19:29:24 GMT</pubDate>
            <atom:updated>2026-03-07T20:03:21.820Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>A complete, runnable AI code completion tool: FIM inference, LSP-style server, and LoRA fine-tuning on a custom codebase.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xq3u4F0CSG0DNp3L5WSpwg.png" /></figure><p><a href="https://colab.research.google.com/github/cmenguy/cmenguy.github.io/blob/main/notebooks/2026-03-04-build-your-own-copilot.ipynb">Run in Google Colab</a> | <a href="https://github.com/cmenguy/cmenguy.github.io/blob/main/notebooks/2026-03-04-build-your-own-copilot.ipynb">View on GitHub</a></p><p>In the <a href="https://ai-terminal.net/llm/ai-engineering/agents/2026/02/05/skills-deep-dive/">skills post</a> I mentioned we’d been building agent skills at work, mostly for marketing ML workflows. One of those workflows is NL2Code: a user describes what they want in plain English (“build me a lookalike audience from this seed list using cosine similarity”), and the agent writes the Python code. It works surprisingly well for self-contained scripts. But it fell apart the moment we needed the generated code to fit into our existing codebase. The agent would write perfectly valid Python that imported libraries we don’t use, called APIs that don’t exist in our stack, and followed patterns that look nothing like the code we actually ship.</p><p>That got me thinking about how tools like Copilot actually work. Not the product, but the machinery underneath: how do you take a general-purpose code model and make it write code that feels like it belongs in <em>your</em> repo? I spent a few weekends digging into the full pipeline, from how code completion models are structured, to how fill-in-the-middle works, to how you fine-tune on a specific codebase. This post is what came out of that: a working AI coding tool, built from scratch in Python, that you can point at your own code.</p><p>This is <strong>part 1 of a 3-part series</strong> on AI-assisted code generation. This post covers the inline completion side: FIM, code models, fine-tuning, and building a working Copilot clone. Part 2 will tackle NL2Code: instruction-following code generation, where you describe what you want in English and the model writes the full implementation. Part 3 will go after the other end of the lifecycle: an AI-assisted bug detection and fix suggestion system that reads your code, spots problems, and proposes patches.</p><h3>1. How Code Completion Actually Works</h3><p>Before building anything, let’s understand what’s happening when Copilot suggests code in your editor.</p><p>A code completion model is a language model trained on code. Same transformer architecture as GPT, same next-token prediction objective, just trained on GitHub repos instead of web text. Models like CodeLlama, StarCoder, and DeepSeek-Coder are all in this family. They predict: given the code written so far, what token comes next?</p><p>But code completion has a problem that regular text doesn’t. When you’re typing in an editor, the cursor isn’t always at the end of the file. You might be in the middle of a function, with code above <em>and</em> below. A model trained purely on left-to-right next-token prediction can only see what’s above the cursor. It has no idea what comes after.</p><p>This is where <strong>Fill-in-the-Middle (FIM)</strong> comes in.</p><h4>1.1 Fill-in-the-Middle: The Key Trick</h4><p>FIM was introduced in the <a href="https://arxiv.org/abs/2207.14255">Bavarian et al. 2022</a> paper from OpenAI. The idea is simple: during training, you take a code file, split it into three parts (prefix, middle, suffix), and train the model to predict the middle given the prefix and suffix.</p><p>Here’s how a normal training example looks:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0595c44174636fcc96e5c9f1f12a154b/href">https://medium.com/media/0595c44174636fcc96e5c9f1f12a154b/href</a></iframe><p>And here’s the same example reformatted for FIM training:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e5f4f59d5a1f07cafe66e739f28fba8/href">https://medium.com/media/4e5f4f59d5a1f07cafe66e739f28fba8/href</a></iframe><p>The model learns to take the prefix (everything before the cursor) and the suffix (everything after), and generate the middle (what should go where the cursor is). Three special tokens mark the boundaries: &lt;fim_prefix&gt;, &lt;fim_suffix&gt;, and &lt;fim_middle&gt;.</p><p>There are two formats for arranging these pieces:</p><p><strong>PSM (Prefix-Suffix-Middle):</strong> &lt;fim_prefix&gt;PREFIX&lt;fim_suffix&gt;SUFFIX&lt;fim_middle&gt;MIDDLE</p><p><strong>SPM (Suffix-Prefix-Middle):</strong> &lt;fim_suffix&gt;SUFFIX&lt;fim_prefix&gt;PREFIX&lt;fim_middle&gt;MIDDLE</p><p>Most production models (StarCoder, CodeLlama, DeepSeek-Coder) use PSM. The key insight from the paper: FIM can be added to training with almost no cost. You take a fraction of your training examples (typically 50–90%), reformat them as FIM, and the model learns both regular left-to-right completion and fill-in-the-middle, with no degradation on either task.</p><h4>1.2 What Makes Code Models Different</h4><p>Code LLMs aren’t just GPT trained on code. A few things change:</p><p><strong>Tokenizer.</strong> Code has different statistical patterns than English. Indentation matters, variable names repeat, and syntax tokens like def, class, (, ) need to be handled efficiently. Code tokenizers typically treat common indent levels (2 spaces, 4 spaces, tab) as single tokens and handle code-specific punctuation better than a general-purpose BPE tokenizer.</p><p><strong>Context length.</strong> Code files are long. A typical Python file might be 500 lines, and you often need cross-file context (imports from other modules, class definitions in other files). Production code models typically support 8k-16k tokens, with some (DeepSeek-Coder-V2, CodeLlama) going up to 100k+.</p><p><strong>Training data.</strong> The training set is filtered, deduplicated code from GitHub (or similar sources), often with license filtering, quality scoring, and language balancing. StarCoder was trained on The Stack, roughly 6TB of permissively licensed source code across 300+ languages.</p><h3>2. Building a Minimal Code Completion Engine</h3><p>Let’s build the core of a Copilot-like tool. We’ll use a small code model and build the FIM inference pipeline from scratch.</p><h4>2.1 Picking a Model</h4><p>For this post, I’m using <a href="https://huggingface.co/bigcode/tiny_starcoder_py">bigcode/tiny_starcoder_py</a>. It’s a 164M parameter model trained on Python code with FIM support. Small enough to run on a laptop CPU (slowly) or a free Colab GPU (quickly), but large enough to generate real Python code.</p><p>For production work, you’d use something bigger: StarCoder2–15B, DeepSeek-Coder-33B, or CodeLlama-34B. The pipeline we’re building is identical regardless of model size.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a3088c4bc4adc14b52a2a086e6c0abc/href">https://medium.com/media/5a3088c4bc4adc14b52a2a086e6c0abc/href</a></iframe><h4>2.2 FIM Inference</h4><p>Here’s the core function: given a prefix and suffix (the code before and after the cursor), generate the missing middle.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59da9b0c0a7392f2f463475a2397acb5/href">https://medium.com/media/59da9b0c0a7392f2f463475a2397acb5/href</a></iframe><p>Low temperature (0.2) makes completions more deterministic, which is what you want for code. You’re not looking for creativity; you’re looking for the most likely correct code. top_p=0.95 with nucleus sampling filters out very unlikely tokens.</p><p>Let’s test it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e56f6010cf63d69b1e079d733809e87/href">https://medium.com/media/4e56f6010cf63d69b1e079d733809e87/href</a></iframe><p>The model should generate something like if arr[mid] == target:\n return mid, which is the missing condition in a binary search. It sees the elif below and understands the branching structure.</p><h4>2.3 Left-to-Right Completion</h4><p>FIM is for when there’s code on both sides of the cursor. When the cursor is at the end of the file (or end of a function), regular left-to-right completion works:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/380d7d9fb6afbb5c8c136b0fcf8f47f2/href">https://medium.com/media/380d7d9fb6afbb5c8c136b0fcf8f47f2/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a84b0650766c621895fcb20281f4650/href">https://medium.com/media/6a84b0650766c621895fcb20281f4650/href</a></iframe><p>This should produce something reasonable: open the file, load the JSON, return the result. The docstring gives the model a clear signal about what the function should do.</p><h4>2.4 Putting It Together: An Editor-Like Interface</h4><p>A real Copilot integration triggers on keystrokes, debounces requests, and sends completions back to the editor via LSP (Language Server Protocol) or a proprietary protocol. Here’s a simplified version that simulates the decision logic:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/abb8975fac92df7097f3d4b7795a9437/href">https://medium.com/media/abb8975fac92df7097f3d4b7795a9437/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ecad8718fed96eda43ddf74a96ee0de/href">https://medium.com/media/9ecad8718fed96eda43ddf74a96ee0de/href</a></iframe><p>The function detects there’s code below (get_history method) and uses FIM. It should fill in the subtract body in a way that&#39;s consistent with the add pattern above it, something like result = a - b followed by the history append.</p><h3>3. Building an LSP-Style Completion Server</h3><p>The completion engine above is the brains, but it needs a body. In the real world, Copilot talks to your editor through a server. Let’s build a minimal HTTP server that acts like a code completion API. Any editor with an HTTP-capable plugin can talk to this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/361bf64e0f9dda9ce9ffaa11fbe1b496/href">https://medium.com/media/361bf64e0f9dda9ce9ffaa11fbe1b496/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/271ea87381a8f9fc51780a9192de96a4/href">https://medium.com/media/271ea87381a8f9fc51780a9192de96a4/href</a></iframe><p>Test it with curl:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b02ac4fdd64d9d930b67faa986a98e4b/href">https://medium.com/media/b02ac4fdd64d9d930b67faa986a98e4b/href</a></iframe><p>That’s it. You now have a code completion server running locally. In production, you’d add request batching (queue up multiple keystrokes and only process the latest), caching (if the prefix hasn’t changed, return the cached completion), and streaming (send tokens as they’re generated rather than waiting for the full completion).</p><h3>4. How Production Copilots Are Actually Built</h3><p>Our toy server works, but production tools like Copilot, Cursor, and Cody have layers of optimization on top. Here’s what the real architecture looks like:</p><h4>4.1 Context Gathering</h4><p>The biggest gap between our toy and production is context. We only use the current file. Production tools gather context from:</p><p><strong>Open tabs.</strong> If you have utils.py and models.py open, the completion engine sees relevant snippets from both.</p><p><strong>Import graph.</strong> When the current file imports from mypackage.data_loader, the tool fetches the signatures and docstrings from that module.</p><p><strong>Repository-level retrieval.</strong> Some tools (Sourcegraph Cody, Continue) use embedding-based search to find the most relevant code snippets across the entire repo and inject them into the prompt.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/033e2726a39d0731b6d782634e11c1ad/href">https://medium.com/media/033e2726a39d0731b6d782634e11c1ad/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1621f45a915a4605428edb3b9e7faa9/href">https://medium.com/media/d1621f45a915a4605428edb3b9e7faa9/href</a></iframe><h4>4.2 Post-Processing</h4><p>Raw model output often needs cleanup before showing it to the user:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c47c417d3e91de87f218fdf8bfb0039/href">https://medium.com/media/7c47c417d3e91de87f218fdf8bfb0039/href</a></iframe><p>This handles three common issues: stopping the completion before it starts generating a new function (the model doesn’t know where to stop), fixing indentation to match the surrounding code, and deduplicating against code that already exists below the cursor.</p><h4>4.3 Latency Budget</h4><p>Here’s the latency breakdown for a production code completion:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbf2a64dcd315404955ac0c272fdd1e8/href">https://medium.com/media/fbf2a64dcd315404955ac0c272fdd1e8/href</a></iframe><p>The debounce is the most important optimization. You don’t fire the model on every keystroke. You wait for the user to pause, then trigger. If they start typing again before the completion arrives, you cancel it and wait for the next pause.</p><p>Most completions are short: a single line, maybe two. The model generates 20–50 tokens, not 200. This is why code completion can feel instant even though the underlying model is the same one that takes 30 seconds to write a full function in a chat interface.</p><h3>5. Fine-Tuning on Your Codebase</h3><p>This is the part I actually set out to understand. A general code model writes generic Python. It doesn’t know about your internal libraries, your coding conventions, or your domain-specific patterns. Fine-tuning bridges that gap.</p><h4>5.1 Why Fine-Tune (and When Not To)</h4><p>There are three approaches to making a code model work with your codebase, and they exist on a spectrum of effort vs. payoff:</p><p><strong>Retrieval-Augmented Generation (RAG).</strong> Fetch relevant code snippets from your repo and inject them into the prompt. Zero training required. Works well when your codebase follows standard patterns and the model just needs examples to follow.</p><p><strong>Fine-tuning with LoRA.</strong> Train the model’s weights on your codebase. Takes a few hours on a single GPU. The model learns your patterns, naming conventions, internal APIs. Works well when your codebase has strong conventions that differ from generic Python.</p><p><strong>Full fine-tuning.</strong> Update all model weights. Expensive, requires multiple GPUs. Rarely necessary for code completion. Only makes sense if you have a very large, very distinctive codebase (hundreds of thousands of files) and the model needs to deeply learn a new programming language or paradigm.</p><p>For most teams, RAG gets you 70% of the way. Fine-tuning with LoRA gets you to 90%. Full fine-tuning is almost never worth the cost for code completion.</p><p>Here’s a quick comparison:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/035ef6b260b09544f1df917d384f7c20/href">https://medium.com/media/035ef6b260b09544f1df917d384f7c20/href</a></iframe><h4>5.2 Preparing Training Data</h4><p>This is where most people make mistakes. The quality of your training data determines the quality of your fine-tuned model. Let’s build the data preparation pipeline.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/323f7e6b387f99467f9c1f74214e5e55/href">https://medium.com/media/323f7e6b387f99467f9c1f74214e5e55/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50ae10faf128f58e3c82cc311ddb9bc6/href">https://medium.com/media/50ae10faf128f58e3c82cc311ddb9bc6/href</a></iframe><h4>5.3 Creating FIM Training Examples</h4><p>For fine-tuning a code completion model, you want FIM-formatted examples. Each example takes a file, picks a random split point, and creates a prefix-suffix-middle triple.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26b67bca4c76a02563c7de4f8cfceeb9/href">https://medium.com/media/26b67bca4c76a02563c7de4f8cfceeb9/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be92c80140adeaa487aef430d98a95f5/href">https://medium.com/media/be92c80140adeaa487aef430d98a95f5/href</a></iframe><p>For a medium-sized repo (500 Python files), this generates roughly 1500 training examples. That’s plenty for LoRA fine-tuning.</p><h4>5.4 The LoRA Fine-Tuning Loop</h4><p>If you read the <a href="https://ai-terminal.net/llm/fine-tuning/2025/12/28/lora-deep-dive/">LoRA post</a>, you know the mechanics. Here’s the application to code completion. We’re using peft and trl to keep it concise, but the underlying math is the same.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7a018c1d89e9d2901a0758299b70567/href">https://medium.com/media/b7a018c1d89e9d2901a0758299b70567/href</a></iframe><p>This should print something like: trainable params: 3,481,600 || all params: 167,625,728 || trainable%: 2.08%. About 2% of the parameters, trained on your code. On a larger model like StarCoder2-15B, that percentage drops below 0.5%.</p><p>Why these target modules? In the StarCoder architecture, c_attn handles the query/key/value projections (this is where the model learns <em>what to attend to</em> in your code), c_proj is the attention output (how it combines attended information), and c_fc is the MLP (where pattern recognition happens). Targeting these three catches the most important weights for learning code patterns without touching the embedding layers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74b1e21d9cfdac255e11018b24a6a1bc/href">https://medium.com/media/74b1e21d9cfdac255e11018b24a6a1bc/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97e3872a987f6e78b953492cb75de8c5/href">https://medium.com/media/97e3872a987f6e78b953492cb75de8c5/href</a></iframe><p>A few things about the hyperparameters. Learning rate 2e-4 is standard for LoRA fine-tuning. Much higher and you&#39;ll overfit fast; much lower and three epochs won&#39;t be enough. Cosine scheduler with warmup is the safest default. Batch size 4 with gradient accumulation 4 gives an effective batch size of 16. For code completion, you want small effective batch sizes because each example is fairly long (a full file context).</p><h4>5.5 Loading and Using the Fine-Tuned Model</h4><p>After training, your LoRA adapter weights are saved separately from the base model. Loading them is straightforward:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51d4756f17aec3213a2f0c38c6f03932/href">https://medium.com/media/51d4756f17aec3213a2f0c38c6f03932/href</a></iframe><p>The merge_and_unload() call is important for production. During training, LoRA adds a side path to each targeted layer: the output is base_output + lora_output. At inference time, you can merge the LoRA weights directly into the base weights:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/109/0*i8eIPckyImvL2qgx" /></figure><p>And run the model as if it were never LoRA-trained. Same quality, zero overhead.</p><h4>5.6 The Multi-Repo Problem: Adapters vs. Merging</h4><p>This is the question I kept circling back to at work. We don’t have one repo. We have a dozen. The data engineering team has their repo with Spark pipelines and Airflow DAGs. The ML team has a separate repo full of PyTorch training code and custom metrics. Marketing analytics has a repo that’s mostly pandas and SQL generation. Each one has its own conventions, internal libraries, and idioms.</p><p>RAG handles this naturally. You point the embedding index at whichever repo the user is currently working in, and the retrieval layer fetches relevant snippets from that repo. Switch repos, switch index. No retraining, no weight changes.</p><p>LoRA is different. If you train a single adapter on all repos pooled together, the model learns a blurry average of everyone’s patterns. The Spark repo uses snake_case everywhere and imports from pyspark.sql.functions. The ML repo uses short variable names and imports from custom internal modules. Training on both means the model sometimes suggests Spark imports when you&#39;re writing PyTorch code. Not great.</p><p>The better approach: <strong>train a separate LoRA adapter per repo</strong> (or per team, or per domain, whatever boundary makes sense). This is where LoRA’s architecture actually shines. Each adapter is tiny. For the tiny_starcoder_py model we&#39;re using, the adapter is about 14MB. For a production 15B model with r=16, each adapter is around 50-100MB. You can store dozens of them.</p><p>Here’s what that looks like in practice:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c51e71a095f5424b24fb310aafd91b2/href">https://medium.com/media/3c51e71a095f5424b24fb310aafd91b2/href</a></iframe><p>At serving time, you detect which repo the user is in (from their editor workspace, git remote, or an explicit config) and load the matching adapter. The base model stays in memory; you’re just swapping a small set of low-rank matrices on top.</p><p>The question of <strong>merge vs. keep separate</strong> depends on your serving setup:</p><p><strong>Keep adapters separate</strong> when you need to switch between repos during a session. PEFT supports loading multiple adapters onto the same base model and switching between them at inference time with zero reloading:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/879037921f5b015429aef84d7261cd07/href">https://medium.com/media/879037921f5b015429aef84d7261cd07/href</a></iframe><p>The switching is near-instant because all adapters are already in memory. The memory overhead is small: each adapter adds about 2% to the base model’s footprint with our config. Three adapters means ~6% extra memory, which is negligible.</p><p><strong>Merge into the base weights</strong> when you’re deploying a dedicated instance per team or per repo. Merging eliminates the LoRA forward pass overhead (the extra matrix multiplications through B and A), which saves a few milliseconds of latency per completion. If the data engineering team has their own completion server, merge their adapter and serve a single clean model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/debec1da4f278c11e7d575fc3dccae0b/href">https://medium.com/media/debec1da4f278c11e7d575fc3dccae0b/href</a></iframe><p>There’s a third option that I haven’t tried in production but is worth knowing about: <strong>adapter merging</strong>. You can combine multiple LoRA adapters into one by weighted averaging their B and A matrices. This is useful if you want a single adapter that captures patterns from, say, three closely related repos:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/115bb9672681bc858c57590dcf21f75a/href">https://medium.com/media/115bb9672681bc858c57590dcf21f75a/href</a></iframe><p>The weights control how much each repo’s patterns contribute. If the data engineering repo is the primary codebase and the ML repo shares some common utilities, a 70/30 split makes sense. The density parameter in TIES-Merging controls sparsity: at 0.5, it keeps only the top 50% of adapter parameters by magnitude, which reduces interference between the two adapters.</p><p>In my experience, the cleanest setup for most companies is: <strong>separate adapters, loaded on demand, no merging</strong>. The memory is cheap, the switching is fast, and you avoid the blurring problem entirely. Reserve adapter merging for cases where repos genuinely share patterns and you’ve measured that the combined adapter outperforms either individual one.</p><p>Here’s the decision tree I’ve landed on:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4deb008fd2fd549f917271581818bfe1/href">https://medium.com/media/4deb008fd2fd549f917271581818bfe1/href</a></iframe><h3>6. Evaluation: How Do You Know It’s Working?</h3><p>Fine-tuning without evaluation is guesswork. Here’s how to measure whether your fine-tuned model is actually better at completing your code.</p><h4>6.1 Held-Out File Completion</h4><p>The simplest test: hold out 10–20% of your repo’s files, then measure how well the model completes code from those files.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46a8af19673b6e7f06064c6c59bab384/href">https://medium.com/media/46a8af19673b6e7f06064c6c59bab384/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e7012a56bebdb778680f5c0688bbc08/href">https://medium.com/media/9e7012a56bebdb778680f5c0688bbc08/href</a></iframe><p>Exact match rates for single-line completion on a fine-tuned model typically land between 25–40% for internal codebases. That sounds low until you consider that there are often multiple valid ways to write a line of code. Edit distance is a better proxy: a fine-tuned model should average 3–5 characters of edit distance where a base model averages 15–20.</p><h4>6.2 The Real Test: Side-by-Side</h4><p>Numbers are useful, but the most telling evaluation is qualitative. Take 10 examples from your codebase and compare the base model’s completion against the fine-tuned model’s:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55a03d76c15ddc01dc0a72df8b3aa28f/href">https://medium.com/media/55a03d76c15ddc01dc0a72df8b3aa28f/href</a></iframe><p>What you’re looking for: does the fine-tuned model use your internal function names? Does it follow your naming conventions (snake_case vs camelCase)? Does it import from your internal modules instead of suggesting import pandas as pd for everything? These qualitative differences are often more valuable than the quantitative metrics.</p><h3>7. Techniques and Tradeoffs: A Practical Guide</h3><p>Here’s a summary of the main approaches to building a code completion tool, with honest assessments of when each one works.</p><h4>7.1 Approach 1: Off-the-Shelf Model + RAG</h4><p><strong>What:</strong> Use StarCoder2 or DeepSeek-Coder out of the box. Build a retrieval layer that fetches relevant code snippets from your repo and injects them into the prompt.</p><p><strong>How it works:</strong> Embed all files in your repo with a code embedding model (like nomic-embed-code or voyage-code-3). At completion time, embed the current context, find the nearest neighbors, and prepend them to the prompt.</p><p><strong>Pros:</strong> No training. Works immediately. Easy to keep up-to-date (just re-embed when code changes).</p><p><strong>Cons:</strong> Limited context window means you can only inject a few snippets. The model still doesn’t “know” your patterns; it just has examples in context. Retrieval quality is the bottleneck.</p><p><strong>Best for:</strong> Small teams, codebases under 100k lines, standard Python patterns.</p><h4>7.2 Approach 2: LoRA Fine-Tuning (What We Built)</h4><p><strong>What:</strong> Fine-tune the model on your codebase with LoRA. The model learns your patterns, conventions, and internal APIs as weight updates.</p><p><strong>How it works:</strong> As described above. Prepare FIM training data from your repo, train LoRA adapters for a few hours, merge and deploy.</p><p><strong>Pros:</strong> Model internalizes your patterns. Better completions for internal APIs. Works with any context window since the knowledge is in the weights.</p><p><strong>Cons:</strong> Stales over time as code changes. Need to retrain periodically (weekly or monthly). Requires a GPU for training.</p><p><strong>Best for:</strong> Teams with strong coding conventions, internal libraries, or domain-specific patterns. Codebases over 50k lines.</p><h4>7.3 Approach 3: RAG + LoRA Together</h4><p><strong>What:</strong> Combine both approaches. Fine-tune for style and conventions, use RAG for specific API signatures and recent code.</p><p><strong>This is what most production Copilot-like tools actually do.</strong> The fine-tuned model knows your general patterns; the RAG layer provides specific, up-to-date context. They’re complementary.</p><p><strong>Best for:</strong> Any team that’s serious about code completion quality.</p><h4>7.4 Approach 4: Continued Pretraining</h4><p><strong>What:</strong> Before LoRA, do a round of continued pretraining on your full codebase. This teaches the model your “language” at a deeper level than LoRA can.</p><p><strong>How it works:</strong> Standard causal language model training on your code, at a low learning rate, for 1–2 epochs. Then apply LoRA on top for task-specific fine-tuning.</p><p><strong>Pros:</strong> Deeper knowledge of your codebase. Better for very large, distinctive codebases.</p><p><strong>Cons:</strong> Expensive. Needs multiple GPUs and days of training. Risk of catastrophic forgetting (the model gets worse at general Python while getting better at your specific code).</p><p><strong>Best for:</strong> Companies with 1M+ lines of highly distinctive code (custom DSLs, unusual frameworks).</p><h3>8. What’s Actually Running in Production</h3><p>Let me close the loop on the original question: how does this relate to the NL2Code agent I’m building at work?</p><p>The Copilot pipeline we built here is for <strong>inline code completion</strong>: short, fast, triggered on keystrokes. The NL2Code use case is different: it’s <strong>instruction-following code generation</strong>, where you describe what you want in natural language and the model writes a complete function or script.</p><p>But the fine-tuning pipeline is almost identical. The difference is in the training data format:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea49f73dee6ce98e585af3271bb8a535/href">https://medium.com/media/ea49f73dee6ce98e585af3271bb8a535/href</a></iframe><p>Same base model, same LoRA setup, different data format. For the NL2Code agent, I swapped FIM examples for instruction/response pairs extracted from our codebase (using docstrings and function signatures as the “instruction” and the function body as the “response”). The fine-tuning loop didn’t change at all.</p><p>The key takeaway from this whole exercise: there’s no magic in Copilot. It’s a code LLM with FIM training, a context-gathering layer, and (probably) fine-tuning on accepted completions. Each piece is understandable, buildable, and improvable. The competitive moat isn’t the model architecture. It’s the data flywheel: every accepted completion becomes a training signal that makes the next completion better. That’s harder to replicate than any of the code in this post.</p><p>Next up in part 2: an NL2Code agent that takes a plain-English description and generates a complete function or script that fits into your codebase. Same fine-tuning pipeline, different data format, very different evaluation problem. And in part 3, we’ll flip the direction entirely: instead of writing new code, we’ll build a system that reads existing code, finds bugs, and suggests fixes.</p><p><em>Originally published on </em><a href="https://ai-terminal.net/llm/ai-engineering/code-gen/2026/03/04/build-your-own-copilot/"><em>AI Terminal</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7767feaeeeba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Look-Alike Audiences: AI-enabled Audience Expansion in Real-Time CDP]]></title>
            <link>https://medium.com/adobetech/look-alike-audiences-ai-enabled-audience-expansion-in-real-time-cdp-e143a1ce93de?source=rss-13004ed1beac------2</link>
            <guid isPermaLink="false">https://medium.com/p/e143a1ce93de</guid>
            <category><![CDATA[adobe-experience-platform]]></category>
            <category><![CDATA[lookalike-audiences]]></category>
            <category><![CDATA[adobe]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Charles Menguy]]></dc:creator>
            <pubDate>Mon, 02 Oct 2023 09:34:39 GMT</pubDate>
            <atom:updated>2023-10-02T09:36:28.995Z</atom:updated>
            <content:encoded><![CDATA[<h4>Breaking down an architecture that helps customers find “look-alike” audiences and improve their campaigns</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BaTXY7KJ6mHVKkzZpXJYKA.png" /><figcaption>Illustrated Concept behind Look-Alike Audiences</figcaption></figure><p><strong>Authors: </strong><a href="https://medium.com/u/13004ed1beac"><strong>Charles Menguy</strong></a><strong>, </strong><a href="https://medium.com/u/c8986301e59a"><strong>Vijeth Lomada</strong></a><strong>, </strong><a href="https://medium.com/u/4de25c9b035d"><strong>Harleen Sahni</strong></a></p><p><a href="https://experienceleague.adobe.com/docs/experience-platform/segmentation/ui/lookalike-audiences.html">Look-Alike Audiences</a> - available in the <a href="https://business.adobe.com/products/real-time-customer-data-platform/rtcdp.html">Real-Time Customer Data Platform</a> (RTCDP) - enables marketers to make data-driven decisions that will help them maximize the potential value of their marketing campaigns.</p><p>This can be achieved with a simple &amp; short workflow to build a look-alike audience using AI/ML, without the need for any technical expertise in data science.</p><p>The stated goal is to help customers find potential users that “look like” a selected audience, expand the pool of their target audience, and ultimately improve the outcome of their marketing campaigns — such as increased conversion rates, more purchases, or better cost-per-acquisition per user.</p><p>In this post we will go over the architecture of the system that makes this a reality, the challenges unique to this kind of modeling, and where the team is heading next.</p><h3>Look-Alike Audiences Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Y7OZlkZeBkXLfXL1lCvJg.png" /><figcaption>High-Level Architecture for Look-Alike Audiences</figcaption></figure><p>Creating look-alike audiences on top of the <a href="https://experienceleague.adobe.com/docs/experience-platform.html">Adobe Experience Platform</a> is a complex process that contains multiple steps described further below.</p><p>But at the very root, this service leverages the Adobe Experience Platform foundational services, such as the <a href="https://experienceleague.adobe.com/docs/experience-platform/identity/home.html">Identity Service</a>, the <a href="https://business.adobe.com/products/experience-platform/real-time-customer-profile.html">Real-Time Customer Profile</a>, all the <a href="https://experienceleague.adobe.com/docs/experience-platform/data-governance/home.html">Data Governance</a> and <a href="https://experienceleague.adobe.com/docs/experience-platform/privacy/home.html">Privacy-related services</a>, and much more.</p><p>The entire system is built with an open-source approach in mind. From leveraging large-scale distributed systems like <a href="https://spark.apache.org/">Spark</a> for feature engineering, to our orchestration layer using <a href="https://airflow.apache.org/">Airflow</a>, and our Machine Learning stack on top of <a href="https://www.databricks.com/">Databricks</a>, the Look-Alike Audiences pipeline is using some battle-tested frameworks to ensure high quality and resiliency.</p><h3>User Experience</h3><p>From the end-user point of view, there are two principles that guide the entire User Experience (UX):</p><ul><li><strong>Insights should be obtained in real-time</strong> as much as possible with no need for user input. This means being able to understand for any existing audience who their look-alikes are and how they are distributed from the get-go.</li><li>Concrete actions from the end-user such as creating a look-alike audience should be <strong>easy to do</strong> in a few clicks, and outcomes of these actions should be visible in a short amount of time.</li></ul><p>To illustrate this, here is a diagram showing the entire user flow for the Look-Alike Audiences product:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wzr6lKW2MNf-MSIdY7eqKQ.png" /><figcaption>User Experience for Look-Alike Audiences</figcaption></figure><p>There are a few steps involved when a customer interacts with the Look-Alike Audiences UI:</p><ul><li><strong>Steps 1 and 2</strong> happen automatically without any customer input. The Look-Alike Audiences system simply looks for any audience with some activity in the past 30 days and will train a look-alike model for it and produce some artifacts (influential factors, as well as similarity/reach graph which will be described below in the section about training)</li><li>In <strong>step 3</strong> the customer finds an audience that they are interested in that might be particularly valuable to expand — for example, buyers of first-class airfare tickets.</li><li>Once they are on the page for that segment, the customer can in <strong>step 4</strong> look at the artifacts generated earlier in step 2 to understand what XDM fields are of particular importance for this audience, and how many other people they could hope to reach depending on how similar they would be to the base audience.</li><li>After the customer has identified a similarity threshold that gives them an appropriate audience size, they can in <strong>step 5</strong> create a look-alike audience out of that base audience which will accurately capture the desired similarity.</li><li>Because the scoring process may take up to 24 hours to run, the customer can then come back in the UI in <strong>step 6</strong> and see that the newly created look-alike audience now has the desired population, and they can now be <a href="https://experienceleague.adobe.com/docs/experience-platform/destinations/home.html?lang=en">activated to destinations</a> if appropriate.</li></ul><p>In addition to this flow, customers can choose to exclude certain fields from modeling which will be respected by the Look-Alike Audiences system through the related <a href="https://experienceleague.adobe.com/docs/experience-platform/data-governance/labels/overview.html?lang=en">Data Governance</a> functionality available in the Real-Time CDP:</p><ul><li>Either by excluding a set of fields globally for any kind of data science purposes — including Look-Alike Audiences.</li><li>Or by excluding a set of fields at the audience level.</li><li>Or by labelling audiences themselves as ineligible to data science purposes, which will be filtered out in the Look-Alike Audiences system.</li></ul><h3>Data Inputs</h3><p>Uncovering look-alikes is a data-hungry process. The more data we have at our disposal, the more accurately we can understand behavior and find interesting insights. Thanks to the <a href="https://business.adobe.com/products/experience-platform/real-time-customer-profile.html">Real-Time Customer Profile</a> we can easily access a unified view of the customers, with the different data components:</p><ul><li><strong>Profile-level data</strong>: Any data that has been ingested and tied directly to a user profile. This can be anything, ranging from standard <a href="https://business.adobe.com/products/experience-platform/experience-data-model.html">Experience Data Model</a> (XDM) fields to completely custom customer-specified schemas.</li><li><strong>Event-level data</strong>: This is essentially time-series data. Anything that is associated to a time horizon is captured there, and a given profile can have many events captured. For example, this can be financial transactions, online interactions over time, etc.</li><li><strong>Segmentation data</strong>: Any segments already defined in the <a href="https://experienceleague.adobe.com/docs/experience-platform/segmentation/home.html">Segmentation service</a> are also important signals directly correlated to what is valuable to a customer, and thus are important to be captured as part of the model.</li></ul><p>We have found the event data to be the richest, by far. Therefore to get quality Look-Alike Audiences it is of utmost importance to have customer events ingested into the Real-Time Customer Profile so it can be leveraged for modeling. That being said, the system will work even with only profile data, but the usefulness of the results will just be reduced.</p><p>All this data will be merged using a stitched view of the profile and used as the main features for finding look-alikes.</p><h3>Feature Engineering</h3><p>Before we can feed any data to a model, we need to massage it into a representation that is easily digestible by the algorithm we choose to use. In our case, this means taking all this profile, event and segmentation data, and automatically transforming it into features.</p><p>A feature represents a characteristic that an audience may or may not have. Because here we are building a general applicable to any customer and data, we are not manually curating features but instead extracting all the key/value pairs from the <a href="https://business.adobe.com/products/experience-platform/experience-data-model.html">Experience Data Model</a> (XDM) and retaining the ones that look the most promising.</p><p>There is some additional complexity when dealing with numerical attributes (like for example income). Those can yield many features, as there can be a large number of unique values which are not necessarily useful. To deal with those data points, we handle different cases:</p><ul><li>If the cardinality for this numerical attribute is small enough, we still treat it as a categorical attribute. For example, if there is a profile attribute in the XDM representing the number of cars someone owns, it is likely the cardinality will be small and consequently every unique value will be its own feature.</li><li>If the cardinality for this numerical attribute is large, we will split the interval between the minimum and maximum value into a maximum of 10 buckets. These buckets are computed automatically by <a href="https://spark.apache.org/docs/3.2.1/api/scala/org/apache/spark/ml/feature/QuantileDiscretizer.html">looking at quantiles</a> and are cached internally so they only need to be computed once every few days. Any profile with this numerical attribute then gets mapped to the right bucket using <a href="https://en.wikipedia.org/wiki/Binary_search_algorithm">binary search</a>. Customers can optionally specify their own buckets that they may be using internally so these intervals show up as features.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P30GE4X_jcamKTHlf3Q-Yw.png" /><figcaption>Feature Engineering Process in Look-Alike Audiences</figcaption></figure><p>At the end of this process, we consider a feature as a structured entity with the following characteristics:</p><ul><li>A unique <strong>feature ID</strong> to refer to this feature across the entire system.</li><li>The <strong>feature type</strong>, representing whether this feature comes from profile attributes, event data, or segmentation data.</li><li>The <strong>key</strong> or <strong>source</strong> of this feature. This can be the XDM column name, or the segment namespace.</li><li>The <strong>value</strong> or <strong>instance</strong> of this feature. This can be the value of that XDM column for a given profile, or the segment/audience ID.</li><li>The <strong>bucket information</strong> in case the source is from a numeric attribute. This contains metadata like the upper/lower bounds of the bucket</li></ul><p>This runs as a <a href="https://spark.apache.org/">Spark</a> job on top of <a href="https://www.databricks.com/">Databricks</a> leveraging our internal Compute APIs and is integrated with internal telemetry and monitoring systems to provide resiliency.</p><h3>Training Pipeline</h3><p>We treat the Look-Alike Audiences modeling problem as a similarity problem, with the following formulation: can we identify look-alike profiles based on their <strong>distance </strong>from the seed audience? If such a distance can be computed for every profile, we can normalize this distance to get a similarity, which can then be used by the customer to expand to the users who did not qualify for the seed audience but may have very similar latent characteristics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zzte685-0DGF0RONtsdoQQ.png" /><figcaption>Training Pipeline for Look-Alike Audiences</figcaption></figure><p>To compute the distance, we first need to create a feature vector for each profile using the following method:</p><ul><li>If we take a step back and think about our data where each profile is composed of multiple features, we can make an analogy to the <a href="https://en.wikipedia.org/wiki/Information_retrieval">information retrieval</a> world where we look to find words in a corpus of documents. In this context, a profile becomes a document, and a feature becomes a word.</li><li>To determine our vocabulary, we need to make some simplifications because there can be a huge number of features as key/value pairs (in the order of hundreds of millions or even trillions for a typical customer). If we keep only the features that have a document frequency above a certain percentage (meaning only the features which appear in at least a percentage of all profiles are kept), this drastically reduces the number of features, removes a lot of noise and leaves us with mostly useful features.</li><li>For each profile, we compute a score using <a href="https://en.wikipedia.org/wiki/Tf%E2%80%93idf">TF-IDF</a> for each of the features in the vocabulary and embed that into a vector. TF-IDF helps ensure that features which are present in all/most profiles would get penalized.</li></ul><p>Once we have the profile feature vectors, we can then compute the audience feature vectors as the mean vector from all the profiles in the audience and normalize it using the <a href="https://en.wikipedia.org/wiki/Norm_(mathematics)#Euclidean_norm">Euclidian norm</a>. These audience vectors are our trained look-alike models.</p><p>There are a few reasons why the problem was modeled this way:</p><ul><li>Using a similarity approach based on TF-IDF is significantly less expensive computationally than treating this as a classification problem or a full-blown clustering problem.</li><li>In terms of accuracy the results are comparable to what we get using classification or clustering techniques.</li><li>The outcome of the model is easy to explain which is important for customers in highly regulated industries.</li><li>Because features are independent with this approach, this is more resistant to noise and inter-day data fluctuations.</li></ul><p>In terms of scalability this process needs to be repeated for every single audience for each customer, so we settled on using <a href="https://spark.apache.org/">Spark</a> on <a href="https://www.databricks.com/">Databricks</a> to provide a highly efficient distributed implementation.</p><p>With this approach, we can compute everything without the need for any sampling, so the results will always be 100% accurate for the entire customer data.</p><h3>Model Interpretation</h3><p>Now that we have a trained model for a given audience, we need to extract information from it to show the results to our customers. The trained model itself from which these insights are derived will be stored into our global model hub so experiments can be tracked more easily.</p><h4>Influential Factors</h4><p>One key insight from the model is the list of influential factors. In other words, we are interested in finding the features which have contributed the most to this model. Because each look-alike model is essentially a vector of scored features, we can easily filter that vector to find the features with the largest scores which form our influential factors.</p><p>Once we have this list of influential factors and the model weights associated with them, we need to refine them to determine what is most relevant to our customers.</p><p>Using some simple heuristics, we can split the interval between the minimum feature score and maximum feature score into 3 buckets, with the bucket containing the highest score being associated to the label “high”, the bucket with lowest scores associated to “low”, and everything in between the label of “medium”. This helps give a clear understanding of which attributes contributed the most in an easily explainable way.</p><p>It is important to note that we only expose the <strong>top 100</strong> influential factors in terms of magnitude to customers as a kind of approximate view of what really influences the model. But this is not a 100% accurate view because the features with smaller weight and influence do not surface back to the user as there would be too many of them (the total number of features can be in the tens of thousands or even hundreds of thousands).</p><h4>Similarity/Reach Graph</h4><p>A second important derived insight for our customers is the ability to understand the trade-off between how similar they want the look-alike audience to be versus how many users they want to reach. Intuitively, a very similar audience will reach fewer users while a less similar audience will reach more users.</p><p>To provide that level of flexibility, we use the trained model to compute a graph showing the estimated reach in function of the similarity to the base audience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xuAlMiyvNMmRw6r2CigOUw.png" /><figcaption>Structure of a Look-Alike Audiences Similarity/Reach Graph</figcaption></figure><p>This graph is generated for a given audience using the following process:</p><ul><li>Take all the profiles which do <strong>not</strong> belong to the base audience. Because this can be a huge set of profiles for small audiences, we use some random sampling to get a representative set of profiles that will be accurate with &lt;2% error.</li><li>For each of these profiles, compute the score between that profile vector and the trained look-alike model vector. For details about the scoring logic please refer to the section about scoring below.</li><li>We create a histogram with 100 buckets of all these scores across all the profiles outside the base audience. The left-most bucket will be the number of profiles with a distance between 0 and 0.01, while the right-most bucket will be the number of profiles with a distance between 0.99 and 1. Note that it is not guaranteed that buckets with very high similarity will have any users because the graph is not normalized to ensure stability over time, so it is possible a given look-alike model may only contain users which are at most 60% similar.</li><li>But this histogram is not yet sufficient because the end-goal is not to target profiles that have a specific similarity, but to target the profiles which have a similarity above a certain threshold. To do that we compute the cumulative sum from the right-most bucket to the left-most bucket. Any point in that new cumulative histogram with a similarity X and reach Y represents the number of profiles with a similarity above or equal to X. Because this is cumulative the left-most bucket reach will be the total number of profiles in the data minus the base audience population as we will capture everyone at 0% similarity. For example, if you select 80% similarity, you will target all the users who have a similarity between 80% and 100%.</li></ul><p>Using this graph, customers can dynamically choose the similarity threshold that makes sense to them. This is what will be used during the scoring step to determine who qualifies for that look-alike audience.</p><h3>Scoring Pipeline</h3><p>Before we can score audiences towards a look-alike model, there are a few pre-requisites:</p><ul><li>We have a <strong>trained look-alike model </strong>with an associated vector.</li><li>We know the <strong>similarity threshold</strong> selected by the customer in the similarity/reach graph.</li></ul><p>Now that we are ready to score, there are a few steps:</p><ol><li>We look at all the user profiles in a certain time window.</li><li>For every user profile, we determine how similar it is to each look-alike audience by computing the <a href="https://en.wikipedia.org/wiki/Cosine_similarity">cosine distance</a> between a profile vector and a seed audience model vector. The normalized distance measure is a number between 0 and 1, with a score of 0 meaning the user is extremely dissimilar to this look-alike audience, while a score of 1 means the user is extremely similar.</li><li>We compare that score with the similarity threshold provided by the customer. If the score is higher than the threshold and that user was not in the base audience, then this user qualifies for the look-alike audience.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vDEZ3xkF-scpkdbJiorMLw.png" /><figcaption>Scoring Pipeline for Look-Alike Audiences</figcaption></figure><p>Before we write back the resulting look-alike audience qualifications to the <a href="https://business.adobe.com/products/experience-platform/real-time-customer-profile.html">Real-Time Customer Profile</a>, we need to figure out what this means in terms of updating the data. For example:</p><ul><li>If a given user had qualified for the look-alike audience last time, but no longer qualifies in the latest run, we still need to send an update saying that this user has exited the look-alike audience.</li><li>If a given user did not qualify for the look-alike audience last time, but now qualifies in the latest run, we send an update saying that this user has entered the look-alike audience.</li><li>If a given user had qualified for the look-alike audience last time, and still qualifies in the latest run, we do need to update the qualification since it already exists.</li></ul><h3>Evaluation Framework</h3><p>An important aspect of this system is ensuring that it meets business objectives and provides high quality artifacts. To ensure that level of quality we devised our evaluation framework focusing on a few areas:</p><h4>Theoretical Evaluation</h4><p>We have done a mathematical analysis for this approach to ensure that everything checks out at the theoretical level. Because the features are independent here, we can show that the artifacts produced with this approach will be more resistant to noise compared to other approaches, like for example classification or clustering.</p><h4>Empirical Evaluation</h4><p>The health and performance of the system can be tracked with different metrics:</p><ul><li><strong>Accuracy</strong>: Although this is not a classical classification algorithm, it is still possible to compare predicted and actual values to compute metrics like True-Positives, True-Negatives, False-Positives, False-Negatives, Accuracy, Precision, Recall, F1 &amp; AUC. We do an 80/20 train-holdout split. So, we have a 20% holdout set that comprises both in-segment and out-of-segment users. We take the cosine similarity of each user in the hold-out set and compare the resulting value with the label (1 if the user is part of the segment. 0 if not part of the segment) to calculate the metrics mentioned above. We found that the majority of audiences have an AUC above 90%, although this depends a lot on the similarity-reach threshold selected by the user. If a user chooses a threshold of 99%, a lot of actual in-audience users in the holdout set might be classified as non-look-alikes leading to high false negatives (low Recall). If the user chooses a threshold of 10%, most of the holdout set users might be classified as look-alike users because we are casting a wide net by choosing a 10% threshold. This leads to high false positives (low precision).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oiJfZDVlVw2IdmY-mYmm8Q.png" /><figcaption>Performance Measurements for Look-Alike Audiences</figcaption></figure><ul><li><strong>Stability of influential factors</strong>: because we retrain look-alike models on a schedule, we want to make sure end-users have a sense of continuity so for consecutive days there should be no drastic change in the set of influential factors if the data changes only marginally. To track that we consider the influential factors as a set and compute the <a href="https://en.wikipedia.org/wiki/Jaccard_index">Jaccard similarity</a> between the influential factors at day N and day N+1 for a given audience. A score of 1 will mean a perfect overlap, while a score of 0 will mean there is no overlap at all. We found that over 99% of audiences have a stability over 80% day-to-day.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yn3Aos20qxAxNMqZXR2kFg.png" /><figcaption>Stability for Influential Factors</figcaption></figure><ul><li><strong>Stability of similarity/reach graphs</strong>: for the same reasons we want to have a sense of continuity for the similarity/reach graphs. The graphs themselves are histograms with reach on the y-axis, so we start by normalizing them on the y-axis so that the y-axis is a value between 0 and 1. Then we can compute the AUC of that normalized histogram, which will yield a number between 0 and 100. A score of 0 would be a L-shaped graph, while a score of 100 would be the reverse. If we compare this score for a given audience on consecutive days, the difference should remain small if there is not much variation in the profile data.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u3TQ9QHbfCmnWH1gtCdghA.png" /><figcaption>Stability for Similarity/Reach Graphs</figcaption></figure><h4>Real-World Tests</h4><p>We are working closely with customers to evaluate the performance of activated look-alike audiences on 3rd party ad platforms (like Facebook, Twitter, etc). The team is also in the process of creating a unified experimentation platform to be able to perform this kind of real-world performance tests in a seamless manner, including but not limited to Look-Alike Audiences.</p><h3>Challenges and Next Steps for Look-Alike Audiences</h3><p>Developing a system that enables the use of Look-Alike Audiences at scale on a wide range of segments on very varied data sources presents some unique challenges:</p><ul><li><strong>Scalability</strong>: We are training thousands of models daily for all customers. This means that the infrastructure must scale out to enable horizontally distributed training and make smart decisions about how data is fed to our models to achieve accurate precisions while remaining cost-effective. The team is investing significantly in optimizations to make the pipelines more efficient, be it at the infrastructure level, the data layer, or the logical layer.</li><li><strong>Latency constraints</strong>: The User Experience (UX) for our customers needs to be snappy, so being able to see these similarity/reach graphs and influential factors must come back within milliseconds. Achieving that requires a careful architecting of our service layer, with a database layer that supports high availability and a regionalized architecture to reduce the round-trip time of data as well as data transfer costs.</li><li><strong>Accurate predictions</strong>: As the typical saying that “<a href="https://en.wikipedia.org/wiki/All_models_are_wrong">all models are wrong, but some are useful</a>” we want to make sure our models fall into the “useful” category. Getting there requires careful tuning for feature selection, hyper-parameter tuning, choice of algorithm, and is an ongoing focus for the team. We have great partnerships with <a href="https://research.adobe.com/">Adobe Research</a> to always investigate novel approaches so we can get the best to delight our customers.</li><li><strong>Empowering our customers</strong>: The dilemma is that we are building a general model applicable to any customer with any kinds of data patterns, but we also want the model to closely fit each customer’s use case. To do so we are looking to add more flexibility into the system, where customers can filter directly in the UI filter out some fields, specify goals, input some parameters, and more. The goal being to add even more transparency and explainability to what customers can see.</li><li><strong>Online experiments</strong>: To measure the effectiveness of a look-alike audience, currently a customer has to activate it to a destination and measure performance offline. The team is looking to eventually have an integrated online experiment system inside the RTCDP product that will allow to more easily measure online performance of look-alike audiences.</li></ul><p>These challenges have been kept top of mind while designing and releasing the Look-Alike Audiences system as it matured. The team is committed to ensuring a smooth experience for our customers and is already working on future improvements that will make the experience even better based on ongoing customer feedback.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e143a1ce93de" width="1" height="1" alt=""><hr><p><a href="https://medium.com/adobetech/look-alike-audiences-ai-enabled-audience-expansion-in-real-time-cdp-e143a1ce93de">Look-Alike Audiences: AI-enabled Audience Expansion in Real-Time CDP</a> was originally published in <a href="https://medium.com/adobetech">Adobe Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>