most-dawn-67700
12/03/2025, 8:10 AMtall-airline-16756
12/03/2025, 8:10 AMtall-airline-16756
12/03/2025, 8:11 AM# load metadata during agent startup and add to initial chat context
metadata = json.loads(ctx.job.metadata)
initial_ctx = ChatContext()
initial_ctx.add_message(role="assistant", content=f"The user's name is {metadata['user_name']}.")
await session.start(room=ctx.room, agent=Assistant(chat_ctx=initial_ctx))
• Dynamic RAG (during conversation)
◦ Use when you need to fetch relevant documents at runtime based on user input.
◦ Example pattern:
async def on_user_turn_completed(self, turn_ctx: ChatContext, new_message: ChatMessage) -> None:
rag_content = await my_rag_lookup(new_message.text_content())
turn_ctx.add_message(role="assistant", content=f"Retrieved info: {rag_content}")
Recommendation:
• Put static or per-session data in initialization to avoid repeated network calls and improve performance.
• Use RAG for query-specific lookups to keep responses up-to-date and context-aware.
If you’d like, I can share a full runnable example repo snippet (LlamaIndex or the LiveKit RAG example) or tailor a sample to your metadata format or RAG provider. Which would you prefer?
Sources: External data and RAG | LiveKit Docsmost-dawn-67700
12/03/2025, 9:44 AMtall-airline-16756
12/03/2025, 9:44 AMon_user_turn_completed and decide whether to call your RAG lookup based on the message content, metadata, turn count, or custom flags.
◦ Example pattern:
async def on_user_turn_completed(self, turn_ctx: ChatContext, new_message: ChatMessage) -> None:
turn_number = turn_ctx.turn_index # or your own counter
if turn_number == 2 or "lookup docs" in new_message.text_content().lower():
rag_content = await my_rag_lookup(new_message.text_content())
turn_ctx.add_message(role="assistant", content=f"RAG: {rag_content}")
• Use system or assistant prompt instructions (possible, less reliable)
◦ Add instructions to the system prompt telling the model when to ask for external info (e.g., “If the user asks for X or on the 3rd turn, request a RAG lookup.”). This relies on the LLM following the prompt and can be unpredictable.
◦ Combine prompt guidance with a token/marker the model emits when it wants a lookup; your code watches for that marker and then performs the RAG call.
• Hybrid approach (best of both)
◦ Put high-level rules in the system prompt (when to prefer RAG) and enforce them deterministically in on_user_turn_completed by checking turn index, message intent, or a model-emitted marker.
Questions to help me give a tailored snippet:
• Do you track turn numbers in your ChatContext (e.g., turn_index) or do you want to base triggers on keywords/intent?
• Do you want the model to request RAG (model-driven) or do you want your application logic to decide (app-driven)?
Tell me which approach you prefer and I’ll provide a focused runnable example.most-dawn-67700
12/03/2025, 9:47 AMtall-airline-16756
12/03/2025, 9:47 AMon_user_turn_completed, checks keywords, and runs a RAG lookup only when a keyword matches.
1) Keyword-driven RAG handler (concise runnable pattern)
KEYWORDS = {"manual", "docs", "instructions", "how to", "details", "spec"}
class MyAgent(Agent):
async def on_user_turn_completed(self, turn_ctx: ChatContext, new_message: ChatMessage) -> None:
text = new_message.text_content().lower()
# simple keyword match
if any(k in text for k in KEYWORDS):
# optional: avoid repeated lookups for same turn/session
if not getattr(turn_ctx, "rag_done", False):
rag_content = await my_rag_lookup(text) # implement this to query your KB
# inject retrieved content before next assistant response
turn_ctx.add_message(role="assistant", content=f"Retrieved knowledge:\n{rag_content}")
turn_ctx.rag_done = True
# else: do nothing and let normal response generation proceed
2) Notes & best practices (short)
• Use lowercase keyword set and simple substring matches for speed; switch to intent classification if you need fewer false positives.
• Keep my_rag_lookup(text) async and fast (e.g., vector DB search + top-k retrieval + short summary).
• Mark turns or session state (like turn_ctx.rag_done) to prevent repeated RAG calls for the same question.
• If you need finer control, check turn_ctx.turn_index, message length, or metadata before querying.
• Insert retrieved content as an assistant message into the chat context so the LLM consumes it for the next reply.
If you want, I can:
• Provide a fuller runnable example (including a sample my_rag_lookup using LlamaIndex or a vector DB), or
• Show a variant that uses regex or simple intent model for keyword detection. Which would you prefer?most-dawn-67700
12/03/2025, 9:50 AMtall-airline-16756
12/03/2025, 9:50 AM# preload static/session context at startup
initial_ctx = ChatContext()
initial_ctx.add_message(role="system", content="Keep these facts available: product_v1 features A,B,C; support_hours: 9–5.")
initial_ctx.add_message(role="assistant", content="ContextPreload: product_v1 features A,B,C; support_hours: 9–5.")
session = AgentSession(...)
await session.start(room=ctx.room, agent=Assistant(chat_ctx=initial_ctx))
# also proactively inject dynamic context (e.g., from an external signal) before assistant replies
class MyAgent(Agent):
async def on_before_assistant_response(self, turn_ctx: ChatContext) -> None:
# decide if context should be injected now (not based on user turn)
if should_inject_context(): # your custom condition or external trigger
dynamic_ctx = await fetch_relevant_context() # e.g., from KB/vector DB
turn_ctx.add_message(role="assistant", content=f"PreloadedContext: {dynamic_ctx}")
Key points:
• Add context as assistant/system messages so it’s consumed by the LLM for subsequent replies.
• Use initialization for static/session data and pre-fetch/inject for dynamic context you know must be present before certain keywords appear.
• Keep injected context concise (summaries or top-k results) to avoid context window bloat.
• If you want the agent to act only when it “would mention” a keyword, combine preloaded context with a lightweight keyword check in on_before_assistant_response and only inject detailed docs when a future assistant response is likely to reference that keyword.
If you’d like, I can provide a runnable example of fetch_relevant_context() using your preferred KB (LlamaIndex, vector DB, or simple document store). Which do you use?most-dawn-67700
12/03/2025, 11:45 AMdef __init__(self, chat_ctx=None, knowledge_base: str | None = None):
"""Initialize SalesAgent with system instructions and optional chat context for handoffs.
Args:
chat_ctx: Optional chat context for agent handoffs
knowledge_base: Optional knowledge base text (warranty/returns policies)
"""
super().__init__(
instructions=SYSTEM_MESSAGE,
chat_ctx=chat_ctx
)
self.knowledge_base = knowledge_base
self._kb_injected_this_turn = False
async def on_before_assistant_response(self, turn_ctx: ChatContext) -> None:
"""Hook called before assistant generates a response.
Injects knowledge base context when warranty/returns topics are detected.
"""
# Reset injection flag for new turn
self._kb_injected_this_turn = False
# Only inject if we have a knowledge base
if not self.knowledge_base:
return
# Get the last user message
messages = turn_ctx.messages
if not messages:
return
# Find the most recent user message
last_user_message = None
for msg in reversed(messages):
if msg.role == "user":
last_user_message = msg
break
if not last_user_message:
return
# Check if message contains warranty/returns keywords
content_lower = last_user_message.content.lower()
warranty_keywords = ["warranty", "warrantee", "guarantee", "guaranteed"]
returns_keywords = ["return", "refund", "exchange", "policy", "policies"]
should_inject = any(keyword in content_lower for keyword in warranty_keywords + returns_keywords)
if should_inject:
logger.info("[CONTEXT_INJECTION] Detected warranty/returns topic, injecting knowledge base")
formatted_kb = format_knowledge_base_for_context(self.knowledge_base)
turn_ctx.add_message(role="assistant", content=formatted_kb)
self._kb_injected_this_turn = Truetall-airline-16756
12/03/2025, 11:45 AM_kb_injected_this_turn = False into the start of a new turn detection (e.g., when turn_ctx.turn_index changes) rather than always resetting inside on_before_assistant_response. Otherwise multiple checks within the same turn could re-enable injection logic unexpectedly.
1. Prefer intent/keyword normalization
• Use a single keyword set and normalize once:
KEYWORDS = {"warranty","warrantee","guarantee","guaranteed","return","refund","exchange","policy","policies"}
content_lower = last_user_message.content.lower()
should_inject = any(k in content_lower for k in KEYWORDS)
1. Debounce repeated injections
• Your _kb_injected_this_turn is good; also consider a per-session flag (e.g., turn_ctx.kb_injected or self._kb_injected_for_session) if you want to avoid injecting again for the same issue later in the session.
1. Keep injected content short & labeled
• Use a concise summary and a clear marker so the model treats it as context, e.g.:
formatted_kb = "Preloaded_KB_SUMMARY: " + format_knowledge_base_for_context(self.knowledge_base)
1. Consider place & role of message
• Adding as an assistant message is fine. For system-level facts you want always available, prefer system on initialization; for contextual assistance just before generation, assistant messages are appropriate.
1. Error handling & async
• If format_knowledge_base_for_context can be async or may fail, guard with try/except so you don't block response generation.
1. Example small tweak showing turn-index check
turn_index = getattr(turn_ctx, "turn_index", None)
if turn_index is not None and getattr(self, "_last_turn_index", None) != turn_index:
self._kb_injected_this_turn = False
self._last_turn_index = turn_index
If you want, I can:
• Return a single integrated snippet with the above changes applied, or
• Show a variant that injects only summaries (top-k) from a vector DB. Which would you like?most-dawn-67700
12/03/2025, 11:47 AMtall-airline-16756
12/03/2025, 11:47 AMmy_logger, format_knowledge_base_for_context, and my_rag_lookup as needed.
KEYWORDS = {
"warranty", "warrantee", "guarantee", "guaranteed",
"return", "refund", "exchange", "policy", "policies"
}
class SalesAgent(Agent):
def __init__(self, chat_ctx=None, knowledge_base: str | None = None):
super().__init__(instructions=SYSTEM_MESSAGE, chat_ctx=chat_ctx)
self.knowledge_base = knowledge_base
self._last_turn_index = None
self._kb_injected_this_turn = False
self._kb_injected_for_session = False # optional: avoid repeating across session
async def _format_kb(self, kb_text: str) -> str:
# Support sync or async formatting helper
try:
result = format_knowledge_base_for_context(kb_text)
if asyncio.iscoroutine(result):
result = await result
return result
except Exception as e:
my_logger.exception("KB formatting failed")
return "" # fail gracefully
async def on_before_assistant_response(self, turn_ctx: ChatContext) -> None:
# Determine current turn index and reset per-turn flag only when a new turn starts
turn_index = getattr(turn_ctx, "turn_index", None)
if turn_index is not None and turn_index != self._last_turn_index:
self._kb_injected_this_turn = False
self._last_turn_index = turn_index
# If KB absent or already injected for this turn or session, skip
if not self.knowledge_base or self._kb_injected_this_turn or self._kb_injected_for_session:
return
# Locate the most recent user message
messages = getattr(turn_ctx, "messages", []) or []
last_user_message = None
for msg in reversed(messages):
if getattr(msg, "role", "") == "user":
last_user_message = msg
break
if not last_user_message:
return
# Keyword detection
content = getattr(last_user_message, "content", "")
content_lower = content.lower()
if not any(k in content_lower for k in KEYWORDS):
return
# Inject KB (with labeling and length guard)
my_logger.info("[CONTEXT_INJECTION] Detected warranty/returns topic, injecting knowledge base")
formatted_kb = await self._format_kb(self.knowledge_base)
if not formatted_kb:
return
# Keep injection concise to avoid context bloat
MAX_INJECTION_LEN = 2000
summary = formatted_kb if len(formatted_kb) <= MAX_INJECTION_LEN else formatted_kb[:MAX_INJECTION_LEN] + "…"
injection = "Preloaded_KB_SUMMARY: " + summary
try:
turn_ctx.add_message(role="assistant", content=injection)
self._kb_injected_this_turn = True
# Optional: mark injected for session to avoid repeated injections later
# self._kb_injected_for_session = True
except Exception:
my_logger.exception("Failed to inject KB into turn_ctx")
If you want the snippet to:
• automatically summarize top-k documents from a vector DB before injection, I can add a fetch_and_summarize_kb() helper; or
• enable the session-level debounce (_kb_injected_for_session) by default, I can toggle that. Which would you like?most-dawn-67700
12/03/2025, 12:03 PMtall-airline-16756
12/03/2025, 12:04 PMinstructions or chat_ctx at construction).
• Hand off augmented context when you want the sub-agent to inherit full conversation history and any prior RAG injections from the main agent.
• Use initialization for deterministic behavior and faster sub-agent responses; use context handoff to preserve continuity and prior turns.
Two concise patterns
1) Initialize sub-agent with KB content (direct)
kb_result = await search_knowledge_base("product specs")
instructions = f"You are a specialist. Key info: {kb_result}"
return SpecialistAgent(instructions=instructions)
2) Handoff with inherited chat context (preserve history + KB injections)
# main agent has injected KB into its chat_ctx earlier
return SpecialistAgent(chat_ctx=self.session.chat_ctx)
Best practices
• Keep injected KB concise (summaries, top-k) to avoid context-window bloat.
• Label injected content (e.g., Preloaded_KB_SUMMARY:) so the model treats it as context.
• If KB needs updates at runtime, prefer doing RAG in on_user_turn_completed and then either inject before handing off or include results in the sub-agent initialization.
• For deterministic routing, perform KB retrieval in application code and pass explicit content to the sub-agent rather than relying solely on prompt instructions.
If you want, I can provide a ready-to-run example that:
• queries a vector DB and initializes a sub-agent with the top-k summary, or
• demonstrates handing off a chat context that already contains RAG-injected messages. Which would you like? Sources: External data and RAG | LiveKit Docs | Tool definition and use | LiveKit docs | Agents and handoffs | LiveKit docsmost-dawn-67700
12/04/2025, 1:19 AMtall-airline-16756
12/04/2025, 1:20 AMsearch_knowledge_base or your my_rag_lookup function) show as spans with inputs, outputs and duration. This is the clearest indicator a KB lookup ran.
• Transcript view: If you inject KB results into the chat (e.g., turn_ctx.add_message(role="assistant", content="KB: ...")), the assistant message appears in the transcript and is included in the next LLM input.
• Logs view: Any logger calls you add around your KB retrieval (e.g., logger.info("RAG lookup for ...")) appear timestamped and correlated with the trace.
• Timeline sync: Trace, transcript, and logs are time-aligned so you can jump from a tool call span to the corresponding transcript and logs.
Requirements to ensure visibility:
1. Enable Agent observability in Project settings → Data and privacy.
2. Use SDK versions that emit traces (Python v1.3+ or Node v1.0.18+).
3. Start the session with record=True (or rely on the default if project-level observability is on).
4. Implement KB retrieval as a function/tool or add explicit logs to make the lookup visible.
Best practices:
• Wrap KB retrieval in a function/tool so it shows as a labeled span in the trace.
• Keep injected KB concise and labeled (e.g., Preloaded_KB_SUMMARY:) so it’s easy to spot in the transcript.
• Log key steps (queries, results, document IDs) to the Logs view for easier debugging.
If you want, I can:
• provide a minimal agent snippet that demonstrates a traced tool-call + transcript injection + logging, or
• point to the Agent Insights docs and an example repo for RAG tool calls. Which would you prefer? Sources: https://blog.livekit.io/streamline-troubleshooting-with-agent-observability/#/portal/signup| | Agent insights in LiveKit Cloud | LiveKit docs | External data and RAG | LiveKit Docs | Tool definition and use | LiveKit docs