hi there need help with chaining agents, I am run...
# ask-ai
c
hi there need help with chaining agents, I am running a livekit voice agent but need to add a intent recognition layer, i.e everytime a query comein, it will recognise intent and allow tools accordingly, How to do it? Here is my current code:
Copy code
async def entrypoint(ctx: agents.JobContext):
    """Entry point for the agent."""

    # Configure the voice pipeline with the essentials
    session = AgentSession(
        stt=deepgram.STT(model="nova-2"),
        llm=openai.LLM(model=os.getenv("LLM_CHOICE", "gpt-4.1-mini")),
        tts=openai.TTS(voice="echo"),
        vad=silero.VAD.load(),
        
    )


    # Start the session
    await session.start(
        room=ctx.room,
        agent=Assistant()
    )


    # Generate initial greeting
    await session.generate_reply(
        instructions="Greet the user warmly and ask how you can help.",
        allow_interruptions=True,
    )
t
Thanks for reaching out, Tamojit. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're on the right track — you can add an intent-recognition step by creating a small intent-classifier tool that runs on each incoming user message and calls
context.agent.update_tools()
to enable only the tools relevant to the detected intent. Below is a minimal, practical pattern you can drop into your existing code and adapt. 1) Add an Assistant that starts with only the intent tool and defines per-intent tool sets:
Copy code
from livekit import agents
from livekit.agents import function_tool

class Assistant(agents.Agent):
    def __init__(self):
        super().__init__(
            instructions="First determine the user's intent, then enable only the tools needed for that intent.",
            tools=[self.recognize_intent]  # start with intent-recognition only
        )

    @function_tool()
    async def recognize_intent(self, user_input: str, context: agents.RunContext) -> str:
        # simple intent mapping (replace with LLM call or classifier)
        lowered = user_input.lower()
        if any(w in lowered for w in ["book", "schedule", "appointment", "calendar"]):
            detected = "scheduling"
        elif any(w in lowered for w in ["error", "issue", "bug", "help", "support"]):
            detected = "support"
        elif any(w in lowered for w in ["price", "cost", "demo", "purchase", "quote"]):
            detected = "sales"
        else:
            detected = "unknown"

        intent_tools = {
            "scheduling": [self.check_availability, self.book_appointment],
            "support": [self.lookup_ticket, self.escalate_issue],
            "sales": [self.check_pricing, self.schedule_demo],
            "unknown": [self.ask_clarify]
        }

        # enable only relevant tools for this intent
        await context.agent.update_tools(intent_tools[detected])

        return f"Intent detected: {detected}. Tools switched accordingly."

    # Example tools — implement your real logic here
    @function_tool()
    async def check_availability(self, date: str, context: agents.RunContext):
        return "Available at 2 PM."

    @function_tool()
    async def book_appointment(self, date: str, time: str, context: agents.RunContext):
        return "Appointment booked."

    @function_tool()
    async def lookup_ticket(self, ticket_id: str, context: agents.RunContext):
        return "Ticket status: open."

    @function_tool()
    async def escalate_issue(self, context: agents.RunContext):
        return "Issue escalated."

    @function_tool()
    async def check_pricing(self, product: str, context: agents.RunContext):
        return "$99/month."

    @function_tool()
    async def schedule_demo(self, context: agents.RunContext):
        return "Demo scheduled."

    @function_tool()
    async def ask_clarify(self, context: agents.RunContext):
        return "Could you clarify what you'd like help with?"
2) Update your entrypoint to instantiate and pass the Assistant to the session:
Copy code
assistant_agent = Assistant()

await session.start(
    room=ctx.room,
    agent=assistant_agent
)
3) Where to improve: • Replace the simple keyword classifier with an LLM prompt or an external intent-recognition model if you need higher accuracy. • Keep the intent tool as the first step in the conversation flow so no other tools run before intent is known. • If you expect multi-intent queries, detect multiple intents and enable the union of their tools. • Consider re-running intent detection periodically (e.g., after a user clarification) and calling
update_tools()
again. Would you like an example that uses an LLM prompt for intent classification instead of the keyword approach? Sources: Tool definition and use | LiveKit docs | Agents and handoffs | LiveKit docs
c
Looks good just make the intent_recogniser real like it is using the llm to recognise the intent
t
You're right — let's make the intent recognizer call the agent's LLM to classify intent and return structured JSON. Below is a drop-in
Assistant
implementation that uses the agent's LLM via
context.session.llm
inside a
@function_tool
to classify intent, then calls
context.agent.update_tools()
to enable the appropriate tools.
Copy code
from livekit import agents
from livekit.agents import function_tool
import json

class Assistant(agents.Agent):
    def __init__(self):
        super().__init__(
            instructions="Determine user intent with the LLM, then enable only the tools needed for that intent.",
            tools=[self.recognize_intent]  # start with intent recognition only
        )

    @function_tool()
    async def recognize_intent(self, user_input: str, context: agents.RunContext) -> str:
        """
        Use the integrated LLM to classify intent and enable matching tools.
        Returns a short confirmation string for the conversation.
        """
        possible_intents = ["scheduling", "support", "sales", "unknown"]

        prompt = f"""
You are an intent classification assistant. Choose one intent from this list: {', '.join(possible_intents)}.
Return a single JSON object with keys:
- "intent": one of the intent keywords
- "confidence": a float between 0 and 1
- "explanation": one short sentence why

User message:
\"\"\"{user_input}\"\"\"

Respond ONLY with valid JSON.
"""

        # Call the session LLM (this uses the agent session LLM)
        llm_resp = await context.session.llm.chat(prompt)

        # llm_resp may be a string or object depending on integration; handle string
        if isinstance(llm_resp, dict):
            llm_text = llm_resp.get("content", "")
        else:
            llm_text = str(llm_resp).strip()

        # Attempt to extract JSON from the LLM response
        try:
            parsed = json.loads(llm_text)
            intent = parsed.get("intent", "unknown")
        except json.JSONDecodeError:
            # Fallback: try to find the intent keyword in the text
            lower = llm_text.lower()
            intent = next((i for i in possible_intents if i in lower), "unknown")

        # Map intents to tool lists (replace with your real tool callables)
        intent_tools = {
            "scheduling": [self.check_availability, self.book_appointment],
            "support": [self.lookup_ticket, self.escalate_issue],
            "sales": [self.check_pricing, self.schedule_demo],
            "unknown": [self.ask_clarify]
        }

        tools_to_enable = intent_tools.get(intent, intent_tools["unknown"])

        # Update the agent's available tools for the conversation
        await context.agent.update_tools(tools_to_enable)

        return f"Intent detected: {intent}. Enabled relevant tools."

    # Example tools — implement your real logic here
    @function_tool()
    async def check_availability(self, date: str, context: agents.RunContext):
        return "Available at 2 PM."

    @function_tool()
    async def book_appointment(self, date: str, time: str, context: agents.RunContext):
        return "Appointment booked."

    @function_tool()
    async def lookup_ticket(self, ticket_id: str, context: agents.RunContext):
        return "Ticket status: open."

    @function_tool()
    async def escalate_issue(self, context: agents.RunContext):
        return "Issue escalated."

    @function_tool()
    async def check_pricing(self, product: str, context: agents.RunContext):
        return "$99/month."

    @function_tool()
    async def schedule_demo(self, context: agents.RunContext):
        return "Demo scheduled."

    @function_tool()
    async def ask_clarify(self, context: agents.RunContext):
        return "Could you clarify what you'd like help with?"
Notes and quick tips: • The prompt asks the LLM to return strict JSON; this makes parsing reliable. • If your LLM client returns structured objects rather than plain text, adjust how
llm_resp
is read. • Replace example tools with your production implementations. • You can add a confidence threshold: if confidence < 0.6, call
ask_clarify
instead of switching tools. Would you like this example adapted to use a specific LLM prompt style (few-shot examples) or to return multiple detected intents? Sources: Tool definition and use | LiveKit docs | Agents and handoffs | LiveKit docs | External data and RAG | LiveKit Docs
c
llm_resp = await context.session.llm.chat(prompt) Is this really asynchronus?
t
Good question — yes, the LLM call is asynchronous, but it uses a streaming pattern. •
await context.session.llm.chat(prompt)
starts the chat and gives you an async stream (an async iterator / async context manager), not a finished string. • You should consume it with
async with
and
async for
to read chunks as they arrive. Minimal example:
Copy code
async with context.session.llm.chat(chat_ctx=prompt) as stream:
    collected = ""
    async for chunk in stream:
        if chunk.delta and chunk.delta.content:
            collected += chunk.delta.content
# `collected` now holds the full generated text
Use this pattern inside your
@function_tool()
intent recognizer to get the LLM's JSON response reliably. Would you like a ready-to-drop example that parses JSON from the streamed chunks? Sources: Large language models (LLM) | LiveKit Docs | Agents v0.x migration guide - Node.js | LiveKit Docs
c
await context.agent.update_tools(tools_to_enable) Is this code valid?
t
Yes — that call is valid and correct. •
update_tools()
is asynchronous, so you must await it:
await context.agent.update_tools(tools_to_enable)
• It replaces the agent's current toolset with the list you pass. If you want to add or remove tools without replacing all, compose the new list (e.g.,
await context.agent.update_tools(agent.tools + [new_tool])
). Use this inside your intent-recognizer tool after you determine intent (LLM or classifier) to enable only the tools relevant to that intent. Sources: Tool definition and use | LiveKit docs
c
"customer_support" intent I think we should create another Agent called "RAGAgent" or similar
t
Good idea — creating a dedicated RAGAgent for the "customer_support" intent is a clean, maintainable pattern. Below is a concise plan and a minimal code sketch showing how to detect the "customer_support" intent with your LLM intent recognizer, then hand off to a RAGAgent that exposes RAG-specific tools (retriever, doc search, answer synthesis). Architecture (high level) • Keep one IntentAgent (your current Assistant) whose job is classification only. • When intent == "customer_support", call
context.agent.update_tools()
to enable a small handoff tool (e.g.,
delegate_to_rag
) or directly instantiate/start the RAGAgent. • RAGAgent contains tools for retrieval, context assembly, and generating grounded answers (and can itself use the session LLM). • Optionally stream context or conversation history into the RAGAgent to preserve thread continuity. Minimal example sketch 1) Intent recognizer (calls LLM and delegates)
Copy code
@function_tool()
async def recognize_intent(self, user_input: str, context: agents.RunContext) -> str:
    intent = await classify_with_llm(user_input, context)  # use streaming pattern
    if intent == "customer_support":
        # Option A: enable a delegate tool that transfers control
        await context.agent.update_tools([self.delegate_to_rag])
        return "Routing you to customer support helper."
    else:
        # enable other tools per intent
        await context.agent.update_tools([...])
        return f"Intent {intent} handled here."
2) Delegate tool (invokes RAGAgent logic)
Copy code
@function_tool()
async def delegate_to_rag(self, user_input: str, context: agents.RunContext):
    # Option: instantiate a RAGAgent instance and call its run method
    rag = RAGAgent()
    # You can pass conversation history, user_input, and context.room if needed
    return await rag.handle_support_query(user_input, context)
3) RAGAgent (focused on retrieval + grounded LLM answers)
Copy code
class RAGAgent(agents.Agent):
    def __init__(self):
        super().__init__(instructions="Use retrieval to answer customer support queries.")
        # define tools like `search_kb`, `fetch_ticket`, `synthesize_answer`

    async def handle_support_query(self, user_input: str, context: agents.RunContext):
        # 1) run a retriever/search tool over your KB
        docs = await self.search_kb(user_input, context)
        # 2) compose prompt with docs + user_input and call session LLM (streamed)
        prompt = compose_prompt(user_input, docs)
        async with context.session.llm.chat(chat_ctx=prompt) as stream:
            collected = ""
            async for chunk in stream:
                if chunk.delta and chunk.delta.content:
                    collected += chunk.delta.content
        # 3) return synthesized answer (optionally call context.agent.update_tools back)
        return collected
Notes and tips • Use the LLM streaming pattern (
async with context.session.llm.chat(...)
) in both intent classification and RAG generation for responsiveness. • Keep the delegate tool minimal: hand off input + relevant history to RAGAgent to avoid duplicating state. • If you want the RAGAgent to run in parallel (isolate state), instantiate it separately; if you prefer a single agent process, use delegate tools that perform retrieval + synthesis inline. • Consider confidence thresholds: if the classifier is uncertain, ask a short clarifying question before delegating. • Ensure any sensitive PII is filtered before sending to retrievers/LLM. Would you like a ready-to-drop full code example that implements
classify_with_llm
,
delegate_to_rag
, and a simple RAGAgent using a local in-memory retriever?
c
like FastAPI has lifetime function do you have anything similar, So I that we can do the Dependency injection in that function once and it runs lifetime?
t
Yes — LiveKit provides a startup/lifecycle pattern you can use like FastAPI's lifetime functions. • Use a prewarm function (runs once per worker process) to initialize dependencies (models, DB clients, retrievers) and store them on
proc.userdata
. • Access those dependencies in your entrypoint via
ctx.proc.userdata
(per-process singletons) or
ctx.userdata
(per-job). • Register cleanup with
ctx.add_shutdown_callback()
for job-scoped resources. Minimal pattern:
Copy code
# server setup (runs once per process)
def prewarm(proc: agents.JobProcess):
    proc.userdata["vad"] = silero.VAD.load()
    proc.userdata["rag_pipeline"] = initialize_rag_pipeline()

server.setup_fnc = prewarm

# per-job entrypoint
@server.rtc_session()
async def entrypoint(ctx: agents.JobContext):
    vad = ctx.proc.userdata["vad"]
    rag = ctx.proc.userdata["rag_pipeline"]

    session = AgentSession(vad=vad, llm=..., tts=...)
    assistant = Assistant()
    await session.start(room=ctx.room, agent=assistant)

    async def cleanup():
        await rag.shutdown()  # if needed
    ctx.add_shutdown_callback(cleanup)
Would you like a full example that preloads a vector store + retriever in
prewarm
, injects them into a RAGAgent, and shows the intent-based handoff? Sources: Agent server options | LiveKit docs | Silero VAD plugin | LiveKit docs | Agents (Node.js) | livekit/livekit_composite | DeepWiki | Job lifecycle | LiveKit docs | Agents and handoffs | LiveKit docs
c
yes
t
Great — I’ll provide a ready-to-drop prototype that does the following: • Uses a
prewarm
function to load a vector store + retriever (one-time per process) into
proc.userdata
. • Shows an entrypoint that reuses those dependencies via
ctx.proc.userdata
. • Implements an Assistant with an LLM-based, streamed intent recognizer tool (
recognize_intent
) that consumes the LLM async stream and parses JSON. • On "customer_support" intent, delegates to a dedicated
RAGAgent
(hand-off) which uses the prewarmed retriever to fetch docs and synthesize a grounded answer via the same session LLM. • Demonstrates cleanup with
ctx.add_shutdown_callback()
. Drop-in prototype (adapt your imports, retriever, and LLM config):
Copy code
# prototype_livekit_rag_handoff.py
from livekit import agents
from livekit.agents import function_tool, AgentSession, JobContext, JobProcess
import asyncio
import json

# ---------------------
# Prewarm: load shared deps once per worker process
# ---------------------
def prewarm(proc: JobProcess):
    # Replace these with your real init code
    # e.g., initialize vector store, embeddings, retriever client
    proc.userdata["retriever"] = initialize_retriever()
    proc.userdata["vector_store"] = initialize_vector_store()
    # any other heavy clients
    proc.userdata["shared_config"] = {"rag_top_k": 4}

# Register prewarm with your server initialization
server = agents.AgentServer()
server.setup_fnc = prewarm

# ---------------------
# Helper: consume streamed LLM output and return text
# ---------------------
async def collect_streamed_llm_text(stream_ctx):
    collected = ""
    async for chunk in stream_ctx:
        # chunk.delta.content contains incremental text for typical chunk model
        if getattr(chunk, "delta", None) and getattr(chunk.delta, "content", None):
            collected += chunk.delta.content
    return collected

# ---------------------
# RAGAgent: handles customer_support queries using retriever + LLM
# ---------------------
class RAGAgent(agents.Agent):
    def __init__(self, chat_ctx=None):
        super().__init__(instructions="You are a customer support agent that answers using retrieved docs.",
                         chat_ctx=chat_ctx)

    @function_tool()
    async def search_kb(self, query: str, context: agents.RunContext) -> str:
        # Use injected retriever from proc.userdata
        retriever = context.proc.userdata["retriever"]
        docs = await retriever.get_top_documents(query, k=context.proc.userdata["shared_config"]["rag_top_k"])
        # Return a simple concatenation for demonstration — in prod, return structured docs
        return "\n\n".join(d.content for d in docs)

    @function_tool()
    async def synthesize_answer(self, user_query: str, context: agents.RunContext) -> str:
        # 1) retrieve
        kb_text = await self.search_kb(user_query, context)

        # 2) compose prompt for grounded answer
        prompt = f"""
You are a helpful support assistant. Use the provided knowledge base excerpts to answer the user's question.
Knowledge base:
{kb_text}

User question:
{user_query}

Respond in JSON: {{ "answer": "...", "source_summary": "..." }}
"""

        # 3) call session LLM as a stream and collect
        async with context.session.llm.chat(chat_ctx=prompt) as stream:
            llm_text = await collect_streamed_llm_text(stream)

        # 4) parse JSON (best-effort)
        try:
            parsed = json.loads(llm_text)
            return parsed.get("answer", llm_text)
        except json.JSONDecodeError:
            # fallback to raw text
            return llm_text

# ---------------------
# Assistant: intent classifier + delegator
# ---------------------
class Assistant(agents.Agent):
    def __init__(self):
        super().__init__(
            instructions="First classify intent using the LLM and enable only tools relevant to that intent.",
            tools=[self.recognize_intent]  # start minimal
        )

    @function_tool()
    async def recognize_intent(self, user_input: str, context: agents.RunContext) -> str:
        """
        Stream LLM to classify intent. LLM instructed to return strict JSON:
        { "intent": "...", "confidence": 0.0 }
        """
        possible_intents = ["scheduling", "support", "sales", "customer_support", "unknown"]

        prompt = f"""
You are an intent classifier. Choose one intent from: {', '.join(possible_intents)}.
Return ONLY a JSON object with keys:
- "intent": one of the intents
- "confidence": float between 0 and 1

User message:
\"\"\"{user_input}\"\"\"
"""
        async with context.session.llm.chat(chat_ctx=prompt) as stream:
            llm_text = await collect_streamed_llm_text(stream)

        # parse
        try:
            parsed = json.loads(llm_text)
            intent = parsed.get("intent", "unknown")
            confidence = float(parsed.get("confidence", 0.0))
        except Exception:
            # fallback: simple heuristic
            intent = "unknown"
            confidence = 0.0

        # If high-confidence customer_support, delegate to RAGAgent
        if intent == "customer_support" and confidence >= 0.5:
            # Option A: enable a handoff tool that will call RAGAgent logic
            await context.agent.update_tools([self.delegate_to_rag])
            return "Routing to customer support helper."

        # non-support intents: set appropriate tools (examples)
        intent_tools = {
            "scheduling": [self.check_availability, self.book_appointment],
            "sales": [self.check_pricing, self.schedule_demo],
            "unknown": [self.ask_clarify],
        }
        tools_to_enable = intent_tools.get(intent, intent_tools["unknown"])
        await context.agent.update_tools(tools_to_enable)
        return f"Intent detected: {intent} (confidence={confidence}). Tools updated."

    @function_tool()
    async def delegate_to_rag(self, user_input: str, context: agents.RunContext) -> str:
        # Create RAGAgent and run its synthesis tool directly, passing context
        rag = RAGAgent()
        # Optionally, pass conversation history or chat_ctx into RAGAgent constructor
        answer = await rag.synthesize_answer(user_input, context)
        return answer

    # Example non-RAG tools
    @function_tool()
    async def check_availability(self, date: str, context: agents.RunContext):
        return "Available at 2 PM."

    @function_tool()
    async def book_appointment(self, date: str, time: str, context: agents.RunContext):
        return "Appointment booked."

    @function_tool()
    async def check_pricing(self, product: str, context: agents.RunContext):
        return "$99/month."

    @function_tool()
    async def schedule_demo(self, context: agents.RunContext):
        return "Demo scheduled."

    @function_tool()
    async def ask_clarify(self, context: agents.RunContext):
        return "Could you clarify what you'd like help with?"

# ---------------------
# Entrypoint: reuse prewarmed dependencies, start session
# ---------------------
@server.rtc_session()
async def entrypoint(ctx: JobContext):
    # Access process-level dependencies
    retriever = ctx.proc.userdata["retriever"]
    vector_store = ctx.proc.userdata["vector_store"]

    # Build session (use your actual vendor LLM / STT / TTS plugins)
    session = AgentSession(
        stt=...,   # e.g., deepgram.STT(...)
        llm=...,   # e.g., openai.LLM(...)
        tts=...,   # e.g., openai.TTS(...)
        vad=...    # e.g., silero.VAD.load() or prewarmed
    )

    assistant = Assistant()

    await session.start(room=ctx.room, agent=assistant)

    # initial greeting
    await session.generate_reply(
        instructions="Greet the user warmly and ask how you can help.",
        allow_interruptions=True,
    )

    # Register cleanup if needed (per-job)
    async def cleanup():
        # e.g., close job-scoped resources
        pass

    ctx.add_shutdown_callback(cleanup)
Notes and next steps: • Replace
initialize_retriever()
/
initialize_vector_store()
and LLM/STT/TTS placeholder args with your real initialization code. • The intent classifier uses the streaming LLM pattern and parses JSON. Use a few-shot prompt if you need higher accuracy. • The
delegate_to_rag
tool simply calls the RAGAgent's
synthesize_answer
method. Alternatively, you can instantiate RAGAgent with chat context and call session methods to preserve conversation threading. • Add a confidence threshold and clarifying-turn fallback to avoid mistaken handoffs. • For production, add error handling, timeouts, and rate limiting around LLM and retriever calls. Would you like this adapted into a concrete example wired to your LLM/STT/TTS plugins (I can fill placeholders for
openai.LLM
,
deepgram.STT
, etc.)? Sources: Pipeline nodes and hooks | LiveKit docs | Observability data hooks | LiveKit docs | Tool definition and use | LiveKit docs | Agent server | LiveKit docs
c
Gives tool duplication error for "recognize_intent"
t
Thanks — that error usually means the same tool function is being registered more than once (either by including
recognize_intent
in the agent's initial
tools
list and again when calling
update_tools
, or by passing the same callable multiple times). Quick checks and fixes: 1. Ensure
recognize_intent
is only registered once • Start the Agent with only the recognizer OR with only downstream tools — not both. Example: start with only the recognizer:
Copy code
super().__init__(instructions=..., tools=[self.recognize_intent])
Then after classification, call
await context.agent.update_tools([...])
with only the new tools (do NOT include
self.recognize_intent
there). 1. If you want the recognizer to remain available, include it once when updating tools • Compose the new list explicitly to avoid duplicates:
Copy code
new_tools = [self.recognize_intent] + intent_tools[detected_intent]
  await context.agent.update_tools(new_tools)
1. Avoid adding the same callable object twice • Don’t do
await context.agent.update_tools(agent.tools + [self.recognize_intent])
if
agent.tools
already contains it; dedupe first:
Copy code
current = list(dict.fromkeys(agent.tools + [self.recognize_intent]))
  await context.agent.update_tools(current)
1. If you instantiate a new Agent (handoff), register tools only on that new instance • When creating
RAGAgent()
for handoff, ensure its tools are defined on
RAGAgent
and you call
update_agent()
or otherwise replace the agent rather than merging tool lists. If you want, paste the exact traceback or the small snippet where you call
update_tools
and define
tools
and I’ll point out the duplicate and give the minimal fix.
c
Stupid, update tools is called only when intent_recogniser executed not in the initial run,
t
No worries — that happens. You're right: since
update_tools()
only runs when
recognize_intent
executes, ensure the recognizer isn't added twice. Quick checklist to avoid duplication: • Start the agent with only the recognizer (or omit it initially) — do NOT include
recognize_intent
both in the initial
tools
list and again in the list you pass to
update_tools()
. • If you want the recognizer to persist after intent detection, include it once when updating tools:
Copy code
new_tools = [self.recognize_intent] + intent_tools[detected_intent]
  await context.agent.update_tools(new_tools)
• If you build the new list by merging, dedupe first:
Copy code
combined = agent.tools + intent_tools[detected_intent]
  deduped = list(dict.fromkeys(combined))
  await context.agent.update_tools(deduped)
If you paste the small snippet where you define
tools
and call
update_tools
, I’ll point out the exact line to change. Sources: Tool definition and use | LiveKit docs | Agents and handoffs | LiveKit docs | Agent server | LiveKit docs
c
See this and understand that function_tool and tools in init is creating problem
t
You're correct — the conflict comes from using
@function_tool
on a method and also listing that same bound method in
tools=
. Quick, concrete fixes: 1) Remove duplicate self and other Python errors • init should be:
def __init__(self, intent_recogniser: IntentRecognizer, rag_engine: RAGApp):
• Instance methods must include `self`:
def respond(self, payload: dict) -> str:
2) Do NOT register the same method twice • If you decorate a method with
@function_tool()
, do not include
self.recognize_intent
in
tools=[...]
in
super().__init__()
.
@function_tool
auto-registers the tool. • Start the agent minimal (only the recognizer) by either: ◦ Decorating the method and omitting
tools=
entirely, or ◦ Using
tools=[external_tool]
only for functions defined outside the class. 3) If you need the recognizer to remain available after updating tools, include it once when you call `update_tools()`:
Copy code
new_tools = [self.recognize_intent] + intent_tools[detected_intent]
await context.agent.update_tools(new_tools)
4) If you want the recognizer only at first, start with it alone and replace tools after intent detection:
Copy code
super().__init__(instructions="...", )  # no tools list
# recognize_intent is available because of @function_tool()
# later inside recognize_intent:
await context.agent.update_tools(intent_tools[detected_intent])
Minimal corrected pattern:
Copy code
class Assistant(Agent):
    def __init__(self, intent_recogniser: IntentRecognizer, rag_engine: RAGApp):
        self.__intent_recogniser = intent_recogniser
        self.__rag_engine = rag_engine
        super().__init__(instructions="Determine intent, then enable relevant tools.")

    @function_tool()
    async def recognize_intent(self, user_input: str, context: agents.RunContext) -> dict:
        # use LLM/classifier, then:
        await context.agent.update_tools([self.delegate_to_rag])  # or appropriate tools
        return {"intent": "customer_support"}

    @function_tool()
    async def delegate_to_rag(self, user_input: str, context: agents.RunContext) -> str:
        rag = RAGAgent()
        return await rag.synthesize_answer(user_input, context)

    def respond(self, payload: dict) -> str:
        return json.dumps(payload)
If you paste your current init + recognize_intent snippet, I’ll point out the exact line to change. Sources: Tool definition and use | LiveKit docs | Agents v0.x migration guide - Python | LiveKit docs | Agent session | LiveKit docs
c
But by your provided code delegate_to_rag will be registered also when the Assistant class is initiated, so how is it helpfull Moreover it will create error while update_tools
t
You're right to flag that — if
delegate_to_rag
is decorated with
@function_tool()
it will be auto-registered at class init, which defeats the purpose of gating it until after intent detection and can cause duplication on
update_tools()
. Two safe patterns to avoid this: 1) Keep delegate tools as plain methods (not decorated), call them directly from the recognizer • Pros: no auto-registration, no update_tools duplication errors. • Use when you want to hand off control programmatically (instantiate RAGAgent or call its methods). Example:
Copy code
class Assistant(Agent):
    def __init__(self, ...):
        super().__init__(instructions="...")  # no tools list

    @function_tool()
    async def recognize_intent(self, user_input: str, context: RunContext):
        intent = await classify_with_llm(user_input, context)
        if intent == "customer_support":
            await context.agent.update_tools([])  # optionally remove tools
            return await self._delegate_to_rag(user_input, context)
        # else enable other tools via update_tools(...)
        await context.agent.update_tools([self.check_availability])
        return "OK"

    # plain method, NOT a @function_tool
    async def _delegate_to_rag(self, user_input: str, context: RunContext):
        rag = RAGAgent()
        return await rag.synthesize_answer(user_input, context)
2) Make delegate tools external (defined outside the class) and only add them to the agent via update_tools when needed • Pros: tools are true `function_tool`s but only registered when explicitly passed to
update_tools
. • Implement the delegate as a top-level
@function_tool()
and pass the callable into
update_tools()
after intent detection. Example:
Copy code
@function_tool()
async def delegate_to_rag_tool(user_input: str, context: RunContext):
    rag = RAGAgent()
    return await rag.synthesize_answer(user_input, context)

# inside recognize_intent:
if intent == "customer_support":
    await context.agent.update_tools([delegate_to_rag_tool])
Which approach fits you better? • If you want the delegate to be callable by the LLM as a tool, use option 2. • If you want a pure programmatic handoff (no LLM tool call), use option 1. Tell me which you prefer and I’ll give the exact drop-in code for your setup.
c
llm_resp = await self.llm.chat(chat_ctx=chat_ctx) Can not use this LLMStream with Async
t
You're correct —
await self.llm.chat(...)
doesn't return a finished string; it returns a streaming object you must consume asynchronously. Use the async-context + async-for pattern to read chunks. Minimal async pattern:
Copy code
async with self.llm.chat(chat_ctx=chat_ctx) as stream:
    collected = ""
    async for chunk in stream:
        if getattr(chunk, "delta", None) and getattr(chunk.delta, "content", None):
            collected += chunk.delta.content
# collected now contains the full text
Helper to reuse:
Copy code
async def collect_stream(stream):
    out = ""
    async for chunk in stream:
        if getattr(chunk, "delta", None) and getattr(chunk.delta, "content", None):
            out += chunk.delta.content
    return out
Using this inside a
@function_tool()
intent recognizer:
Copy code
@function_tool()
async def recognize_intent(self, user_input: str, context: agents.RunContext) -> dict:
    prompt = "..."  # ask LLM to return JSON with intent
    async with context.session.llm.chat(chat_ctx=prompt) as stream:
        llm_text = await collect_stream(stream)
    parsed = json.loads(llm_text)  # handle JSON errors
    # then update tools or delegate
    await context.agent.update_tools([...])
    return parsed
If your LLM client returns a different structure for chunks (not
chunk.delta.content
), tell me the chunk shape and I’ll adapt the helper.
c
await context.session.current_agent.update_tools(next_tools) This line adds the tools but we are not able to use it immediately, We needed to wait til next question, so that the agent is able to answer, How to tackle this?
t
You're right —
update_tools()
changes the agent's toolset, but the framework fixes the available tools at the start of the current LLM turn. New tools won't be callable by the LLM until the next turn. To use capabilities immediately, choose one of these patterns: • Direct invocation (recommended when deterministic): after updating, call the new function yourself and send its result as a reply.
Copy code
await context.session.current_agent.update_tools(next_tools)
  result = await some_new_tool_function(user_input, context)
  await context.session.generate_reply(instructions=f"Result: {result}")
• Agent handoff (recommended when you want the LLM to drive behavior with the new tools): replace the agent with a new agent that already includes the desired tools so the new agent can act immediately.
Copy code
await context.session.current_agent.update_agent(NewAgent(...))
  # NewAgent starts with its tools available on its first turn
• Trigger a follow-up turn (less ideal): after update, simulate a new user message or prompt the agent to run another turn so the LLM reevaluates tools. This can feel unnatural and risks loops. Which behavior do you want: (A) programmatic immediate execution, or (B) LLM-driven usage of the new tools? I’ll give a drop-in code example for your preferred pattern. Sources: Tool definition and use | LiveKit docs | Agents v0.x migration guide - Python | LiveKit docs
c
context.session.current_agent.update_agent no suck function called update_agent
t
You're right — there is no
update_agent()
on
context.session.current_agent
. Quick summary and exact patterns that work: 1) Agent handoff (recommended if you want the new agent to act immediately) • Return a new Agent instance from a
@function_tool()
call. The framework performs the handoff at end of the turn and the new agent's tools are available on its first turn. Example:
Copy code
@function_tool()
async def transfer_to_rag(self, user_input: str, context: RunContext):
    rag_agent = RAGAgent()
    return rag_agent, "Handing off to RAGAgent for support"
2) Immediate execution without waiting for next LLM turn • After
await context.agent.update_tools(next_tools)
, call the new tool function directly from your code instead of waiting for the LLM to call it. Example:
Copy code
await context.agent.update_tools(next_tools)
# call the callable directly (if it's a function_tool defined outside the class)
result = await some_new_tool(user_input, context)
await context.session.generate_reply(instructions=f"Result: {result}")
3) Create tools dynamically (if you need them to be LLM-callable later) • Define
@function_tool
at module level and add it with
update_tools()
when needed; or create dynamic tool callables and invoke them directly immediately after adding. 4) If you want the recognizer to remain available • Include it once when updating tools to avoid duplication:
Copy code
new_tools = [self.recognize_intent] + intent_tools[detected_intent]
await context.agent.update_tools(new_tools)
Why
update_agent()
doesn't exist • The SDK doesn't expose
update_agent()
on the session/agent object. Agent replacement is handled by returning a new Agent from a tool call (pattern #1).
update_tools()
changes toolset but those tools only become callable by the LLM in the next conversation turn. If you tell me which behavior you want (pure programmatic immediate execution, or LLM-driven usage via a new agent), I’ll give a ready-to-drop code snippet tailored to your current Agent/session code. Sources: Tool definition and use | LiveKit docs | Agent session | LiveKit docs
c
ok so how can we achieve this. First we do multi agent architecture via livekit OR should I use Langgraph
t
Good question — both are viable, but the right choice depends on priorities. Below is a concise comparison and a recommended path with concrete LiveKit patterns so you can make a decision quickly. Short comparison • LiveKit multi-agent (stay with LiveKit) ◦ Pros: native voice + realtime session handling, built-in Agent lifecycle, intent-driven handoff via tool returns, prewarm for dependency injection, single runtime for STT/TT S/LLM streaming. Best if your app is voice-first and you want tight control over realtime behavior. ◦ Cons: tool changes take effect next turn; immediate actions require programmatic calls or agent handoff patterns (covered below). • LangGraph ◦ Pros: designed for building complex LLM workflows/graphs, visual orchestration, easier to compose multi-agent pipelines and branching logic. ◦ Cons: another system to integrate with realtime voice layer; adds complexity for live audio/session handling unless you bridge it to LiveKit. Which to pick • Choose LiveKit if you want one runtime that handles voice, streaming LLMs, and agent handoffs with low integration overhead. • Consider LangGraph if your primary need is rich, reusable LLM workflow orchestration and you’re comfortable building a bridge between LangGraph and LiveKit for realtime audio. Practical LiveKit patterns to achieve your goals 1) Intent classification → immediate behavior • Use an LLM-based
@function_tool
intent recognizer (streamed), then either: ◦ Programmatically invoke the action/tool immediately (recommended when deterministic), or ◦ Return a new Agent instance from the tool to do a handoff so the new agent can run with its tools on its first turn. 2) Handoff pattern (LLM-driven tools available immediately) • From a tool, return (new_agent, "message") — the framework will replace the agent and the new agent gets its tools in its first response. Example:
Copy code
@function_tool()
  async def transfer_to_rag(self, user_input: str, context: RunContext):
      rag_agent = RAGAgent(...)   # RAGAgent defines its own @function_tool tools
      return rag_agent, "Handing off to RAG"
3) Immediate programmatic invocation (no wait) • After intent detection:
Copy code
await context.agent.update_tools(next_tools)   # tools will be available next turn
  # Do immediate work directly:
  result = await some_local_method_or_external_tool(user_input, context)
  await context.session.generate_reply(instructions=f"Result: {result}")
Use this when the flow is deterministic and you don't need the LLM to decide which tool to call right away. 4) Avoid tool-duplication • Do not decorate a method with
@function_tool()
and also list the same bound method in
tools=[...]
in
super().__init__
. • If you want a tool only available later, define it as: ◦ a plain instance method and call it programmatically, or ◦ a top-level
@function_tool()
and add that callable to
update_tools()
when needed. 5) Dependency injection / lifecycle • Use
prewarm(proc)
to load vector stores, retrievers, and heavy models into
proc.userdata
. • Access them in job with
ctx.proc.userdata
. • Use
ctx.add_shutdown_callback()
for cleanup. Suggested next step (practical) • If you want a drop-in LiveKit solution: I can provide a short working example that: ◦ prewarms a retriever, ◦ runs an LLM-based streamed intent recognizer, ◦ on "customer_support" either (A) programmatically calls the RAG synth function immediately, or (B) returns a RAGAgent to hand off (you pick), ◦ demonstrates no-duplication patterns for tools. Tell me which handoff mode you prefer (A = programmatic immediate execution, B = LLM-driven via agent handoff) and I’ll produce the exact code.