Implementing a code switching feature where I want...
# ask-ai
a
Implementing a code switching feature where I want to change the following on runtime
tts
: working using
run_context.session._tts = target_tts
stt
: working using
run_context.session._stt = target_tts
, but for only one turn of speech
instruction
: not working at all limitation: • tool is created dynamically, separately from the agent
t
Thanks for reaching out, kasmare. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're trying to switch TTS, STT, and agent instructions at runtime; TTS and STT changes via direct session attribute assignment are behaving inconsistently (STT only one turn) and instructions don't change. I can help—quick clarifying questions and recommended actions below. 1) Quick clarifying questions • Are you creating the tool/agent and then performing the runtime switch from within the same agent context or from an external controller? • Do you call any handoff or agent-switch APIs when you change STT/TTS, or are you only assigning
run_context.session._tts/_stt
? • Which SDK/language and LiveKit package version are you using? 2) What you can do now (recommended, supported approaches) • Change agent instructions using the agent API: use
await self.update_instructions("New instructions here")
from the agent context to update instructions at runtime. This is the supported method for updating agent behavior. • For STT/TTS, prefer setting `stt`/`tts` on the Agent when creating or handing off to an agent — agent-level overrides take precedence over session defaults. Use agent handoffs or re-create/reconfigure the agent with the desired `stt`/`tts` rather than mutating private session fields (
_tts
,
_stt
), which are not documented and can produce inconsistent behavior. 3) If you must switch mid-session without recreating agents • Use an explicit handoff pattern: create or select an agent configured with the target `stt`/`tts` and perform a handoff so the new agent’s settings apply consistently across turns. • For one-off speech-turn overrides, a temporary agent configured for that turn is reliable; assign instructions via
update_instructions()
on that agent if needed. If you share a short code snippet showing how you currently switch
tts
,
stt
, and instructions (where you call it, and whether you perform handoffs), I’ll point out exact code changes to make it reliable. Would you like that? Sources: Building an Automated IVR Menu Caller | LiveKit docs | Agents and handoffs | LiveKit docs
a
1) Quick clarifying questions • Are you creating the tool/agent and then performing the runtime switch from within the same agent context or from an external controller? ◦ Yes, within the same context via the run context but from outside the agent. • Do you call any handoff or agent-switch APIs when you change STT/TTS, or are you only assigning
run_context.session._tts/_stt
? • Only assigning, I have a lot of configurations when it comes to my agent and passing them in again to recreate the whole agent is not feasible for me. • Which SDK/language and LiveKit package version are you using? ◦ "livekit" = "1.0.19" ◦ livekit-agents = ~=1.2 2) What you can do now (recommended, supported approaches) • Change agent instructions using the agent API: use
await self.update_instructions("New instructions here")
from the agent context to update instructions at runtime. This is the supported method for updating agent behavior. ◦ I can't do this since the tool is running from outside the agent, it only has access to the run_context • For STT/TTS, prefer setting `stt`/`tts` on the Agent when creating or handing off to an agent — agent-level overrides take precedence over session defaults. Use agent handoffs or re-create/reconfigure the agent with the desired `stt`/`tts` rather than mutating private session fields (
_tts
,
_stt
), which are not documented and can produce inconsistent behavior. ◦ the complexity of recreating the whole agent is an issue 3) If you must switch mid-session without recreating agents • Use an explicit handoff pattern: create or select an agent configured with the target `stt`/`tts` and perform a handoff so the new agent’s settings apply consistently across turns. ◦ how so? • For one-off speech-turn overrides, a temporary agent configured for that turn is reliable; assign instructions via
update_instructions()
on that agent if needed. ◦ it's not one off
t
Thanks — this is helpful context. You're switching from outside the agent via
run_context
, can't recreate the agent, and currently only assign
run_context.session._tts/_stt
. I'll be direct: mutating private fields is unsupported and causes the inconsistent behavior you see. Two supported, reliable patterns you can use from outside the agent are below. Pick the one that fits your constraints. 1) Best-fit: session.update_options() (no full agent rebuild) • What it does: safely updates session-level STT/TTS for subsequent turns without recreating the agent. • How to call it from your tool:
Copy code
# inside your tool, with access to run_context
await run_context.session.update_options(stt=new_stt, tts=new_tts)
• Effect: future turns use the new models consistently. Use this if you only need to swap STT/TTS and keep the same Agent instance and tools. 2) When you need instruction changes or agent-scoped overrides: agent handoff (lightweight agent replacement) • What it does: replaces the active agent with a new Agent instance that overrides only the fields you need (instructions, stt, tts) while preserving session/chat state and userdata. • How to perform from a tool:
Copy code
# create a new agent with only the changed pieces
new_agent = MyAgent(instructions="New instructions", stt=new_stt, tts=new_tts)
# perform the handoff from outside by returning/setting the new agent
await run_context.session.update_agent(new_agent)
# or return new_agent from the tool if your tool-return handoff pattern is used
• Effect: full, persistent instruction changes and agent-level overrides. You do not need to re-specify every config — preserve or reuse tools, chat_ctx, and userdata. Extra notes and recommendations • Use
agent.update_instructions()
when inside an agent; from outside, update instructions via a handoff/new-agent or get
run_context.session.active_agent
and call its
update_instructions()
if available. • Encapsulate your common config in factory functions or presets so creating the replacement agent is cheap and deterministic (avoids re-assembling many configs). • Avoid
run_context.session._tts/_stt
— it's unreliable and causes one-turn behavior or no-op instruction changes. If you want, paste a minimal snippet of your current tool code that does the assignment and I’ll show exactly where to call
update_options()
or construct the replacement agent and preserve chat/userdata. Which do you prefer to try first:
update_options()
or a lightweight handoff with a preset factory? Sources: Agents and handoffs | LiveKit docs | Tool definition and use | LiveKit docs | Agents (Python) | livekit/livekit_composite | DeepWiki | Models | LiveKit Docs
a
update options is only providing the following _min_endpointing_delay_: _NotGivenOr_[float] = _NOT_GIVEN_, _max_endpointing_delay_: _NotGivenOr_[float] = _NOT_GIVEN_, _turn_detection_: _NotGivenOr_[TurnDetectionMode | None] = _NOT_GIVEN_
t
Thanks — clear info. You're right:
update_options()
only controls endpointing/turn-detection (min/max endpointing delay, turn detection). It does NOT change TTS, STT, or instructions. Use one of these supported patterns from your tool (outside the agent) instead: 1) session.update_agent() — recommended for instruction + STT/TTS changes • Create a lightweight replacement Agent that overrides only what you need (instructions, stt, tts). • Call from your tool:
Copy code
new_agent = MyAgent(instructions="New instructions", stt=new_stt, tts=new_tts)
await run_context.session.update_agent(new_agent)
• Preserves session/chat history and userdata; you don’t need to re-specify all configs if you reuse factories or copy chat_ctx/userdata. 2) agent.update_instructions() — if you can access the active agent instance • From outside, you can get the active agent and call:
Copy code
await run_context.session.active_agent.update_instructions("New instructions")
• This updates instructions persistently across turns. Notes and tips • Do NOT mutate
run_context.session._tts
/
_stt
— those are private and cause one-turn or inconsistent behavior. • If creating an agent object feels heavy, wrap common config in small factory/preset functions so instantiation is cheap. • If you want to change only STT/TTS and the plugin supports in-place updates, update the plugin instance via its own
update_options()
(plugin-dependent). Otherwise use
update_agent()
. If you paste the minimal tool code where you currently assign
_tts/_stt
, I’ll show the exact, minimal edits to switch to
update_agent()
or call
active_agent.update_instructions()
so it works reliably. Which snippet would you like me to refactor? Sources: Agents and handoffs | LiveKit docs | Tool definition and use | LiveKit docs | Agents (Python) | livekit/livekit_composite | DeepWiki
a
Is there anyway to create an agent handoff using the
current_agent
as the root object
t
You can perform a handoff using the current agent as the base by creating a new Agent instance that reuses the current agent’s state (chat_ctx, userdata, tools, etc.) and overrides only the pieces you need (instructions,
stt
,
tts
). That preserves session history and avoids rebuilding every config field. Two minimal patterns: 1) Lightweight clone + override (recommended)
Copy code
# inside your tool (outside agent), with run_context
current_agent = run_context.session.active_agent
chat_ctx = current_agent.chat_ctx
userdata = run_context.session.userdata
tools = current_agent.tools  # or copy/filter if needed

new_agent = type(current_agent)(
    chat_ctx=chat_ctx,
    instructions="New instructions here",
    tts=new_tts,    # only include if changing
    stt=new_stt,    # only include if changing
    # tools and other config reused from current_agent if constructor supports them
)

# preserve userdata if constructor doesn't take it directly
run_context.session.userdata = userdata

await run_context.session.update_agent(new_agent)
2) Factory/preset + partial reuse (keeps constructors simple)
Copy code
def agent_from_current(base_agent, *, instructions=None, tts=None, stt=None):
    # build a new agent reusing base_agent settings, overriding only passed fields
    return MyAgent(
        chat_ctx=base_agent.chat_ctx,
        tools=base_agent.tools,
        instructions=instructions or base_agent.instructions,
        tts=tts or base_agent.tts,
        stt=stt or base_agent.stt,
        # reuse any other shared config
    )

new_agent = agent_from_current(current_agent, instructions="Now Spanish", tts=new_tts)
await run_context.session.update_agent(new_agent)
Notes and tips • Don’t mutate private fields (
_tts
,
_stt
) — they’re unsupported and cause one-turn or inconsistent behavior. • Preserve
userdata
via
run_context.session.userdata
so any persisted state survives the handoff. • If your Agent subclass has complex init logic, wrap that logic in a factory that accepts overrides to keep handoff cheap. • You can also call
await run_context.session.active_agent.update_instructions(...)
if you can access the active agent and only need to change instructions. If you paste a short snippet of your current agent class or the tool code that performs the switch, I’ll convert it into the exact clone/factory + update_agent changes to use. Which snippet do you want to share? Sources: Agents and handoffs | LiveKit docs | Agents v0.x migration guide - Python | LiveKit docs | Workflows | LiveKit docs
a
My agent doesn't take stt and tts as parameters, rather, they are set in the agent_session
t
Yes — since your agent sets STT/TTS at the session level, you can still perform a handoff that uses the current agent as the base and override STT/ TTS (and instructions) on the new agent instance. Do this from your tool using the session’s active agent state to preserve chat_ctx/userdata and only change the fields you need. Minimal pattern (from a tool using run_context):
Copy code
current_agent = run_context.session.active_agent
chat_ctx = current_agent.chat_ctx
userdata = run_context.session.userdata
tools = current_agent.tools  # copy or reuse as needed

# create a replacement agent (same class) reusing current state
new_agent = type(current_agent)(
    chat_ctx=chat_ctx,
    # keep other constructor args the same or use factory to reuse config
)

# override agent-level fields (these take precedence over session defaults)
new_agent.instructions = "Respond in Spanish."
new_agent.stt = DeepgramSTT(language="es")    # per-agent override
new_agent.tts = CartesiaTTS(voice="es_voice") # per-agent override

# preserve userdata if needed
run_context.session.userdata = userdata

# perform handoff
await run_context.session.update_agent(new_agent)
Notes and tips • Do NOT mutate private session fields (
session._stt
,
session._tts
) — unsupported and unreliable. • If your Agent constructor is complex, wrap construction in a factory that accepts overrides to keep handoffs cheap. •
chat_ctx
and
userdata
persist across handoffs when copied into the new agent. • If you only need instruction changes and can access the active agent,
await run_context.session.active_agent.update_instructions("...")
is simpler. If you paste a short snippet of your current agent class or the tool function that performs the switch, I’ll produce the exact minimal refactor to use this clone+override handoff pattern. Which snippet shall I work from? Sources: Models | LiveKit Docs | Agents and handoffs | LiveKit docs
a
I can't access the stt/tts setters from my child agent class
t
Thanks — understood. If your child agent class doesn't expose STT/TTS setters in the constructor, you can still perform a safe handoff by creating a new agent instance (same class) and assigning the `stt`/`tts` attributes directly on that new instance before calling the handoff. That avoids touching private session fields and preserves chat/userdata. What to do (minimal, supported pattern) 1. From your tool (with
run_context
), grab current state:
Copy code
current = run_context.session.active_agent
chat_ctx = current.chat_ctx
userdata = run_context.session.userdata
1. Instantiate a new agent (same class) using the same constructor you already use:
Copy code
new_agent = type(current)(chat_ctx=chat_ctx, /* other ctor args */)
1. Override the agent-level fields directly on the new instance:
Copy code
new_agent.instructions = "New instructions..."
new_agent.stt = DeepgramSTT(language="es")
new_agent.tts = CartesiaTTS(voice="es_voice")
1. Preserve userdata if needed:
Copy code
run_context.session.userdata = userdata
1. Perform the handoff:
Copy code
await run_context.session.update_agent(new_agent)
Why this works • The session prefers an agent's `.stt`/`.tts` when present, so per-agent overrides apply even if the session-level defaults were set originally. • This avoids mutating private internals (
_stt
,
_tts
) which cause the inconsistent one-turn behavior you saw. • You only replace the active agent; session/chat history and userdata can be preserved. If direct attribute assignment is blocked by your agent's implementation (e.g.,
__setattr__
prevented), use a small factory or subclass wrapper that sets the attributes after construction, or copy relevant internal config into the new agent before handoff. If you share a 10–15 line snippet of your agent class and the tool function that triggers the switch, I’ll produce the exact minimal refactor (factory or wrapper) that will work with your class. Which snippet would you like to paste?