Skip to content

fix(llm): keep an Instructions kwarg's common text in resolve_template - #8780

Open
1AbdullahButt wants to merge 1 commit into
livekit:mainfrom
1AbdullahButt:fix/resolve-template-keeps-common
Open

1AbdullahButt wants to merge 1 commit into
livekit:mainfrom
1AbdullahButt:fix/resolve-template-keeps-common

Conversation

@1AbdullahButt

Copy link
Copy Markdown

Instructions treats audio= and text= as additions to common: render(modality="audio") returns common plus audio. Instructions.resolve_template() handles an Instructions kwarg differently. It fills that kwarg's placeholder with v.audio (or v.text) on its own, so the kwarg's common text is dropped from that modality's variant.

Users hit this through beta.workflows.WorkflowInstructions(persona=...), which calls resolve_template:

from livekit.agents.llm.chat_context import Instructions

persona = Instructions("You are Sam, the Acme Bank assistant.", audio="Speak warmly and slowly.")
instr = Instructions.resolve_template("{persona}\n\nCollect the caller's address.", persona=persona)
instr.render(modality="audio")
# main:  "Speak warmly and slowly.\n\nCollect the caller's address."    <- persona text lost
# here:  "You are Sam, the Acme Bank assistant.\n\nSpeak warmly and slowly.\n\nCollect the caller's address."
instr.render(modality="text")
# both:  "You are Sam, the Acme Bank assistant.\n\nCollect the caller's address."

The kwarg handling seems to date from #6116, when Instructions changed from holding full alternative variants to the common-plus-additions model. #6414 fixed the output side (#6407) but not this input side. The fix fills each placeholder with v.render_static(modality=...), which is what the kwarg renders to for that modality.

One behaviour change to flag: a kwarg with non-empty common and an explicit empty addition, such as Instructions("C", audio=""), now fills its placeholder with "C" instead of "". This matches render(modality="audio"). The comment I removed said an explicit "" removes the section, so tell me if that case was intended. In-tree workflow kwargs all have empty common, so their output doesn't change.

Tests: I added test_resolve_template_keeps_common_of_instructions_kwarg. tests/test_instructions.py gives 1 failed / 50 passed on main and 51 passed with the fix. tests/test_chat_ctx.py, tests/test_workflows.py and tests/test_workflow_readback.py give the same result before and after: 104 passed and 4 failed. The 4 failures are DTMF tests that need LIVEKIT_API_KEY.

I made this change with help from Claude Code, and I reviewed the diff and the test results myself.

🤖 Generated with Claude Code

An Instructions kwarg's audio/text are additions to its common text,
but resolve_template filled each placeholder with the addition alone,
so the common text was lost from that modality's variant.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@1AbdullahButt
1AbdullahButt requested a review from a team as a code owner November 25, 2026 08:11

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Devin Review: No Issues Found

Devin Review analyzed this PR and found no bugs or issues to report.

Devin Review

@ayushmnnit ayushmnnit left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked out 71f44c1. test_instructions.py, test_chat_ctx.py, test_workflows.py and test_workflow_readback.py give 155 passed and 4 failed. The 4 failures are the api_key ones you listed.

I compared main with this PR on a few kwarg shapes (first script):

  • persona=Instructions("P", audio="A"): main renders audio as "A\n\nCollect...", and this PR gives "P\n\nA\n\nCollect...". That's the fix.
  • A nested kwarg, where the value passed in is itself the result of resolve_template with differing audio/text: main renders "A\n\n..." and "X\n\n..." and loses P in both modalities. With this PR both keep P. That's the same bug through a second route, and it's what happens when one workflow template feeds another, so it may be worth a parametrized case next to the new test.
  • Instructions("P", audio="") now keeps P, as your description says.

For the in-tree tasks, GetAddressTask and GetEmailTask with require_confirmation set to None, True and False render the same audio and text instructions on main and with this PR (second script), so your "no in-tree change" claim holds for those two.

One thing on the same WorkflowInstructions path that this PR doesn't touch. WorkflowInstructions still takes audio and text, but resolve() (beta/workflows/utils.py:79) passes only persona, extra and the task kwargs to resolve_template. Its own audio/text never reach the task. GetAddressTask(instructions=WorkflowInstructions(audio="Speak slowly.", text="Use bullets.")) renders neither string, on main or here. The first positional parameter is also audio, while Instructions uses common, so WorkflowInstructions("You are Sam.") puts the text in audio and then drops it. Both look like leftovers from #6116, when Instructions(audio, text=...) held full variants. A follow-up could either feed them into the template or drop them from the constructor. Mentioning it here because it's the same migration gap. It doesn't need to block this PR.

script
from livekit.agents.beta.workflows.utils import WorkflowInstructions
from livekit.agents.llm.chat_context import Instructions

T = "{persona}\n\nCollect the address.{extra}"
R = Instructions.resolve_template

cases = {
    "persona common+audio": dict(persona=Instructions("P", audio="A"), extra=""),
    "persona common, audio=''": dict(persona=Instructions("P", audio=""), extra=""),
    "persona with dynamic": dict(persona=Instructions("P", dynamic="Now: 9am"), extra=""),
    "nested resolved kwarg": dict(
        persona=R("{a}", a=Instructions("P", audio="A", text="X")), extra=""
    ),
    "extra common+text": dict(persona="P", extra=Instructions("\n\nE", text=" (typed)")),
}
for name, kw in cases.items():
    out = R(T, **kw)
    print(f"{name:26} audio={out.render(modality='audio')!r}")
    print(f"{'':26} text ={out.render(modality='text')!r}")

# WorkflowInstructions' own audio/text never reach resolve()
wi = WorkflowInstructions(audio="Speak slowly.", text="Use bullets.", persona="P")
out = wi.resolve(template=T, default_persona="D")
print("WorkflowInstructions(audio=..., text=...) ->", repr(out.render(modality="audio")), "|", repr(out.render(modality="text")))
# Built-in workflow tasks: does the PR change their rendered instructions, and
# do WorkflowInstructions' own audio/text reach the task?
from livekit.agents.beta.workflows import GetAddressTask, GetEmailTask
from livekit.agents.beta.workflows.utils import WorkflowInstructions

for cls in (GetAddressTask, GetEmailTask):
    for rc in (None, True, False):
        kw = {} if rc is None else {"require_confirmation": rc}
        t = cls(**kw)
        for m in ("audio", "text"):
            print(cls.__name__, rc, m, hash(t.instructions.render(modality=m)))

t = GetAddressTask(instructions=WorkflowInstructions(audio="Speak slowly.", text="Use bullets."))
a, x = t.instructions.render(modality="audio"), t.instructions.render(modality="text")
print("own audio kept:", "Speak slowly." in a, "| own text kept:", "Use bullets." in x)
print("positional arg lands in:", vars(WorkflowInstructions("You are Sam."))  )

k: (v.audio if v.audio is not None else str(v))
if isinstance(v, Instructions)
else v
k: v.render_static(modality="audio") if isinstance(v, Instructions) else v

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

render_static leaves out the kwarg's dynamic, so persona=Instructions("P", dynamic="Caller: +1555...") loses the caller line without any warning (it renders "P\n\nCollect the address." in both modalities). The docstring says the result never carries dynamic, so this may be deliberate, but with this change dynamic is the only part of a kwarg that still gets dropped. Carrying the kwargs' dynamic onto the result (joined), or logging when one is dropped, would close that.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants