c
hi
t
Thanks for reaching out, Arun. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hi — thanks for reaching out. How can I help you today? If you’re not sure where to start, tell me: • What you’re trying to build or fix (app type, platform: web/iOS/Android) • Any error messages or unexpected behavior • Room ID, session ID, or SDK and version you’re using (if relevant) Share whatever you have and I’ll guide you next.
c
from dotenv import load_dotenv load_dotenv() import os, json, time, asyncio from datetime import datetime from uuid import uuid4 from typing import List from livekit.agents import Agent, JobContext, WorkerOptions, cli, function_tool from livekit.agents.voice import AgentSession from livekit.plugins import deepgram, groq, cartesia, silero class SupportAgent(Agent): def __init__(self, job_meta_str): super().__init__( instructions="You are a helpful support agent. Start by saying your name is Tom.", stt=deepgram.STT(), llm=groq.LLM(model="llama-3.1-8b-instant"), tts=cartesia.TTS(model="sonic-3", voice="e3087ad8-7018-4154-9a87-11577f916cd4"), vad=silero.VAD.load() ) self.job_meta_str = job_meta_str async def on_enter(self): print("on_enter", self.job_meta_str) await self.session.generate_reply(instructions="Greet the user and ask how you can help them.") @function_tool() async def get_free_slots(self, date: str = None) -> List[str]: return ["10:00 AM", "2:00 PM", "4:30 PM"] @function_tool() async def book_slot(self, date: str, slot: str) -> str: return f"Booked slot {slot} on {date}" @function_tool() async def cancel_slot(self, date: str, slot: str) -> str: return f"Cancelled slot {slot} on {date}" async def entrypoint(ctx: JobContext): job_meta_str = getattr(ctx.job, "metadata", None) agent = SupportAgent(job_meta_str) session = AgentSession() start_ts = time.time() @session.on("starting") def _on_start(): nonlocal start_ts start_ts = start_ts or time.time() async def _shutdown(): end_ts = time.time() duration = end_ts - start_ts transcript_id = uuid4() os.makedirs("transcripts", exist_ok=True) fname = os.path.join("transcripts", f"transcript_{transcript_id}_{datetime.utcnow():%Y%m%d_%H%M%S}.json") payload = { "session_id": i want funcianlity to discnnect this agent from agent side str(getattr(session, "id", "unknown_session")), "started_at": start_ts, "ended_at": end_ts, "duration_seconds": duration, "transcript": getattr(session, "history", {"items": []}).to_dict() if hasattr(session, "history") else {"items": []} } with open(fname, "w", encoding="utf-8") as f: json.dump(payload, f, indent=2) ctx.add_shutdown_callback(_shutdown) await session.start(agent=agent, room=ctx.room) def run(): cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint, agent_name="support", port=8081)) if name == "__main__": run()
t
You're asking how to let the agent disconnect itself from the session — I reviewed your snippet and can show the minimal changes to add that functionality. What I'll cover: • where to call the shutdown • example tool you can expose that ends the call gracefully (drain current speech) • immediate-close option 1) Where to call it • Call
await session.shutdown(drain=True)
to gracefully end the agent session and run your shutdown callbacks. • For an immediate disconnect use
await session.aclose()
. 2) Example — add an agent tool to end the call Add a
function_tool
on your agent that awaits current playout and then shuts down the session:
Copy code
@function_tool()
async def end_call(self):
    # wait for any current TTS playout to finish (optional)
    await self.session.wait_for_playout()
    # graceful shutdown: completes pending speech and triggers shutdown hooks
    await self.session.shutdown(drain=True)
3) Example — trigger shutdown from your entrypoint or external logic If you want to stop the session from your entrypoint code (e.g., after some condition):
Copy code
# somewhere in your async flow
await session.shutdown(drain=True)
# or immediate:
await session.aclose()
4) Session ID note (use in your transcript payload)
session.id
may not be present. Generate and store a session id when starting if you need one:
Copy code
session_id = str(uuid4())
# include session_id in payload instead of session.id
If you want, I can: • Show exactly where to insert
end_call
into your posted class (with correct indentation), or • Provide a version that immediately ends the session after a specific agent response. Which would you prefer? Sources: Job lifecycle | LiveKit docs
c
.14", "rtc-version": "1.0.17"} 2025-11-22 000703,829 - INFO livekit.agents - registered worker {"id": "AW_5yaGWUShtyy2", "url": "ws://localhost:7880", "region": "", "protocol": 16} 2025-11-22 000729,929 - INFO livekit.agents - received job request {"job_id": "AJ_e288wezwsfim", "dispatch_id": "AD_6KPkmufTksnV", "room_name": "8004a9ed-ffa9-4ad6-a58f-abf3e74174e1", "agent_name": "support", "resuming": false} 2025-11-22 000729,934 - INFO livekit.agents - initializing job runner {"tid": 7480} 2025-11-22 000729,935 - DEBUG asyncio - Using proactor: IocpProactor 2025-11-22 000729,936 - INFO livekit.agents - job runner initialized {"tid": 7480, "elapsed_time": 0.0} 2025-11-22 000730,310 - DEBUG livekit.agents - input stream attached {"participant": null, "source": "SOURCE_UNKNOWN", "accepted_sources": ["SOURCE_MICROPHONE"]} 2025-11-22 000730,314 - DEBUG livekit.agents - http_session(): creating a new httpclient ctx on_enter {"user": {"sub": "arun@dezyit.com", "id": 1, "client_id": 1, "exp": 1763751381}, "agent": {"agent_id": 13, "room_name": "8004a9ed-ffa9-4ad6-a58f-abf3e74174e1", "agent_name": "support"}} 2025-11-22 000730,618 - DEBUG livekit.agents - start reading stream {"participant": "79f2a96c-a6b2-4d8f-80e1-9bfc49002b04user", "source": "SOURCE_MICROPHONE"} 2025-11-22 000730,620 - DEBUG livekit.agents - using audio io:
RoomIO
->
AgentSession
->
TranscriptSynchronizer
->
RoomIO
2025-11-22 000730,621 - DEBUG livekit.agents - using transcript io:
AgentSession
->
TranscriptSynchronizer
->
RoomIO
2025-11-22 000730,630 - DEBUG livekit.agents - start reading stream {"participant": "79f2a96c-a6b2-4d8f-80e1-9bfc49002b04user", "source": "SOURCE_MICROPHONE"} 2025-11-22 000730,791 - WARNING livekit.agents - failed to generate LLM completion, retrying in 0.1s {"llm": "livekit.plugins.groq.services.LLM", "attempt": 1} Traceback (most recent call last): File "C:\Users\work\work\agents\.venv\Lib\site-packages\livekit\agents\llm\llm.py", line 190, in _main_task return await self._run() ^^^^^^^^^^^^^^^^^ File "C:\Users\work\work\agents\.venv\Lib\site-packages\livekit\agents\inference\llm.py", line 341, in _run raise APIStatusError( livekit.agents._exceptions.APIStatusError: Error code: 400 - {'error': {'message': "invalid JSON schema for tool end_call, tools[2].function.parameters: 'required' present but 'properties' is missing", 'type': 'invalid_request_error', 'param': 'tool end_call, tools[2].function.parameters'}} (status_code=400, request_id=req_01kakva2t9fdvv8zpqg7k031ke, body={'message': "invalid JSON schema for tool end_call, tools[2].function.parameters: 'required' present but 'properties' is missing", 'type': 'invalid_request_error', 'param': 'tool end_call, tools[2].function.parameters'}, retryable=True) 2025-11-22 000730,934 - WARNING livekit.agents - failed to generate LLM completion, retrying in 2.0s {"llm": "livekit.plugins.groq.services.LLM", "attempt": 2} Traceback (most recent call last): File "C:\Users\work\work\agents\.venv\Lib\site-packages\livekit\agents\llm\llm.py", line 190, in _main_task return await self._run() ^^^^^^^^^^^^^^^^^ File "C:\Users\work\work\agents\.venv\Lib\site-packages\livekit\agents\inference\llm.py", line 341, in _run raise APIStatusError( livekit.agents._exceptions.APIStatusError: Error code: 400 - {'error': {'message': "invalid JSON schema for tool end_call, tools[2].function.parameters: 'required' present but 'properties' is missing", 'type': 'invalid_request_error', 'param': 'tool end_call, tools[2].function.parameters'}} (status_code=400, request_id=req_01kakva2yzfdvrwv3w1yhm54t2, body={'message': "invalid JSON schema for tool end_call, tools[2].function.parameters: 'required' present but 'properties' is missing", 'type': 'invalid_request_error', 'param': 'tool end_call, tools[2].function.parameters'}, retryable=True) 2025-11-22 000732,985 - WARNING livekit.agents - failed to generate LLM completion, retrying in 2.0s {"llm": "livekit.plugins.groq.services.LLM", "attempt": 3} Traceback (most recent call last): File "C:\Users\work\work\agents\.venv\Lib\site-packages\livekit\agents\llm\llm.py", line 190, in _main_task return await self._run() ^^^^^^^^^^^^^^^^^ File "C:\Users\work\work\agents\.venv\Lib\site-packages\livekit\agents\inference\llm.py", line 341, in _run raise APIStatusError( livekit.agents._exceptions.APIStatusError: Error code: 400 - {'error': {'message': "invalid JSON schema for tool end_call, tools[2].function.parameters: 'required' present but 'properties' is missing", 'type': 'invalid_request_error', 'param': 'tool end_call, tools[2].function.parameters'}} (status_code=400, request_id=req_01kakva4ywe5rrtm1ravgs6keb, body={'message': "invalid JSON schema for tool end_call, tools[2].function.parameters: 'required' present but 'properties' is missing", 'type': 'invalid_request_error', 'param': 'tool end_call, tools[2].function.parameters'}, retryable=True) 2025-11-22 000735,025 - ERROR livekit.agents - Error in _llm_inference_task Traceback (most recent call last): File "C:\Users\work\work\agents\.venv\Lib\site-packages\livekit\agents\llm\llm.py", line 190, in _main_task return await self._run() ^^^^^^^^^^^^^^^^^ File "C:\Users\work\work\agents\.venv\Lib\site-packages\livekit\agents\inference\llm.py", line 341, in _run raise APIStatusError( livekit.agents._exceptions.APIStatusError: Error code: 400 - {'error': {'message': "invalid JSON schema for tool end_call, tools[2].function.parameters: 'required' present but 'properties' is missing", 'type': 'invalid_request_error', 'param': 'tool end_call, tools[2].function.parameters'}} (status_code=400, request_id=req_01kakva6yve5tvqavm3g71avr0, body={'message': "invalid JSON schema for tool end_call, tools[2].function.parameters: 'required' present but 'properties' is missing", 'type': 'invalid_request_error', 'param': 'tool end_call, tools[2].function.parameters'}, retryable=True) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\work\work\agents\.venv\Lib\site-packages\livekit\agents\utils\log.py", line 16, in async_fn_logs return await fn(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\work\work\agents\.venv\Lib\site-packages\opentelemetry\util\_decorator.py", line 71, in async_wrapper return await func(*args, **kwargs) # type: ignore ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\work\work\agents\.venv\Lib\site-packages\livekit\agents\voice\generation.py", line 125, in _llm_inference_task async for chunk in llm_node: File "C:\Users\work\work\agents\.venv\Lib\site-packages\livekit\agents\voice\agent.py", line 402, in llm_node async for chunk in stream: File "C:\Users\work\work\agents\.venv\Lib\site-packages\livekit\agents\llm\llm.py", line 344, in anext raise exc # noqa: B904 ^^^^^^^^^ File "C:\Users\work\work\agents\.venv\Lib\site-packages\opentelemetry\util\_decorator.py", line 71, in async_wrapper return await func(*args, **kwargs) # type: ignore ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\work\work\agents\.venv\Lib\site-packages\livekit\agents\llm\llm.py", line 202, in _main_task raise APIConnectionError( livekit.agents._exceptions.APIConnectionError: failed to generate LLM completion after 4 attempts (body=None, retryable=True)
t
Thanks — I reviewed your logs and the error. You're hitting this because the LLM provider rejects the generated function schema for `end_call`: it includes a
required
field but no
properties
object. I'll show a minimal, correct
end_call
you can drop into your posted agent that (1) has no parameter schema issues and (2) gracefully ends the session. Replace/add this inside your SupportAgent class:
Copy code
from livekit.agents import RunContext

@function_tool()
async def end_call(self, ctx: RunContext) -> None:
    """End the call gracefully from the agent side."""
    # Optionally say a goodbye
    await self.session.generate_reply(instructions="Goodbye! Ending the call now.")
    # Wait for TTS playout to finish
    await ctx.wait_for_playout()
    # Graceful agent shutdown (drains outstanding work)
    await self.session.shutdown(drain=True)
Key notes: • Using a single
ctx: RunContext
parameter avoids auto-generating a broken parameters schema (no `required`/`properties` mismatch). •
await self.session.shutdown(drain=True)
gracefully finishes TTS/playout and runs shutdown hooks (your transcript writer). • For immediate disconnect use
await self.session.aclose()
instead. • If you must supply a custom JSON schema, include
parameters.properties
(even if empty) when you have a
required
list. If you want, I can: • Paste this with correct indentation into your full class, or • Convert the tool to delete the room (to end the entire call for all participants) instead of
session.shutdown
. Which do you prefer? Sources: Agent speech and audio | LiveKit docs | Agents telephony integration | LiveKit Docs
c
anscriptSynchronizer` ->
RoomIO
2025-11-22 000907,634 - DEBUG livekit.agents - start reading stream {"participant": "100e71c5-5d06-400c-af9f-bc36907723c6user", "source": "SOURCE_MICROPHONE"} 2025-11-22 000907,781 - WARNING livekit.agents - failed to generate LLM completion, retrying in 0.1s {"llm": "livekit.plugins.groq.services.LLM", "attempt": 1} Traceback (most recent call last): File "C:\Users\work\work\agents\.venv\Lib\site-packages\livekit\agents\llm\llm.py", line 190, in _main_task return await self._run() ^^^^^^^^^^^^^^^^^ File "C:\Users\work\work\agents\.venv\Lib\site-packages\livekit\agents\inference\llm.py", line 341, in _run raise APIStatusError( livekit.agents._exceptions.APIStatusError: Error code: 400 - {'error': {'message': "invalid JSON schema for tool end_call, tools[2].function.parameters: 'required' present but 'properties' is missing", 'type': 'invalid_request_error', 'param': 'tool end_call, tools[2].function.parameters'}} (status_code=400, request_id=req_01kakvd1hdfeh8snn0z5pk55eb, body={'message': "invalid JSON schema for tool end_call, tools[2].function.parameters: 'required' present but 'properties' is missing", 'type': 'invalid_request_error', 'param': 'tool end_call, tools[2].function.parameters'}, retryable=True) 2025-11-22 000907,920 - WARNING livekit.agents - failed to generate LLM completion, retrying in 2.0s {"llm": "livekit.plugins.groq.services.LLM", "attempt": 2} Traceback (most recent call last): File "C:\Users\work\work\agents\.venv\Lib\site-packages\livekit\agents\llm\llm.py", line 190, in _main_task return await self._run() ^^^^^^^^^^^^^^^^^ File "C:\Users\work\work\agents\.venv\Lib\site-packages\livekit\agents\inference\llm.py", line 341, in _run raise APIStatusError( livekit.agents._exceptions.APIStatusError: Error code: 400 - {'error': {'message': "invalid JSON schema for tool end_call, tools[2].function.parameters: 'required' present but 'properties' is missing", 'type': 'invalid_request_error', 'param': 'tool end_call, tools[2].function.parameters'}} (status_code=400, request_id=req_01kakvd1nre6ma3yr8zs978afh, body={'message': "invalid JSON schema for tool end_call, tools[2].function.parameters: 'required' present but 'properties' is missing", 'type': 'invalid_request_error', 'param': 'tool end_call, tools[2].function.parameters'}, retryable=True) 2025-11-22 000909,970 - WARNING livekit.agents - failed to generate LLM completion, retrying in 2.0s {"llm": "livekit.plugins.groq.services.LLM", "attempt": 3} Traceback (most recent call last): File "C:\Users\work\work\agents\.venv\Lib\site-packages\livekit\agents\llm\llm.py", line 190, in _main_task return await self._run() ^^^^^^^^^^^^^^^^^ File "C:\Users\work\work\agents\.venv\Lib\site-packages\livekit\agents\inference\llm.py", line 341, in _run raise APIStatusError( livekit.agents._exceptions.APIStatusError: Error code: 400 - {'error': {'message': "invalid JSON schema for tool end_call, tools[2].function.parameters: 'required' present but 'properties' is missing", 'type': 'invalid_request_error', 'param': 'tool end_call, tools[2].function.parameters'}} (status_code=400, request_id=req_01kakvd3nvfehsqnd1de0c47pb, body={'message': "invalid JSON schema for tool end_call, tools[2].function.parameters: 'required' present but 'properties' is missing", 'type': 'invalid_request_error', 'param': 'tool end_call, tools[2].function.parameters'}, retryable=True)
t
Thanks — I see the repeated 400 errors complaining: "invalid JSON schema for tool end_call, tools[2].function.parameters: 'required' present but 'properties' is missing." That means the tool schema the LLM sees includes a
required
array without a matching
properties
object. What to do (minimal, safe fix): • Define the tool with a single `ctx`/`RunContext` parameter (no user args) so no invalid schema is generated. • Or if you supply a raw schema, ensure
parameters.properties
exists (even empty) whenever you include
required
. Drop this exact tool into your SupportAgent (correct indent and imports):
Copy code
from livekit.agents import RunContext

@function_tool()
async def end_call(self, ctx: RunContext) -> None:
    """End the call gracefully from the agent side."""
    await self.session.generate_reply(instructions="Goodbye — ending the call now.")
    await ctx.wait_for_playout()
    await self.session.shutdown(drain=True)  # graceful
If you prefer to end the entire room for all participants instead of just shutting down the agent, replace the shutdown with a room delete using the job context API:
Copy code
job_ctx = ctx.job_ctx
if job_ctx:
    await job_ctx.api.room.delete_room(api.DeleteRoomRequest(room=job_ctx.room.name))
If you previously tried a signature or manual schema like: • @function_tool(parameters={... "required": [...]}) without
properties
that caused the error. Either remove
required
or add
properties
per the examples above. Would you like me to: • paste the full fixed class with correct indentation, or • show a raw-schema example that is valid if you must supply one?
c
class SupportAgent(Agent): def __init__(self, job_meta_str): super().__init__( instructions="You are a helpful support agent. Start by saying your name is Tom.", stt=deepgram.STT(), llm=groq.LLM(model="llama-3.1-8b-instant"), tts=cartesia.TTS(model="sonic-3", voice="e3087ad8-7018-4154-9a87-11577f916cd4"), vad=silero.VAD.load() ) self.job_meta_str = job_meta_str async def on_enter(self): meta = json.loads(self.job_meta_str) agent_info = meta.get("agent", {}) print("Agent ID:", agent_info.get("id")) print("Agent Name:", agent_info.get("name")) print("Agent Role:", agent_info.get("role")) print("Agent Description:", agent_info.get("description")) print("Agent System Prompt:", agent_info.get("system_prompt")) await self.session.generate_reply(instructions="Greet the user and ask how you can help them.") setup instrueions stt tts llm on enter check livkeit docs
t
You're on the right track — below is a minimal, corrected version of your SupportAgent pattern and where to put STT/LLM/TTS/VAD so it matches LiveKit usage and avoids the function-tool schema error. What I'm addressing: • Parse job metadata in
on_enter
(as you showed) • Keep model plugins on the AgentSession (not in Agent.init) • Provide a safe
end_call
tool that won't generate an invalid JSON schema Paste these changes into your code (keep indentation consistent): 1) SupportAgent (agent-only concerns)
Copy code
from livekit.agents import Agent, function_tool, RunContext
import json

class SupportAgent(Agent):
    def __init__(self, job_meta_str):
        super().__init__(
            instructions="You are a helpful support agent. Start by saying your name is Tom.",
            tools=[ ]  # add tools like end_call_tool here if desired
        )
        self.job_meta_str = job_meta_str

    async def on_enter(self):
        try:
            meta = json.loads(self.job_meta_str)
            agent_info = meta.get("agent", {})
            print("Agent ID:", agent_info.get("id"))
            print("Agent Name:", agent_info.get("name"))
            print("Agent Role:", agent_info.get("role"))
            print("Agent Description:", agent_info.get("description"))
            print("Agent System Prompt:", agent_info.get("system_prompt"))
        except Exception as e:
            print("Failed to parse job metadata:", e)

        await self.session.generate_reply(instructions="Hi, I'm Tom. How can I help you today?")
2) Safe end_call tool (no bad schema)
Copy code
from livekit.agents import function_tool, RunContext

@function_tool()
async def end_call(self, ctx: RunContext) -> None:
    """End the call gracefully from the agent side."""
    await self.session.generate_reply(instructions="Goodbye — ending the call now.")
    await ctx.wait_for_playout()
    await self.session.shutdown(drain=True)  # graceful agent-side disconnect
3) Entry point / AgentSession (attach STT/LLM/TTS/VAD here)
Copy code
from livekit.agents import AgentSession, JobContext

async def entrypoint(ctx: JobContext):
    stt = deepgram.STT()
    llm = groq.LLM(model="llama-3.1-8b-instant")
    tts = cartesia.TTS(model="sonic-3", voice="e3087ad8-7018-4154-9a87-11577f916cd4")
    vad = silero.VAD.load()

    session = AgentSession(stt=stt, llm=llm, tts=tts, vad=vad)
    agent = SupportAgent(job_meta_str=getattr(ctx.job, "metadata", "{}"))
    await session.start(agent=agent, room=ctx.room)
Notes: • The LLM schema error originates from a tool definition that included
required
without
properties
. Using a single
ctx: RunContext
parameter (or a correctly structured raw schema) prevents that invalid schema. • Use
session.shutdown(drain=True)
to gracefully stop the agent; use
session.aclose()
for immediate disconnect. To end the entire room for everyone, call the room delete API from the job context instead. • Keep STT/LLM/TTS/VAD in AgentSession, not passed directly to Agent.init. If you'd like, I can: • Insert the
end_call
tool into your full class with proper imports and indentation, or • Provide a valid raw-schema example for
end_call
that requires a confirmation boolean. Which would you prefer? Sources: Tool definition and use | LiveKit docs | Agents and handoffs | LiveKit docs | Agent session | LiveKit docs | Job lifecycle | LiveKit docs | Voice AI quickstart | LiveKit docs