<?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 James Zaremba on Medium]]></title>
        <description><![CDATA[Stories by James Zaremba on Medium]]></description>
        <link>https://medium.com/@james.zaremba?source=rss-d67616e0b2e1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*rwN2O8gtwV4l4aOa</url>
            <title>Stories by James Zaremba on Medium</title>
            <link>https://medium.com/@james.zaremba?source=rss-d67616e0b2e1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 16:10:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@james.zaremba/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[Behind the scenes: the prompts that run our AI conversation coach]]></title>
            <link>https://medium.com/preply-engineering/behind-the-scenes-the-prompts-that-run-our-ai-conversation-coach-ce5315291af2?source=rss-d67616e0b2e1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce5315291af2</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[James Zaremba]]></dc:creator>
            <pubDate>Tue, 28 Apr 2026 11:21:41 GMT</pubDate>
            <atom:updated>2026-04-28T15:50:46.381Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wn2Loex9b0r1iYDGYIMtmw.png" /></figure><p>How “speak to an avatar, practice a real scenario” turned out to need a stage actor, a silent stage manager, and a very firm rule about who gets to talk to the learner.</p><p>Learners do not report prompt bugs. They reach for adjectives: the coach felt <em>pushy</em>, or <em>vague</em>, or <em>oddly cheerful about a heavy topic</em> — as though “tone” were something you could assign in Jira. Sometimes the transcript looked fluent while the audio sounded much messier, and downstream logic treated the polished text as ground truth. None of that shows up as a stack trace. The system is still running; it has just stopped being trustworthy for practice.</p><p>This post is about <strong>Scenario Practice</strong>: learners are immersed in real-life situations within the platform — ordering coffee at a café, navigating a job interview, or handling a complaint at a hotel reception. They speak, an avatar responds in character, and the system tracks whether the learner achieves real communicative goals.</p><h3>How this fits the series</h3><p>Oleh Vatria’s earlier <a href="https://medium.com/preply-engineering/designing-a-streaming-ai-scenario-practice-engine-with-webrtc-openai-and-anam-28aa2c24c7c9">article</a> walked through the mobile and WebRTC architecture and explained why the realtime conversational loop and the heavier structured work were pulled apart in the first place — <strong>latency</strong>. This post picks up after that split has hardened into two distinct agents with incompatible jobs, and focuses on what we tell each model and why. The migration story, avatar/TTS (Text-to-Speech) details, and the older client-orchestrated shape live in sibling posts.</p><p><em>One wiring note for readers of Oleh’s </em><a href="https://medium.com/preply-engineering/designing-a-streaming-ai-scenario-practice-engine-with-webrtc-openai-and-anam-28aa2c24c7c9"><em>pseudocode</em></a><em>:</em> today’s LiveKit-backed worker uses OpenAI Realtime in text modality only and sends assistant text to a TTS provider for speech. Same product family, different audio graph.</p><h3>What Scenario Practice is actually trying to do</h3><p>The product goal is deceptively straightforward: <strong>give learners a low-stakes place to practise real conversation between lessons</strong>, with enough structure to make it educationally useful.</p><p>That phrase — <em>enough structure</em> — is where it gets complicated:</p><ul><li>A <strong>purely free-form conversation</strong> is enjoyable but unmeasurable; you cannot tell if the learner got better or just got lucky.</li><li>A <strong>purely task-graded exercise</strong> feels like a worksheet with a face.</li></ul><p>Scenario Practice sits between those failure modes: the conversation has to feel natural enough that a learner stays engaged, and structured enough that the system knows what “success” means.</p><p>This creates the <strong>fundamental tension</strong> that shapes everything below. One side of the system needs to behave like a warm, in-character interlocutor who happens to be a barista named Sophie. The other side needs to run structured reasoning about whether task 2 is complete, whether the learner seems confused, and when the session has reached a natural end. Asking one model to do both is like asking a stage actor to simultaneously perform and update the stage manager’s checklist between every line. <em>Something suffers.</em></p><h3>Two agents, not one</h3><p><strong>Two agents run in parallel during every session, and the learner only ever talks to one of them.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LSS4O-Rs9Wc9MPeahaPwMw.png" /></figure><h3>The Conversational Agent</h3><p>This is what the learner interacts with. It:</p><ul><li><strong>Plays the scenario persona</strong> and stays in character from opening line to goodbye</li><li>Does <strong>not</strong> know which tasks the learner has completed</li><li>Does <strong>not</strong> decide when the session ends</li><li>Is <strong>not</strong> responsible for hints</li></ul><p>It runs on a realtime model in text modality, with separate STT (Speech-to-Text) and TTS (Text-to-Speech) services on either side, all coordinated over LiveKit.</p><h3>The Supervisor Agent</h3><p>The supervisor <strong>never speaks to the learner</strong> — not once, not even by accident. It:</p><ul><li>Runs on gpt-4.1-mini at <strong>temperature 0.0</strong> (meaning it always produces the same, deterministic output for the same input — no randomness or creative variation)</li><li>Fires <strong>silently</strong> after each assistant turn</li><li>Reads a truncated window of recent conversation plus the current task state</li><li>Produces exactly <strong>one structured tool call</strong> per cycle</li></ul><p>That tool call always carries the full task state and a short planning text, plus four optional fields:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JmFDkfjK-Gajs7CujqePDA.png" /></figure><p><strong>Separating the two agents is what makes each independently optimisable.</strong> If task detection needs sharpening, you change the supervisor prompt. If the persona needs to feel warmer, you change the persona prompt. Neither touches the other.</p><h3>Prompt-level contract vs runtime-enforced guarantee</h3><p>This distinction is worth being precise about, because the two are often conflated in prompt-stack write-ups.</p><p><strong>Runtime-enforced</strong> — the worker grants the supervisor a budget of exactly one tool call per planning cycle. Any further tool call is silently dropped. This is a hard guard against the model spinning in a loop:</p><pre>async def _plan_once() -&gt; None:<br>    async with self._plan_lock:<br>        if normalized_text and normalized_text == self._last_processed_assistant_text:<br>            logger.debug(&quot;[supervisor] Duplicate planning prevented by lock check&quot;)<br>            return<br>        self._last_processed_assistant_text = normalized_text<br>        self._tool_budget_left = 1</pre><p><strong>Prompt-level</strong> — the “at most one optional field per turn” rule. Inside the single allowed tool call, the handler checks each optional field independently. The strict “never combine end, tips, and safety in one turn” contract lives in the supervisor instructions, not in code.</p><p>So the hard guarantee is <em>one tool call per plan</em>; the stricter <em>one optional UI action per turn</em> is a prompt behaviour we treat as an evaluator requirement rather than a runtime invariant. If the model ever violated it, the runtime would not automatically collapse the output — we would see it first in evaluators or production traces.</p><h3>Tap-to-speak, not automatic VAD</h3><p><strong>Turn-taking is manual by default</strong>: the learner taps to speak and taps again to end their turn.</p><p>VAD (Voice Activity Detection) — where the system automatically detects when you’ve stopped speaking — is available but kept off by default. A false trigger in a language-learning product, where the system decides you finished speaking when you didn’t, is more disruptive than a button.</p><h3>How supervisor output becomes UI</h3><p>The supervisor does not render UI directly. It <strong>emits typed events over LiveKit</strong> which the mobile client routes to the right surface:</p><ul><li>Task list updates</li><li>End-of-session signals</li><li>Two tip overlays (next-task and phrase)</li><li>Safety banner</li></ul><p>When a tip fires, the app shows a short, dismissible overlay. None of that is the persona “deciding” to be helpful out loud — it is structured output becoming product chrome.</p><p><strong>Why two tips plus a safety banner?</strong> Because pedagogy lives in the task list, but learners still get stuck or drift into territory where in-character answers could be mistaken for professional advice:</p><ul><li>The <strong>next-task tip</strong> acknowledges progress without breaking character</li><li>The <strong>phrase tip</strong> offers a concrete thing to try after a couple of rough turns</li><li>The <strong>safety reminder</strong> exists for scenarios that touch medical, legal, financial, or psychological domains — where the learner might treat the avatar’s answers as real guidance</li></ul><h3>The prompt layers</h3><h3>1. The persona instructions prompt</h3><p>This is the system prompt for the conversational agent, assembled server-side before it reaches the LiveKit worker. The template is formatted with a rich payload:</p><pre>payload = {<br>    &quot;language&quot;: language, # e.g. &quot;English&quot;<br>    &quot;avatar_role&quot;: avatar_role, # &quot;You are Sophie. You are a friendly barista at a Paris café.&quot;<br>    &quot;scenario_instructions&quot;: …, # scene-specific instructions from the Scenario DB object<br>    &quot;ambient_context&quot;: …, # physical setting, mood, situational context<br>    &quot;learner_goal&quot;: …, # the overarching communicative objective<br>    &quot;learner_tasks&quot;: …, # XML-tagged task list with IDs<br>    &quot;topic_text&quot;: …, # topic keywords for the session<br>    &quot;level&quot;: level_definition, # CEFR level description<br>    &quot;can_do_statements&quot;: …, # what a learner at this level can and cannot do<br>    &quot;complexity&quot;: …, # grammatical complexity expectations<br>    &quot;conversational_section&quot;: …, # how to pitch the conversation register<br>}</pre><p>Two fields pull disproportionate weight:</p><p><strong>CEFR level is a calibration instrument, not a label.</strong> A B1 barista and an A2 barista are having genuinely different conversations with the same learner: different vocabulary assumptions, different sentence complexity, different patience when the learner is reaching for words. The prompt creates that distinction not by hardcoding “speak simply” but by supplying structured can-do statements and complexity guidelines the model interprets in context.</p><p><strong>Ambient context has more leverage than we expected.</strong> Sessions with a rich ambient_context feel grounded within a few turns. Sessions with a sparse one feel like the avatar is floating in a white void, technically answering questions about coffee. The model does not need to be told &quot;sound natural&quot; — it needs enough situational detail to <em>actually be</em> natural.</p><h3>2. The supervisor prompt</h3><p>The supervisor’s prompt is <strong>structurally coupled to its tool schema</strong>: it references the exact optional fields (end, next-task tip, phrase tip, safety reminder) that map one-to-one to code paths downstream. Moving one without the other produces silent failures, so the prompt and the schema must change together and be reviewed together.</p><pre>def get_supervisor_instructions() -&gt; str:<br>    instructions = &quot;&quot;&quot;<br>You are the backend/UI-state manager for a conversational language-learning exercise.<br>A separate &quot;role-play&quot; assistant drives the dialogue with the learner;<br>you never send plain text to the user — only invoke tools.<br>...<br>&quot;&quot;&quot;</pre><p>The prompt also asks the model to <strong>think out loud</strong> about which optional field to use — if any — before committing. Structured reasoning before action, legible in logs, at temperature 0.0.</p><p><strong>Temperature 0.0 is non-negotiable.</strong> Temperature controls how “creative” or random a model’s output is — 0.0 means fully deterministic, the same input always produces the same output. Early experiments at higher temperatures produced supervisors that would occasionally end a session that was clearly going well, or fail to mark a task complete when the learner had obviously achieved it. <strong>A model making binary session-state decisions needs to be deterministic. Creativity is not a virtue in the stage manager.</strong></p><h3>3. The transcription prompt</h3><p>Deepgram handles the raw audio. Around it, we hold a single principle for anything that touches transcription:</p><blockquote>Don’t beautify clear speech. Don’t guess at unclear audio.</blockquote><ul><li><strong>Clear speech</strong> goes in verbatim, exactly as it was said</li><li><strong>Unclear audio</strong> is marked as uncertain — typically with an explicit “inaudible” marker — rather than approximated or silently dropped</li></ul><p><strong>The failure mode this rule exists to prevent is not wrong words; it is polished words.</strong> A transcription path that smooths grammar, infers unclear words, or completes half-finished sentences produces a more readable transcript — and a false record of what the learner actually said. The supervisor then marks a task complete based on fluent fiction. The learner gets positive feedback. Nobody learns anything, and nobody notices.</p><p>Marking unclear audio explicitly matters for the same reason: “heard nothing” and “heard audio but could not confidently parse words” are different situations that need to be different signals downstream. Collapsing them — or worse, converting them into confidently wrong text — is how task completion logic ends up grading something the learner never produced.</p><h3>4. The conclude prompt</h3><p>Small but load-bearing. <strong>Ending cleanly is a multi-step contract, not an instruction buried in the persona prompt.</strong> When the learner completes all talking points, the app calls the conclude_conversation RPC; that flips the scenario agent into closing mode.</p><p>The instruction itself is a handful of sentences:</p><ul><li>Stay in character</li><li>End the conversation now</li><li>Produce a single polite closing line</li><li>Do not ask questions</li><li>Do not continue the dialogue</li></ul><p>It is <strong>deliberately narrow</strong>. Without an explicit conclude path, the model’s default instinct is to keep the conversation going — because that is what it has been trained to do.</p><h3>Safety nets (outside the prompt stack)</h3><p>Two hard limits are enforced in the session lifecycle, not in prompts, because <strong>prompts are not a reliable safety net for time</strong>:</p><ul><li>10-minute hard cap — the session ends regardless of task state.</li><li>3-minute silence limit — if neither party has said anything for three minutes, the session is cleaned up.</li></ul><p>The supervisor’s end_session call is the graceful path. A well-calibrated supervisor ends the session before either limit fires; <strong>when a hard limit fires, something in the prompt stack has failed</strong> to bring the conversation to a natural close. That metric is a useful signal.</p><h3>Observability and iteration</h3><p><strong>Prompts are treated like code</strong> — reviewed, versioned, and tested against datasets before they ship.</p><p>We sample traces in production, tagged by prompt name, model, and environment, so “what happened in prod last week for this prompt?” becomes a filter rather than a log-archaeology expedition. Rendered prompts, parameters, latency, token usage, tool calls, and errors land in one place.</p><p>Evaluation splits cleanly along the same lines as the agents:</p><ul><li><strong>Persona prompt</strong> — judged like a dialogue system: naturalness, constraint adherence, scenario fidelity, level fit. LLM-as-judge with graded rubrics.</li><li><strong>Supervisor prompt</strong> — judged like a state machine: did it mark the right tasks complete, did it emit at most one optional field, is the tool output valid. Binary checks.</li></ul><p><strong>Promoting a new prompt version to production</strong> compares three dimensions:</p><ol><li><strong>Quality</strong> — evaluator scores</li><li><strong>Operations</strong> — latency, tokens, cost</li><li><strong>Stability</strong> — variance on edge cases</li></ol><p>An experiment that improves aggregate scores but introduces a new failure pattern on edge cases does not promote. The bar differs per path: for the supervisor, there is no “almost right” for a wrong session end; for the persona, a little more stiffness is acceptable if safety and task flow measurably improve.</p><p>Planning latency is timed on every assistant turn — longer supervisor instructions, more planning text, or a wider history window add tokens and milliseconds directly to the user-perceived pause before the next reply.</p><h3>What surprised us</h3><p>Four things stood out that weren’t obvious upfront:</p><ul><li><strong>Ambient context has more leverage than expected.</strong> Rich vs sparse is visible in conversation quality within a few turns — the model doesn’t need to be told to “sound natural,” it needs enough situational detail to actually be natural.</li><li><strong>Temperature 0.0 for the supervisor is non-negotiable.</strong> Determinism on binary state decisions matters more than flexibility. Early experiments with higher temperatures caused the supervisor to make clearly wrong session-end calls.</li><li><strong>The “beautify” problem is real and insidious.</strong> Cleaner transcripts caused task-completion logic to mark things done based on a polished version of speech that didn’t actually happen.</li><li><strong>Small prompts can be load-bearing.</strong> The conclude path is just a few sentences and does exactly one thing. Not every prompt needs to be a document to do real work.</li></ul><h3>Final takeaway</h3><p>Scenario Practice looks like one thing: speak to an avatar, practise a real situation. Under the hood it is <strong>two agents with different models, different temperatures, different prompts, and different responsibilities</strong> — coordinated so that the learner experience feels coherent.</p><p>The simplest honest summary:</p><ul><li>The persona prompt makes the avatar feel real.</li><li>The supervisor prompt keeps task state and session end aligned with what actually happened — and decides when phrase hints, next-task hints, and safety reminders should surface in the UI. The persona never announces those.</li><li>The transcription principle makes the feedback honest.</li><li>The conclude prompt, together with the conclude_conversation RPC path, stops Sophie from offering you more pastries after you have already said goodbye.</li></ul><p>When any one of those is off, the session does not crash. It just <strong>feels slightly wrong in a way the learner cannot quite articulate and will not be able to report in a bug ticket</strong>. That is the hardest failure mode to catch, and the most expensive one to leave unfixed.</p><p>Prompts are not configuration. They are product.</p><p><em>Inspired by our approach at Preply? If you’re driven by going the extra mile to raise the bar, hungry to have a visible impact on the business, and would like to join a fast-paced company where growth and learning go hand in hand, then check out our open positions </em><a href="https://bit.ly/36rmMgB"><em>here</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce5315291af2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/preply-engineering/behind-the-scenes-the-prompts-that-run-our-ai-conversation-coach-ce5315291af2">Behind the scenes: the prompts that run our AI conversation coach</a> was originally published in <a href="https://medium.com/preply-engineering">Preply Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>