most-dawn-67700
12/01/2025, 7:59 AMtall-airline-16756
12/01/2025, 7:59 AMtall-airline-16756
12/01/2025, 8:00 AMchat_ctx (for example self.session.chat_ctx or a custom-constructed chat_ctx) forwards:
• user and assistant messages (ChatMessage)
• tool/function calls initiated by the LLM (FunctionCall)
• tool execution results (FunctionCallOutput)
If you do not pass chat_ctx, a new agent starts with a fresh conversation history (effectively only the new transcript). Regardless of chat_ctx, the complete session conversation history (all messages and tool interactions) is always available in session.history.
Sources: Agents and handoffs | LiveKit docs | Agents v0.x migration guide - Node.js | LiveKit Docsmost-dawn-67700
12/01/2025, 11:09 AMtall-airline-16756
12/01/2025, 11:09 AMchat_ctx object.
1) Collect the existing chat context
• Use the session's current chat context (for example self.session.chat_ctx) or build a chat_ctx that includes:
◦ ChatMessage entries (user and assistant messages)
◦ FunctionCall entries (tool calls initiated by the LLM)
◦ FunctionCallOutput entries (results returned from tool executions)
2) Attach an AgentHandoff marker (optional but recommended)
• Add an AgentHandoff item to the chat_ctx with old_agent_id and new_agent_id to track the transfer.
3) Pass the chat_ctx to the new agent on initialization
• When creating or activating the new agent, pass the collected chat_ctx (e.g., new_agent.start(chat_ctx=previous_chat_ctx) or assign new_agent.session.chat_ctx = previous_chat_ctx depending on your integration). This ensures the new agent receives messages, function calls, and function outputs in their original form.
4) Verify full history availability
• The complete session conversation history is also available in `session.history`; you can read from there if you need to reconstruct or validate the chat_ctx before passing it.
If you’d like, tell me which SDK/language you’re using (server SDK, JS, Python, or other) and I’ll provide a concrete code snippet for passing chat_ctx during handoff.most-dawn-67700
12/01/2025, 11:11 AMtall-airline-16756
12/01/2025, 11:11 AMchat_ctx. I can help troubleshoot and give concrete steps/examples so the transferred agent receives those results.
Quick clarification: which SDK/language are you using (server, JavaScript, or Python)? Also tell me whether you’re:
• directly passing self.session.chat_ctx at handoff, or
• building a custom chat_ctx from session.history before passing it.
With that I’ll provide a short targeted checklist and a code snippet you can drop into your flow.most-dawn-67700
12/01/2025, 11:11 AMtall-airline-16756
12/01/2025, 11:12 AMself.session.chat_ctx, here’s a short checklist and a small Python snippet to verify and ensure FunctionCall and FunctionCallOutput items are preserved and passed to the new agent.
Checklist
• Confirm the tool actually returned a value (not None) and that the agent recorded a FunctionCallOutput.
• Inspect self.session.chat_ctx.items before handoff to confirm FunctionCall and FunctionCallOutput entries exist.
• Ensure you pass the exact chat_ctx object to the new agent (don’t rebuild or filter it unless you include function outputs).
• Check your code for any update_chat_ctx() or filters that might remove non-message items.
Quick verification snippet
# Inspect chat_ctx for function calls/outputs
for item in self.session.chat_ctx.items:
if getattr(item, "function_call", None):
print("FunctionCall:", item.function_call)
if getattr(item, "output", None):
print("FunctionCallOutput:", item.output)
Passing the full context on handoff
# Example: create/start new agent with full chat_ctx
new_agent = NewAgent(...)
new_agent.start(chat_ctx=self.session.chat_ctx)
# or
new_agent.session.chat_ctx = self.session.chat_ctx
Debug tips if outputs are missing
• Log the entire chat_ctx immediately after the tool run and right before handoff to see where the output disappears.
• Confirm the tool execution flow added a FunctionCallOutput (not just logged somewhere else).
• If you build a custom chat_ctx from session.history, include items whose type is FunctionCall and FunctionCallOutput rather than only message-like entries.
If you’d like, paste a minimal snippet where you perform the tool call and then hand off; I can point out exactly where the output might be getting lost.
Sources: Agents v0.x migration guide - Python | LiveKit docs | Agents and handoffs | LiveKit docs | Tool definition and use | LiveKit docs | Testing and evaluation | LiveKit Docsmost-dawn-67700
12/01/2025, 11:12 AMtall-airline-16756
12/01/2025, 11:13 AMself.session.chat_ctx, not self.chat_ctx.
Why:
• self.session.chat_ctx contains the full, up-to-date session context: ChatMessage, FunctionCall, and FunctionCallOutput items (plus AgentHandoff records).
• self.chat_ctx is typically the agent's initial/local context and may not include tool call outputs produced during the session.
What to do (quick checklist)
• Inspect self.session.chat_ctx.items for FunctionCall and FunctionCallOutput before handoff.
• Pass the exact self.session.chat_ctx to the new agent (don’t rebuild or filter it).
• Ensure the tool actually produced a FunctionCallOutput and that no function cleared or filtered the context.
Quick verification snippet
for item in self.session.chat_ctx.items:
if getattr(item, "function_call", None):
print("FunctionCall:", item.function_call)
if getattr(item, "output", None):
print("FunctionCallOutput:", item.output)
Passing on handoff
new_agent = SpecialistAgent(...)
new_agent.start(chat_ctx=self.session.chat_ctx)
# or
new_agent.session.chat_ctx = self.session.chat_ctx
If you're still missing outputs, paste the minimal code where you run the tool and then call the handoff and I’ll point out where the output may be lost.
Sources: Agents v0.x migration guide - Python | LiveKit docs | Agents and handoffs | LiveKit docsmost-dawn-67700
12/02/2025, 5:05 AMtall-airline-16756
12/02/2025, 5:05 AMself.session.chat_ctx captured at handoff time doesn't yet contain the FunctionCallOutput.
• Ordering: the handoff code may run before the agent runtime has appended the tool output to session chat context.
• Intermediate commits/filters: some code paths may write or copy chat context early (or filter non-message items) and hand that copy to the new agent.
What to do (recommended fixes)
• Wait for tool completion before initiating handoff:
◦ Ensure the tool call finishes and the framework has appended a FunctionCallOutput to self.session.chat_ctx before you create/activate the new agent.
• Hand off only after you confirm the output is present:
◦ Inspect self.session.chat_ctx.items and check for the corresponding FunctionCallOutput entry, then proceed.
• Use an explicit synchronization point:
◦ Add an acknowledgement step after tool execution (e.g., set a flag, return a completion status, or emit an event) and trigger handoff only when that signal is observed.
• Avoid passing stale copies:
◦ Always pass the live self.session.chat_ctx (not self.chat_ctx or a previously copied object).
• If tool execution is dispatched to background workers, have the worker append the output to session.chat_ctx and signal completion before handoff.
Debugging checklist (quick)
1. Log timestamps:
◦ Log when the tool call returns, when FunctionCallOutput is appended, and when handoff starts.
1. Inspect self.session.chat_ctx right before handoff:
◦ Confirm presence of the FunctionCallOutput.
1. Search for early copies or filters:
◦ Look for code that copies chat_ctx earlier in the flow or calls update_chat_ctx() in a way that clears non-message items.
1. If using async flows or background tasks:
◦ Ensure the handoff awaits the tool result or listens for a completion event.
If you share a minimal snippet showing how you call the tool and then perform the handoff (or tell me your SDK/language), I’ll point out the exact spot to add the synchronization/await and provide a concise code example.most-dawn-67700
12/02/2025, 5:16 AM@function_tool()
async def in_stock_sales_flow(self, ctx: RunContext):
"""Once all key details are collect, and you've confirmed inventory, use this transfer. Do not mention you're handing over to a new agent. It should be seamless from customers point of view."""
# Pass the agent's chat_ctx which contains the full conversation history
# Serialize session.history for validation
try:
history_dict = self.session.history.to_dict()
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
debug_file = f"/tmp/agent_transfer_history_{timestamp}.json"
with open(debug_file, 'w') as f:
json.dump(history_dict, f, indent=2, default=str)
logger.info(f"[TRANSFER] Session history exported to {debug_file}")
logger.info(f"[TRANSFER] History contains {len(history_dict.get('messages', []))} items")
except Exception as e:
logger.error(f"[TRANSFER] Failed to export history: {e}")
logger.info(f"[TRANSFER] Transferring to sales agent with session history")
return SalesAgent(chat_ctx=self.session.history)tall-airline-16756
12/02/2025, 5:16 AMSalesAgent(chat_ctx=self.session.history). That hands the other agent a session history object (which is message-centric) instead of the structured chat context that includes function calls and outputs. Also your handoff happens immediately without confirming the last tool output was appended.
What to change (concise)
1) Pass session.chat_ctx, not `session.history`:
return SalesAgent(chat_ctx=self.session.chat_ctx)
2) Ensure the tool output has been appended before handoff — wait/verify:
• After the tool run completes, check for a FunctionCallOutput in self.session.chat_ctx.items.
• Only return the new agent once that entry exists.
Example pattern (pseudo-Python):
# run tool -> tool appends FunctionCallOutput to session.chat_ctx
# then verify before handing off
for item in self.session.chat_ctx.items:
if getattr(item, "output", None):
break
else:
# wait/raise/log until output appears
await asyncio.sleep(0.1) # or use an event/ack from your tool runner
return SalesAgent(chat_ctx=self.session.chat_ctx)
Quick checklist to prevent race conditions
• Use self.session.chat_ctx (live, structured).
• Wait for tool completion or an explicit completion signal from the worker that produced the output.
• Avoid returning a new agent synchronously from the same async flow if your tool runs in background; instead await the tool's result or listen for an event that appends the output.
• Log timestamps for tool completion, context append, and handoff to confirm ordering.
If you want, paste the tool execution code (how you call/run the tool) and I’ll suggest the exact await/event placement for your flow.