rich-application-94483
12/05/2025, 2:26 PMtall-airline-16756
12/05/2025, 2:26 PMtall-airline-16756
12/05/2025, 2:26 PMclass MyAgent(Agent):
async def on_exit(self):
summary = await self.session.generate_reply(
instructions="Generate a concise summary of the key points from this conversation."
)
# Optionally store/send the summary
await save_summary(summary)
2) TypeScript
class MyAgent extends Agent {
async onExit(): Promise<void> {
const summary = await this.session.generateReply({
instructions: "Generate a concise summary of the key points from this conversation."
});
// Optionally store/send the summary
await saveSummary(summary);
}
}
Notes and tips:
• Use clear, specific instructions (e.g., include desired length, bullet points, action items).
• Save or send the returned summary before the session teardown so it isn't lost.
• If you need the summary in a particular format (JSON, bullets, include timestamps), add that to instructions.
Would you like an example instruction prompt tuned for meeting notes, action items, or a one-paragraph recap?
Sources: Pipeline nodes and hooks | LiveKit docsrich-application-94483
12/05/2025, 2:27 PMtall-airline-16756
12/05/2025, 2:28 PMgenerate_reply (safe, simple)
1. Turn off agent audio output so no TTS audio is published:
◦ Python: self.session.output.set_audio_enabled(False)
◦ TypeScript: this.session.output.setAudioEnabled(false)
1. Call generate_reply() to produce the summary and extract the text from the returned events.
2. Save/send the text summary to your DB or external service; do NOT call session.say() or any TTS method.
Python sketch:
async def on_exit(self):
self.session.output.set_audio_enabled(False)
result = await self.session.generate_reply(instructions="Summarize the conversation in 3 bullets.")
summary = extract_text_from_result(result) # parse assistant message events
await save_summary(summary)
Option B — Call the LLM directly (bypasses agent output pipeline)
1. Use the LLM chat API directly with the current chat context so you get text-only output that never touches the TTS node.
2. Aggregate streamed chunks or final response into summary.
3. Persist the summary; do not route it back into session output.
Python sketch:
async def on_exit(self):
chat_ctx = self.session.chat_ctx
async with self.llm.chat(chat_ctx=chat_ctx) as stream:
summary = ""
async for chunk in stream:
summary += chunk.delta.content or ""
await save_summary(summary)
Option C — Use generate_reply but ensure it doesn't add to chat or trigger outputs
1. Call generate_reply() with any flags you have to avoid adding to the room/chat output (for example, don't call functions that enable transcription or audio).
2. Parse the returned events for assistant text, save it, and do not re-insert to session output.
Key rules to follow (apply to any option)
• Never call session.say() or any TTS helper with the summary.
• Ensure `audio_output`/agent audio is disabled while generating the summary.
• Extract and persist text from LLM response events rather than routing them into the session's output pipeline.
• If you use streaming LLM calls, collect text chunks and stop before sending anything to TTS.
If you tell me which language (Python or TypeScript) and whether you prefer to disable audio or call the LLM directly, I’ll give a copy-paste-ready implementation for your agent.
Sources: Agents and handoffs | LiveKit docs | How to Set Up Speech-to-Text Input with Text-Only Output in LiveKit Agents | Tool definition and use | LiveKit docs | Text and transcriptions | LiveKit docsrich-application-94483
12/05/2025, 2:48 PMtall-airline-16756
12/05/2025, 2:49 PMonExit hook to produce a text-only summary that never goes through TTS or gets published to the room. It collects the chat context, calls the LLM with text-only modalities, aggregates the streamed text, and stores the summary locally (or sends it to a DB) without using session.say() or generateReply().
import { voice } from '@livekit/agents';
class MyAgent extends voice.Agent {
constructor() {
super({ instructions: 'You are a helpful assistant.' });
}
async onExit(): Promise<void> {
const llmInstance = this.llm;
if (!llmInstance) {
console.warn('LLM instance not available');
return;
}
// Prepare a prompt to generate the summary
const summaryPrompt = {
role: 'system',
text: 'Summarize the conversation in 3 brief bullet points: key user inputs, decisions, and action items.',
};
try {
// Build a chat context based on the current session
const chatCtx = this.session.chatCtx.append(summaryPrompt);
// Call the LLM directly with text-only modality to avoid TTS/audio
const stream = await llmInstance.chat({
chatCtx,
// If supported by your model SDK, instruct text-only modalities
// This option shape may vary by model; adapt if your SDK uses a different field
modelOptions: { modalities: ['text'] },
});
// Aggregate streamed chunks into a single text summary
let summary = '';
for await (const chunk of stream) {
// chunk.text or chunk.delta.text depending on SDK; check your chunks
if (typeof (chunk as any).text === 'string') {
summary += (chunk as any).text;
} else if ((chunk as any).delta && (chunk as any).delta.content) {
summary += (chunk as any).delta.content;
}
}
// Persist or forward the summary without sending it to the room
// Example: attach to session userData, log, or call an external save function
if (this.session.userData) {
(this.session.userData as any).exitSummary = summary;
}
// Non-blocking external save/log
setImmediate(() => {
console.log('Exit summary (text-only):', summary);
// e.g., saveSummaryToDB(summary).catch(console.error);
});
} catch (err) {
console.error('Error generating text-only summary in onExit:', err);
}
}
}
Notes:
• Do NOT call session.say() or session.generateReply() if you want to avoid TTS/output pipelines.
• Ensure modelOptions.modalities = ['text'] (or equivalent for your model) so the LLM does not produce audio output.
• Save the resulting summary to your storage/DB or session.metadata; avoid sending it back into the room. Sources: Realtime model plugins | LiveKit Docs | Agents (Node.js) | livekit/livekit_composite | DeepWikiquiet-pilot-2691
12/10/2025, 9:34 AMextract_text_from_resulttall-airline-16756
12/10/2025, 9:35 AMextract_text_from_result that handles common shapes returned by generate_reply() or similar LLM call results. It extracts and concatenates assistant message text from event streams, handling arrays of content, chunked deltas, and a few common field names.
/**
* Extracts concatenated assistant text content from a generate_reply() result or LLM stream result.
* Handles various event shapes: message events, streamed chunks with `text` or `delta.content`.
*
* @param result The result object returned by session.generate_reply() or similar LLM call.
* It may be an object with `events: []` or an iterable/stream of chunks.
* @returns The combined assistant text as a single trimmed string.
*/
export function extract_text_from_result(result: any): string {
let output = '';
// Case A: result is an object with events array (e.g., generate_reply() final result)
if (result && Array.isArray(result.events)) {
for (const ev of result.events) {
// message-style event
if (ev?.type === 'message' && ev.message?.role === 'assistant') {
const content = ev.message.content;
if (Array.isArray(content)) {
for (const part of content) {
if (typeof part === 'string') output += part;
else if (part?.text) output += part.text;
else if (part?.content) output += String(part.content);
}
} else if (typeof content === 'string') {
output += content;
}
}
// some implementations put assistant text under ev.text or ev.message_text
if (!output && (typeof ev?.text === 'string')) {
output += ev.text;
} else if (!output && typeof ev?.message_text === 'string') {
output += ev.message_text;
}
}
return output.trim();
}
// Case B: result is an async iterable/stream (e.g., llm.chat() stream)
// We'll attempt to iterate synchronously if it's an array-like or handle generator-ish objects
try {
// If result is iterable (sync)
if (result && typeof (result as any)[Symbol.iterator] === 'function') {
for (const chunk of result as Iterable<any>) {
appendChunkText(chunk);
}
return output.trim();
}
// If result is async iterable (stream)
if (result && typeof (result as any)[Symbol.asyncIterator] === 'function') {
// Note: caller must use this function in an async context to await the async iterable.
// We don't await here to keep this function synchronous; return a placeholder.
// Prefer using the async helper below instead.
return output.trim();
}
} catch {
// fallthrough to best-effort checks below
}
// Case C: best-effort single-object shapes
if (result) {
if (typeof result === 'string') return result.trim();
if (typeof result.text === 'string') return result.text.trim();
if (result.delta?.content && typeof result.delta.content === 'string') {
return result.delta.content.trim();
}
}
return output.trim();
// Local helper to extract from a stream/chunk
function appendChunkText(chunk: any) {
if (!chunk) return;
// Common chunk shapes: { text: '...', delta: { content: '...' } }
if (typeof chunk.text === 'string') {
output += chunk.text;
return;
}
if (chunk.delta) {
if (typeof chunk.delta.content === 'string') {
output += chunk.delta.content;
return;
}
// some SDKs use delta.content as array
if (Array.isArray(chunk.delta.content)) {
for (const p of chunk.delta.content) {
if (typeof p === 'string') output += p;
else if (p?.text) output += p.text;
}
return;
}
}
// fallback to scanning chunk for string fields
for (const key of Object.keys(chunk)) {
const v = chunk[key];
if (typeof v === 'string') {
output += v;
return;
}
}
}
}
If you want an async version that fully consumes an async iterable stream (e.g., for await (const chunk of stream) { ... }) I can provide that as well — tell me if you need it to return a Promise<string> instead.quiet-pilot-2691
12/10/2025, 10:17 AMtall-airline-16756
12/10/2025, 10:17 AMextract_text_from_result (async and/or sync)?
• The helper that matches the Python LLM/stream shapes from earlier TypeScript examples?
• The full agent on_exit showing how to call the helper and save the summary?
Tell me which option (or mix) and whether you need async streaming support.quiet-pilot-2691
12/10/2025, 10:18 AMextract_text_from_result asynctall-airline-16756
12/10/2025, 10:19 AMextract_text_from_result that consumes an async iterable (LLM stream or result), handles common chunk/event shapes, and returns the concatenated assistant text. It ignores non-text events and avoids any TTS/publishing logic.
import asyncio
from typing import AsyncIterable, Any
async def extract_text_from_result(result: AsyncIterable[Any]) -> str:
"""
Consume an async iterable `result` (LLM stream or events) and extract/concatenate
assistant text content into a single string.
Handles common chunk shapes:
- chunk.text (str)
- chunk.delta.content (str)
- event objects with .type == 'message' and event.message.role == 'assistant'
where event.message.content may be a string or list of parts
Returns:
str: concatenated assistant text (trimmed)
"""
parts = []
async for chunk in result:
if chunk is None:
continue
# 1) Simple text field on chunk
text = getattr(chunk, "text", None)
if isinstance(text, str) and text:
parts.append(text)
continue
# 2) Delta style: chunk.delta.content
delta = getattr(chunk, "delta", None)
if delta is not None:
# delta.content might be a string or list
content = getattr(delta, "content", None)
if isinstance(content, str) and content:
parts.append(content)
continue
if isinstance(content, list):
for item in content:
if isinstance(item, str):
parts.append(item)
elif hasattr(item, "text") and isinstance(item.text, str):
parts.append(item.text)
continue
# 3) Event objects returned by generate_reply() with events array iteration
# Some streamed shapes yield full events directly.
evt_type = getattr(chunk, "type", None)
if evt_type == "message":
msg = getattr(chunk, "message", None)
if msg and getattr(msg, "role", None) == "assistant":
content = getattr(msg, "content", None)
if isinstance(content, str):
parts.append(content)
continue
if isinstance(content, list):
for c in content:
if isinstance(c, str):
parts.append(c)
elif getattr(c, "text", None):
parts.append(c.text)
continue
# 4) Fallback: inspect common dict-like shapes
if isinstance(chunk, dict):
# direct 'text' key
if "text" in chunk and isinstance(chunk["text"], str):
parts.append(chunk["text"])
continue
# delta.content in dict
delta = chunk.get("delta")
if isinstance(delta, dict):
content = delta.get("content")
if isinstance(content, str):
parts.append(content)
continue
if isinstance(content, list):
for item in content:
if isinstance(item, str):
parts.append(item)
continue
# message event shape
if chunk.get("type") == "message":
msg = chunk.get("message", {})
if msg.get("role") == "assistant":
content = msg.get("content")
if isinstance(content, str):
parts.append(content)
elif isinstance(content, list):
for c in content:
if isinstance(c, str):
parts.append(c)
return "".join(parts).strip()
If you want, I can:
• Add an example showing how to call this function with for await style LLM streams, or
• Provide a version that also accepts sync iterables or final result objects with an events array. Sources: Pipeline nodes and hooks | LiveKit docs | Testing and evaluation | LiveKit Docs | Text and transcriptions | LiveKit docsquiet-pilot-2691
12/10/2025, 10:21 AMfor await style LLM streams, ortall-airline-16756
12/10/2025, 10:22 AMextract_text_from_result function with a for-await style LLM stream inside an agent's on_exit hook, collect the summary, and save it without sending to TTS or the room.
# assume extract_text_from_result is already defined (async)
# async def extract_text_from_result(result: AsyncIterable[Any]) -> str: ...
class MyAgent:
def __init__(self, session, llm):
self.session = session
self.llm = llm
async def on_exit(self):
# Build prompt / chat context for summary
prompt = {
"role": "system",
"text": "Summarize the conversation in 3 bullet points: key inputs, decisions, action items."
}
# Append prompt to current chat context (API shape may vary)
chat_ctx = self.session.chat_ctx.append(prompt)
try:
# Call LLM directly to get an async iterable stream (text-only)
stream = await self.llm.chat({
"chatCtx": chat_ctx,
"modelOptions": {"modalities": ["text"]} # ensure text-only if supported
})
# Use the helper to extract concatenated text from the async stream
summary = await extract_text_from_result(stream)
# Persist the summary without publishing to the room
if self.session.userData is not None:
self.session.userData["exit_summary"] = summary
# Non-blocking external save/log (optional)
import asyncio
asyncio.get_event_loop().call_soon_threadsafe(lambda: print("Exit summary:", summary))
except Exception as e:
# handle errors quietly; do not call session.say() or any TTS
print("Failed to generate summary:", e)
Notes:
• Do not call session.say() or generate_reply() here; those can trigger TTS/output pipelines.
• Ensure modelOptions or equivalent forces text-only responses for your LLM SDK.
• Adapt chat_ctx.append and llm.chat argument shapes to match your SDK.quiet-pilot-2691
12/10/2025, 12:01 PMtall-airline-16756
12/10/2025, 12:01 PMfrom typing import AsyncIterable, Any
async def extract_text_from_result(result: AsyncIterable[Any]) -> str:
parts = []
async for chunk in result:
if chunk is None:
continue
text = getattr(chunk, "text", None)
if isinstance(text, str) and text:
parts.append(text)
continue
delta = getattr(chunk, "delta", None)
if delta is not None:
content = getattr(delta, "content", None)
if isinstance(content, str) and content:
parts.append(content)
continue
if isinstance(content, list):
for item in content:
if isinstance(item, str):
parts.append(item)
elif hasattr(item, "text") and isinstance(item.text, str):
parts.append(item.text)
continue
evt_type = getattr(chunk, "type", None)
if evt_type == "message":
msg = getattr(chunk, "message", None)
if msg and getattr(msg, "role", None) == "assistant":
content = getattr(msg, "content", None)
if isinstance(content, str):
parts.append(content)
continue
if isinstance(content, list):
for c in content:
if isinstance(c, str):
parts.append(c)
elif getattr(c, "text", None):
parts.append(c.text)
continue
if isinstance(chunk, dict):
if "text" in chunk and isinstance(chunk["text"], str):
parts.append(chunk["text"])
continue
delta = chunk.get("delta")
if isinstance(delta, dict):
content = delta.get("content")
if isinstance(content, str):
parts.append(content)
continue
if isinstance(content, list):
for item in content:
if isinstance(item, str):
parts.append(item)
continue
if chunk.get("type") == "message":
msg = chunk.get("message", {})
if msg.get("role") == "assistant":
content = msg.get("content")
if isinstance(content, str):
parts.append(content)
elif isinstance(content, list):
for c in content:
if isinstance(c, str):
parts.append(c)
return "".join(parts).strip()
my_agent.py
from typing import Any
from helpers import extract_text_from_result
class MyAgent:
def __init__(self, session, llm):
self.session = session
self.llm = llm
async def on_exit(self):
prompt = {"role": "system", "text": "Summarize the conversation in 3 bullets."}
chat_ctx = self.session.chat_ctx.append(prompt)
stream = await self.llm.chat({"chatCtx": chat_ctx, "modelOptions": {"modalities": ["text"]}})
summary = await extract_text_from_result(stream)
# persist without sending to room
if self.session.userData is not None:
self.session.userData["exit_summary"] = summary
print("Exit summary:", summary)
Notes:
• Ensure the module path is on Python's import path (same package or use a package init.py).
• If files are in different packages, use a relative import: from .helpers import extract_text_from_result.
• Keep the helper pure (no session/TTS calls) so it’s reusable and testable.quiet-pilot-2691
12/11/2025, 6:57 AMTraceback (most recent call last):
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/venv/lib/python3.13/site-packages/opentelemetry/util/_decorator.py", line 71, in async_wrapper
return await func(*args, **kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/venv/lib/python3.13/site-packages/livekit/agents/ipc/job_proc_lazy_main.py", line 286, in _traceable_entrypoint
await self._job_entrypoint_fnc(job_ctx)
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/agent.py", line 199, in entrypoint
agent=Assistant(
~~~~~~~~~^
session=session, llm=session.llm, instructions=formatted_agent_instructions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
),
^
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/agent.py", line 46, in __init__
self.session = session
^^^^^^^^^^^^
AttributeError: property 'session' of 'Assistant' object has no setter
2025-12-11 12:25:17,843 [ERROR] unhandled exception while running the job task
Traceback (most recent call last):
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/venv/lib/python3.13/site-packages/opentelemetry/util/_decorator.py", line 71, in async_wrapper
return await func(*args, **kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/venv/lib/python3.13/site-packages/livekit/agents/ipc/job_proc_lazy_main.py", line 286, in _traceable_entrypoint
await self._job_entrypoint_fnc(job_ctx)
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/agent.py", line 199, in entrypoint
agent=Assistant(
~~~~~~~~~^
session=session, llm=session.llm, instructions=formatted_agent_instructions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
),
^
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/agent.py", line 46, in __init__
self.session = session
^^^^^^^^^^^^
AttributeError: property 'session' of 'Assistant' object has no setter
Traceback (most recent call last):
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/venv/lib/python3.13/site-packages/opentelemetry/util/_decorator.py", line 71, in async_wrapper
return await func(*args, **kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/venv/lib/python3.13/site-packages/livekit/agents/ipc/job_proc_lazy_main.py", line 286, in _traceable_entrypoint
await self._job_entrypoint_fnc(job_ctx)
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/agent.py", line 199, in entrypoint
agent=Assistant(
~~~~~~~~~^
session=session, llm=session.llm, instructions=formatted_agent_instructions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
),
^
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/agent.py", line 46, in __init__
self.session = session
^^^^^^^^^^^^
AttributeError: property 'session' of 'Assistant' object has no setter
12:25:17.843 ERROR livekit.agents unhandled exception while running the job task
Traceback (most recent call last):
File
"/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/venv/lib/python3.13/site-packages/opentelemetry/util/_…
line 71, in async_wrapper
return await func(*args, **kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File
"/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/venv/lib/python3.13/site-packages/livekit/agents/ipc/j…
line 286, in _traceable_entrypoint
await self._job_entrypoint_fnc(job_ctx)
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/agent.py", line 199, in entrypoint
agent=Assistant(
~~~~~~~~~^
session=session, llm=session.llm, instructions=formatted_agent_instructions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
),
^
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/agent.py", line 46, in __init__
self.session = session
^^^^^^^^^^^^
AttributeError: property 'session' of 'Assistant' object has no setter
{"room": "gopichandar_pandian_room", "pid": 39484, "job_id": "AJ_v2z3Ktc5RGA4", "room_id": "RM_d65PwXNFJpgc"}tall-airline-16756
12/11/2025, 6:57 AMsession as a read-only property. Assigning to self.session = ... in your subclass triggers that AttributeError.
Fixes (pick one):
1) Accept the base class session and don't overwrite it
• Remove any assignment to self.session in your init.
• Use the session provided by the framework (usually set after construction) or access it via provided callbacks.
Example (recommended)
# helpers.py
from typing import AsyncIterable, Any
async def extract_text_from_result(result: AsyncIterable[Any]) -> str:
parts = []
async for chunk in result:
if chunk is None:
continue
text = getattr(chunk, "text", None)
if isinstance(text, str) and text:
parts.append(text); continue
delta = getattr(chunk, "delta", None)
if delta is not None:
content = getattr(delta, "content", None)
if isinstance(content, str) and content:
parts.append(content); continue
if isinstance(content, list):
for item in content:
if isinstance(item, str):
parts.append(item)
elif hasattr(item, "text") and isinstance(item.text, str):
parts.append(item.text)
continue
if getattr(chunk, "type", None) == "message":
msg = getattr(chunk, "message", None)
if msg and getattr(msg, "role", None) == "assistant":
content = getattr(msg, "content", None)
if isinstance(content, str):
parts.append(content); continue
if isinstance(content, list):
for c in content:
if isinstance(c, str):
parts.append(c)
elif getattr(c, "text", None):
parts.append(c.text)
continue
if isinstance(chunk, dict):
if "text" in chunk and isinstance(chunk["text"], str):
parts.append(chunk["text"]); continue
delta = chunk.get("delta")
if isinstance(delta, dict):
content = delta.get("content")
if isinstance(content, str):
parts.append(content); continue
if isinstance(content, list):
for item in content:
if isinstance(item, str):
parts.append(item)
continue
if chunk.get("type") == "message":
msg = chunk.get("message", {})
if msg.get("role") == "assistant":
content = msg.get("content")
if isinstance(content, str):
parts.append(content)
elif isinstance(content, list):
for c in content:
if isinstance(c, str):
parts.append(c)
return "".join(parts).strip()
# my_agent.py
from livekit.agents import voice # or the correct base class import
from helpers import extract_text_from_result
class Assistant(voice.Agent):
def __init__(self, instructions: str):
# Pass instructions to base class; do NOT set self.session here
super().__init__(instructions=instructions)
async def on_exit(self):
# The framework should provide self.session (read-only); use it directly
chat_ctx = self.session.chat_ctx.append({
"role": "system",
"text": "Summarize the conversation in 3 bullet points."
})
# Call LLM directly for text-only stream
stream = await self.llm.chat({
"chatCtx": chat_ctx,
"modelOptions": {"modalities": ["text"]}
})
summary = await extract_text_from_result(stream)
# Persist without publishing
if self.session.userData is not None:
self.session.userData["exit_summary"] = summary
print("Exit summary:", summary)
2) If you need to accept session and llm at construction time
• Only do this if the base Agent supports passing them into super().init or storing them via provided API.
• Example: call super().*init*(..., session=session, llm=llm) if the base supports those parameters. Do not assign directly to self.session.
3) Alternative: use different attribute names
• If you must keep constructor args, store them under another name (e.g., self._initial_session) and avoid touching the read-only property. But this is less idiomatic than using the framework's session.
Next step I can provide:
• A quick audit of your init so I can show the minimal change, or
• A version that passes session/llm into super() if your base class supports it.
Which would you like?quiet-pilot-2691
12/11/2025, 8:44 AMasync def on_exit(self):
logger.info("==== On exit 2 ====")
self.session.output.set_audio_enabled(False)
prompt = {
"role": "system",
"text": "Summarize the conversation in 2 topics: 'Overview' and 'Summary'",
}
chat_ctx = self.session.chat_ctx.append(prompt)
stream = await self.session.llm.chat(
{"chatCtx": chat_ctx, "modelOptions": {"modalities": ["text"]}}
)
summary = await extract_text_from_result(stream)
my python agent application has above code to generate the conversation summary after the complete conversation.
But with the above code, I am getting below error:
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/venv/lib/python3.13/site-packages/livekit/agents/voice/agent_activity.py", line 603, in _traceable_on_exit
await self._agent.on_exit()
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/agent.py", line 65, in on_exit
chat_ctx = self.session.chat_ctx.append(prompt)
^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'AgentSession' object has no attribute 'chat_ctx'
14:11:48.643 ERROR livekit.agents Error in _aclose_impl
Traceback (most recent call last):
File
"/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/venv/lib/python3.13/site…
line 16, in async_fn_logs
return await fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File
"/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/venv/lib/python3.13/site…
line 773, in _aclose_impl
await self._activity.drain()
File
"/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/venv/lib/python3.13/site…
line 71, in async_wrapper
return await func(*args, **kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File
"/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/venv/lib/python3.13/site…
line 613, in drain
await self._on_exit_tasktall-airline-16756
12/11/2025, 8:44 AMAgentSession does not expose chat_ctx. The agent's chat context and LLM live on the Agent instance itself. Use self.chat_ctx (or a copy of it) and self.llm inside on_exit. Also don't call session.generate_reply() or session.say() if you want to avoid TTS — call the LLM directly and persist the returned text.
Use this corrected pattern in your agent:
from typing import Any
async def on_exit(self) -> None:
# disable audio so nothing is published
self.session.output.set_audio_enabled(False)
# copy the agent-owned chat context and append a system instruction
chat_ctx = self.chat_ctx.copy()
chat_ctx.add_message(
role="system",
content="Summarize the conversation in 2 topics: 'Overview' and 'Summary'."
)
# call the LLM directly (text-only) and stream the response
summary = ""
async with self.llm.chat(chat_ctx=chat_ctx, modelOptions={"modalities": ["text"]}) as stream:
async for chunk in stream:
# common chunk shapes: chunk.delta.content or chunk.text
if getattr(chunk, "delta", None) and getattr(chunk.delta, "content", None):
summary += chunk.delta.content
elif getattr(chunk, "text", None):
summary += chunk.text
elif isinstance(chunk, dict):
# fallback for dict-shaped chunks
if chunk.get("delta") and isinstance(chunk["delta"].get("content"), str):
summary += chunk["delta"]["content"]
elif isinstance(chunk.get("text"), str):
summary += chunk["text"]
summary = summary.strip()
# persist without publishing to the room
if self.session.userData is not None:
self.session.userData["exit_summary"] = summary
# optional: log/save externally (do NOT call TTS or session.say)
print("Exit summary (text-only):", summary)
Key points:
• Use self.chat_ctx (agent-owned) not self.session.chat_ctx.
• Use self.llm.chat(chat_ctx=...) (keyword chat_ctx) and set text-only modalities if supported.
• Aggregate text from streamed chunks (delta.content or text) and save it; do not call any TTS methods.
If you want, I can:
• Provide a small helper to normalize chunk shapes into text,
• Show a version that uses your existing extract_text_from_result helper integrated into this on_exit. Which would you prefer? Sources: Agents and handoffs | LiveKit docs | External data and RAG | LiveKit Docs | Large language models (LLM) | LiveKit Docsquiet-pilot-2691
12/11/2025, 11:07 AMFile "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/venv/lib/python3.13/site-packages/livekit/agents/voice/agent_activity.py", line 603, in _traceable_on_exit
await self._agent.on_exit()
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/agent.py", line 65, in on_exit
chat_ctx = self.chat_ctx.add_message(prompt)
TypeError: ChatContext.add_message() takes 1 positional argument but 2 were given
2025-12-11 16:36:43,453 [ERROR] Error in _traceable_on_exit
Traceback (most recent call last):
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/venv/lib/python3.13/site-packages/livekit/agents/utils/log.py", line 16, in async_fn_logs
return await fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/venv/lib/python3.13/site-packages/livekit/agents/voice/agent_activity.py", line 603, in _traceable_on_exit
await self._agent.on_exit()
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/agent.py", line 65, in on_exit
chat_ctx = self.chat_ctx.add_message(prompt)
TypeError: ChatContext.add_message() takes 1 positional argument but 2 were given
Traceback (most recent call last):
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/venv/lib/python3.13/site-packages/livekit/agents/utils/log.py", line 16, in async_fn_logs
return await fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/venv/lib/python3.13/site-packages/livekit/agents/voice/agent_activity.py", line 603, in _traceable_on_exit
await self._agent.on_exit()
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/agent.py", line 65, in on_exit
chat_ctx = self.chat_ctx.add_message(prompt)
TypeError: ChatContext.add_message() takes 1 positional argument but 2 were given
2025-12-11 16:36:43,457 [ERROR] Error in _aclose_impl
Traceback (most recent call last):
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/venv/lib/python3.13/site-packages/livekit/agents/utils/log.py", line 16, in async_fn_logs
return await fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/venv/lib/python3.13/site-packages/livekit/agents/voice/agent_session.py", line 773, in _aclose_impl
await self._activity.drain()
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/venv/lib/python3.13/site-packages/opentelemetry/util/_decorator.py", line 71, in async_wrapper
return await func(*args, **kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/venv/lib/python3.13/site-packages/livekit/agents/voice/agent_activity.py", line 613, in drain
await self._on_exit_task
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/venv/lib/python3.13/site-packages/livekit/agents/voice/agent_activity.py", line 405, in _context_aware_coro
return await coro
^^^^^^^^^^
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/venv/lib/python3.13/site-packages/opentelemetry/util/_decorator.py", line 71, in async_wrapper
return await func(*args, **kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/venv/lib/python3.13/site-packages/livekit/agents/utils/log.py", line 16, in async_fn_logs
return await fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/venv/lib/python3.13/site-packages/livekit/agents/voice/agent_activity.py", line 603, in _traceable_on_exit
await self._agent.on_exit()
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/agent.py", line 65, in on_exit
chat_ctx = self.chat_ctx.add_message(prompt)
TypeError: ChatContext.add_message() takes 1 positional argument but 2 were given
ERROR livekit.agents Error in _traceable_on_exit
Traceback (most recent call last):
File
"/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/venv/lib/python3.13/site…
line 16, in async_fn_logs
return await fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File
"/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/venv/lib/python3.13/site…
line 603, in _traceable_on_exit
await self._agent.on_exit()
File "/Users/gopichandar.pandian.ext/projects/bay-pharma-sales-agent/agent.py", line
65, in on_exit
chat_ctx = self.chat_ctx.add_message(prompt)
TypeError: ChatContext.add_message() takes 1 positional argument but 2 were given
{"room": "gopichandar_pandian_room", "pid": 69404, "job_id": "AJ_vz7nZvmrbnNy", "room_id":
"RM_xXQGrkABU3ej"}tall-airline-16756
12/11/2025, 11:08 AMadd_message with a positional arg. ChatContext.add_message() expects keyword args (e.g., role=..., content=...) and returns None (it mutates the context in-place). Change your code from:
chat_ctx = self.chat_ctx.add_message(prompt)
to:
# add the system instruction to the existing context (in-place)
self.chat_ctx.add_message(
role="system",
content="Summarize the conversation in 2 topics: 'Overview' and 'Summary'."
)
# if you prefer a copy to avoid mutating live context:
summary_ctx = self.chat_ctx.copy()
summary_ctx.add_message(
role="system",
content="Summarize the conversation in 2 topics: 'Overview' and 'Summary'."
)
Then call the LLM with the context (example using a copy and your existing helper):
self.session.output.set_audio_enabled(False)
summary_ctx = self.chat_ctx.copy()
summary_ctx.add_message(
role="system",
content="Summarize the conversation in 2 topics: 'Overview' and 'Summary'."
)
async with self.llm.chat(chat_ctx=summary_ctx, modelOptions={"modalities": ["text"]}) as stream:
summary = await extract_text_from_result(stream)
# persist without publishing
if self.session.userData is not None:
self.session.userData["exit_summary"] = summary
That fixes the TypeError and keeps the summary text-only (no TTS). Would you like me to convert this into a full on_exit snippet using your existing helper?
Sources: Agents v0.x migration guide - Python | LiveKit docs | Pipeline nodes and hooks | LiveKit docs | Agents v0.x migration guide - Node.js | LiveKit Docsquiet-pilot-2691
12/11/2025, 12:42 PMasync def on_exit(self):
self.session.output.set_audio_enabled(False)
# if you prefer a copy to avoid mutating live context:
summary_ctx = self.chat_ctx.copy()
summary_ctx.add_message(
role="system",
content="Summarize the conversation in 2 topics: 'Overview' and 'Summary'.",
)
async with self.session.llm.chat(
chat_ctx=summary_ctx, modelOptions={"modalities": ["text"]}
) as stream:
summary = await extract_text_from_result(stream)
# persist without sending to room
if self.session.userData is not None:
self.session.userData["exit_summary"] = summary
print("Exit summary:", summary)
why I am getting below error, please give me correct code:
"/Users/projects/sales-agent/venv/lib/python3.13/site-packages/opentelemetry/util/_decorator.py",
line 71, in async_wrapper
return await func(*args, **kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File
"/Users/projects/sales-agent/venv/lib/python3.13/site-packages/livekit/agents/voice/agent_activity.
py", line 613, in drain
await self._on_exit_task
File
"/Users/projects/sales-agent/venv/lib/python3.13/site-packages/livekit/agents/voice/agent_activity.
py", line 405, in _context_aware_coro
return await coro
^^^^^^^^^^
File
"/Users/gopichandar.pandian.ext/projects/sales-agent/venv/lib/python3.13/site-packages/opentelemetry/util/_decorator.py",
line 71, in async_wrapper
return await func(*args, **kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/projects/sales-agent/venv/lib/python3.13/site-packages/livekit/agents/utils/log.py",
line 16, in async_fn_logs
return await fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File
"/Users/projects/sales-agent/venv/lib/python3.13/site-packages/livekit/agents/voice/agent_activity.
py", line 603, in _traceable_on_exit
await self._agent.on_exit()
File "/Users/projects/sales-agent/agent.py", line 75, in on_exit
async with self.session.llm.chat(
~~~~~~~~~~~~~~~~~~~~~^
chat_ctx=summary_ctx, modelOptions={"modalities": ["text"]}
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
) as stream:
^
TypeError: LLM.chat() got an unexpected keyword argument 'modelOptions'. Did you mean 'conn_options'?tall-airline-16756
12/11/2025, 12:42 PMmodelOptions — use the correct kwargs for your SDK (e.g., chat_ctx= and conn_options= / options= depending on your version). Also prefer streaming with async with self.llm.chat(chat_ctx=...) as stream: and iterate to pass into your extractor.
Try this corrected snippet (uses conn_options={"modalities": ["text"]} which matches the error hint). Adjust conn_options name if your SDK version uses a different param.
async def on_exit(self):
# prevent any audio from being published
self.session.output.set_audio_enabled(False)
# copy context and add system instruction (mutates copy)
summary_ctx = self.chat_ctx.copy()
summary_ctx.add_message(
role="system",
content="Summarize the conversation in 2 topics: 'Overview' and 'Summary'."
)
# call the LLM directly in text-only mode (use conn_options per your SDK)
summary = ""
try:
async with self.llm.chat(chat_ctx=summary_ctx, conn_options={"modalities": ["text"]}) as stream:
# stream is an async iterable of chunks/events
summary = await extract_text_from_result(stream)
except TypeError:
# fallback: if your SDK expects no conn_options, call without it
async with self.llm.chat(chat_ctx=summary_ctx) as stream:
summary = await extract_text_from_result(stream)
# persist without sending to room
if self.session.userData is not None:
self.session.userData["exit_summary"] = summary
print("Exit summary:", summary)
If this still errors with the keyword name, tell me the LiveKit Agents package version (e.g., the output of pip show livekit-agents), and I will give the exact parameter name to use.quiet-pilot-2691
12/11/2025, 12:52 PM"/Users/projects/sales-agent/venv/lib/python3.13/site…
line 16, in async_fn_logs
return await fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File
"/Users/projects/sales-agent/venv/lib/python3.13/site…
line 603, in _traceable_on_exit
await self._agent.on_exit()
File "/Users/projects/sales-agent/agent.py", line
83, in on_exit
summary = await extract_text_from_result(stream)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/projects/sales-agent/helpers.py", line
6, in extract_text_from_result
async for chunk in result:
...<58 lines>...
parts.append(c)
File
"/Users/projects/sales-agent/venv/lib/python3.13/site…
line 346, in __anext__
raise exc # noqa: B904
^^^^^^^^^
File
"/Users/projects/sales-agent/venv/lib/python3.13/site…
line 173, in _traceable_main_task
await self._main_task()
File
"/Users/projects/sales-agent/venv/lib/python3.13/site…
line 187, in _main_task
for i in range(self._conn_options.max_retry + 1):
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'dict' object has no attribute 'max_retry'
{"room": "gopichandar_pandian_room", "pid": 70684, "job_id": "AJ_Kp4kHjRhnvT3", "room_id":
"RM_kZYpkgw5SoAR"}
Traceback (most recent call last):
File "/Users/projects/sales-agent/venv/lib/python3.13/site-packages/livekit/agents/llm/llm.py",
line 343, in __anext__
val = await self._event_aiter.__anext__()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
StopAsyncIteration
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/projects/sales-agent/venv/lib/python3.13/site-packages/livekit/agents/utils/log.py",
line 16, in async_fn_logs
return await fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File
"/Users/projects/sales-agent/venv/lib/python3.13/site-packages/livekit/agents/ipc/job_proc_lazy_mai
n.py", line 327, in _run_job_task
await session.aclose()
File
"/Users/projects/sales-agent/venv/lib/python3.13/site-packages/livekit/agents/voice/agent_session.p
y", line 839, in aclose
await self._aclose_impl(reason=CloseReason.USER_INITIATED)
File "/Users/projects/sales-agent/venv/lib/python3.13/site-packages/livekit/agents/utils/log.py",
line 16, in async_fn_logs
return await fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File
"/Users/projects/sales-agent/venv/lib/python3.13/site-packages/livekit/agents/voice/agent_session.p
y", line 773, in _aclose_impl
await self._activity.drain()
File
"/Users/projects/sales-agent/venv/lib/python3.13/site-packages/opentelemetry/util/_decorator.py",
line 71, in async_wrapper
return await func(*args, **kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File
"/Users/projects/sales-agent/venv/lib/python3.13/site-packages/livekit/agents/voice/agent_activity.
py", line 613, in drain
await self._on_exit_task
File
"/Users/projects/sales-agent/venv/lib/python3.13/site-packages/livekit/agents/voice/agent_activity.
py", line 405, in _context_aware_coro
return await coro
^^^^^^^^^^
File
"/Users/projects/sales-agent/venv/lib/python3.13/site-packages/opentelemetry/util/_decorator.py",
line 71, in async_wrapper
return await func(*args, **kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/projects/sales-agent/venv/lib/python3.13/site-packages/livekit/agents/utils/log.py",
line 16, in async_fn_logs
return await fn(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File
"/Users/projects/sales-agent/venv/lib/python3.13/site-packages/livekit/agents/voice/agent_activity.
py", line 603, in _traceable_on_exit
await self._agent.on_exit()
File "/Users/projects/sales-agent/agent.py", line 83, in on_exit
summary = await extract_text_from_result(stream)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/projects/sales-agent/helpers.py", line 6, in extract_text_from_result
async for chunk in result:
...<58 lines>...
parts.append(c)
File "/Users/projects/sales-agent/venv/lib/python3.13/site-packages/livekit/agents/llm/llm.py",
line 346, in __anext__
raise exc # noqa: B904
^^^^^^^^^
File "/Users/projects/sales-agent/venv/lib/python3.13/site-packages/livekit/agents/llm/llm.py",
line 173, in _traceable_main_task
await self._main_task()
File "/Users/projects/sales-agent/venv/lib/python3.13/site-packages/livekit/agents/llm/llm.py",
line 187, in _main_task
for i in range(self._conn_options.max_retry + 1):
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'dict' object has no attribute 'max_retry'tall-airline-16756
12/11/2025, 12:52 PMllm.chat(...) with the correct keyword args for your SDK (no raw `modelOptions`/`modelOptions` dict). Use either no extra options or the SDK's Connection/ConnOptions object. 2) Consume the stream with your existing async extractor.
Try this corrected, minimal on_exit implementation — it avoids TTS, uses the agent-owned chat context, and does not pass a raw dict for connection options:
from livekit.agents.llm import ConnectionOptions # if your SDK exposes this
# or omit ConnectionOptions if you don't need custom options
async def on_exit(self):
# Prevent any audio from being published
self.session.output.set_audio_enabled(False)
# Build a copy of the chat context and append a system instruction (mutates the copy)
summary_ctx = self.chat_ctx.copy()
summary_ctx.add_message(
role="system",
content="Summarize the conversation in 2 topics: 'Overview' and 'Summary'."
)
# Use your session's LLM (or a properly constructed LLM client).
# Option A: No extra conn options (preferred if unsure)
try:
async with self.session.llm.chat(chat_ctx=summary_ctx) as stream:
summary = await extract_text_from_result(stream)
except TypeError:
# Option B: If you must set connection options, construct the SDK options object
conn_opts = ConnectionOptions(max_retry=3) # use SDK class, not a dict
async with self.session.llm.chat(chat_ctx=summary_ctx, conn_options=conn_opts) as stream:
summary = await extract_text_from_result(stream)
# Persist without sending to the room
if self.session.userData is not None:
self.session.userData["exit_summary"] = summary
print("Exit summary:", summary)
Notes:
• Do not pass raw dicts like {"modalities": ["text"]} or {"max_retry": 3} into llm.chat or LLM constructors; the SDK expects a specific ConnectionOptions/ConnOptions type (hence the AttributeError on .max_retry).
• If you need text-only modality and your SDK supports it, pass the appropriate typed option (e.g., ConnectionOptions or conn_options) — check your livekit-agents version for the exact class/param name.
• If you still hit a TypeError about unexpected keyword names, run pip show livekit-agents and tell me the version and I will give the exact parameter name and usage for that version.
If you want, I can:
• Provide the correct ConnectionOptions import and usage for your installed livekit-agents version, or
• Inspect your current LLM/llm initialization snippet and show exactly how to construct it without using raw dicts. Which do you prefer?