cool-salesmen-60705
12/10/2025, 5:43 PMtall-airline-16756
12/10/2025, 5:43 PMtall-airline-16756
12/10/2025, 5:44 PMself.complete() and self._on_completion() when building tasks. Good question — here's the short answer.
• Use self.complete(result) to mark a task as finished and return a result to the controlling agent. Call it once the task's objective is achieved (for example, after collecting input or finishing work).
• self._on_completion() is not part of the public API in the LiveKit Agents task docs. It isn't documented or shown in examples, so do not rely on it. If you need a post-completion callback, implement your own handler or perform follow-up actions immediately after calling self.complete() (or in the agent code that receives the task result).
Would you like an example of calling self.complete() inside an AgentTask implementation or guidance on where to handle post-completion logic?
Sources: Tasks and task groups | LiveKit docscool-salesmen-60705
12/10/2025, 5:55 PMtall-airline-16756
12/10/2025, 5:56 PMJobContext and RunContext are for. Short answer:
• JobContext
◦ Scope: job/room-level (created when a room or dispatch starts).
◦ Use it for job lifecycle and room interactions: access ctx.room, job metadata (ctx.job.metadata), connect to the room (ctx.connect()), wait for participants (ctx.waitForParticipant()), and shut down (ctx.shutdown()).
◦ Typical place to do setup, teardown, and any logic that applies to the whole job/session.
• RunContext
◦ Scope: per-session / per-tool-execution.
◦ Passed into @function_tool handlers; gives access to the current session (AgentSession), function_call, speech_handle, and userdata.
◦ Use it for session-specific logic, controlling the voice/speech pipeline, and maintaining type-safe session state across tool calls.
Would you like a short code example for either context (Job entrypoint or a @function_tool using RunContext)?
Sources: Job lifecycle | LiveKit docs | Agents (Node.js) | livekit/livekit_composite | DeepWiki | Tool definition and use | LiveKit docs | Agents and handoffs | LiveKit docscool-salesmen-60705
12/10/2025, 6:15 PMtall-airline-16756
12/10/2025, 6:15 PMcool-salesmen-60705
12/10/2025, 6:16 PMtall-airline-16756
12/10/2025, 6:16 PMTaskGroup inside an agent (Python-style):
class MyAgent(Agent):
async def run(self, ctx: JobContext):
# create TaskGroup inside the agent
tg = TaskGroup()
tg.add(lambda: GetEmailTask(), id="get_email")
tg.add(lambda: GetAddressTask(), id="get_address")
# await the TaskGroup — agent orchestrates execution and receives results
results = await tg
# results is a dict keyed by task id
email = results["get_email"]
address = results["get_address"]
# continue agent logic (e.g., respond or transition)
await self.respond(f"Got email {email} and address {address}")
If you'd like the same pattern in TypeScript or a version showing error handling/corrections inside tasks, tell me which one.cool-salesmen-60705
12/10/2025, 8:01 PMtall-airline-16756
12/10/2025, 8:02 PMself.complete(None) vs self.complete(result).
• Use self.complete(result) when the task produces data the agent or other tasks will consume. Return a typed, structured result (e.g., a dataclass or boolean) so downstream logic can act on it.
• Use self.complete(None) when the task only performs side effects (notifications, DB updates, etc.) and no value is needed downstream. It's valid but conveys "no useful result."
• Always declare a clear result type on your AgentTask (generics) to document expectations and improve type safety.
• Never omit calling self.complete(...) — the task must call it to finish.
Would you like a short code example showing typed results vs side-effect-only tasks?
Sources: Tasks and task groups | LiveKit docscool-salesmen-60705
12/10/2025, 8:06 PMtall-airline-16756
12/10/2025, 8:06 PMNone or omit the return when you want the tool to run silently (side effects only).
• Returning an agent instance (plus an optional message) can trigger an agent handoff.
Would you like a brief Python or TypeScript example for your case?
Sources: Tool definition and use | LiveKit docscool-salesmen-60705
12/10/2025, 8:08 PMtall-airline-16756
12/10/2025, 8:08 PMCommuteResults) and calls self.complete(results) to finish the task and return that structured data to the agent. That is the right pattern for tasks that produce data for downstream logic.
• The @function_tool decorator is allowed to return values to the LLM; function-tool returns are sent back as tool output. In your example the function doesn't return (it instead calls self.complete(...)), which is fine because the task is responsible for signaling completion and returning the task result.
• Summary guidance:
◦ Use self.complete(result) from inside a task when you want the task to return structured data.
◦ Use self.complete(None) for side-effect-only tasks.
◦ Function tools may return values (or None) when you want the LLM to see tool output; but when a function tool is part of a task's internal flow and the task owns the result, calling self.complete(...) inside the task is appropriate.
Would you like a small variant showing the same flow but with the function tool returning a value to the LLM instead of the task calling self.complete()?cool-salesmen-60705
12/10/2025, 10:36 PMtall-airline-16756
12/10/2025, 10:36 PMfrom typing import Dict, List
from dataclasses import dataclass
# Typed result for a single question
@dataclass
class QuestionResult:
question_id: str
answer: str
# Final survey results
@dataclass
class SurveyResults:
answers: Dict[str, str]
class AskQuestionTask(AgentTask[QuestionResult]):
def __init__(self, question_id: str, prompt: str) -> None:
super().__init__(instructions=prompt)
self.question_id = question_id
self.prompt = prompt
async def on_enter(self) -> None:
# Ask the question to the user (generates voice/LM reply)
await self.session.generate_reply(instructions=self.prompt)
async def on_user_message(self, message: str) -> None:
# Simple presence check — require non-empty answer
answer = message.strip()
if answer:
result = QuestionResult(question_id=self.question_id, answer=answer)
self.complete(result)
else:
# Re-prompt if no answer provided
await self.session.generate_reply(instructions="Please provide an answer to the question.")
class SurveyAgent(Agent):
def __init__(self, questions: List[dict]):
super().__init__()
self.questions = questions # list of {"id": "...", "prompt": "..."}
async def run(self, ctx: JobContext):
collected: Dict[str, str] = {}
for q in self.questions:
# Create and run a TaskGroup with a single AskQuestionTask so the agent
# can await the typed result and keep orchestration simple.
tg = TaskGroup()
tg.add(lambda: AskQuestionTask(q["id"], q["prompt"]), id=q["id"])
# Agent orchestrates the TaskGroup and receives results
results = await tg
# results is dict keyed by task id
qr: QuestionResult = results[q["id"]]
collected[qr.question_id] = qr.answer
# All questions answered, complete job (or respond)
survey_results = SurveyResults(answers=collected)
await self.respond(f"Survey complete. Collected {len(collected)} answers.")
# Optionally return results or hand off
return survey_results
Notes and customization ideas:
• Replace simple presence check in on_user_message with more advanced validation (choices, formats).
• If using function tools for input parsing, have the task call those tools and then self.complete(...) with parsed results.
• For multi-turn prompts or clarifications, keep re-prompting inside on_user_message until validation passes.
• If you prefer not to use TaskGroup for each question, you can instantiate and await a single task directly, but using TaskGroup keeps results structured.
Would you like a TypeScript variant or an example that enforces choices (e.g., multiple-choice answers)?cool-salesmen-60705
12/10/2025, 10:40 PMtall-airline-16756
12/10/2025, 10:40 PMself.complete(...).
◦ You want typed task results consumed by the agent or TaskGroup orchestration.
◦ You need session/speech control (RunContext.session) and per-question lifecycle handling.
• Use function tools when:
◦ You want a synchronous tool call that returns a value to the LLM (or agent) for parsing, validation, or side effects.
◦ You prefer to keep parsing/validation logic separate from the task's turn-handling (e.g., call a tool to normalize answers, check formats, or call an external API).
Brief patterns:
• Task-only (previous example): each question is an AgentTask that prompts, waits for user messages, validates, then calls self.complete(result). This keeps control flow inside the task and is simplest for strict sequential surveys.
• Task + function tool: the task collects the raw reply, then calls a @function_tool to parse/validate or enrich the answer; the task calls self.complete(parsed_result) after the tool returns. Use this when validation is complex or when you want the tool's output included in the LLM context.
Tiny illustrative snippet (Python-style):
# inside AskQuestionTask
async def on_user_message(self, message: str) -> None:
# call a function tool to validate/parse
parsed = await self.run_tool(validate_answer_tool, raw_answer=message)
if parsed.valid:
self.complete(QuestionResult(self.question_id, parsed.value))
else:
await self.session.generate_reply(instructions="I didn't understand that. Please answer again.")
Would you like a concrete example that shows a validation function tool integrated into the survey flow?cool-salesmen-60705
12/10/2025, 10:41 PMtall-airline-16756
12/10/2025, 10:41 PMAgentTask for clarity. That pattern keeps the question/answer turn-handling, re-prompts, and typed results all inside the task. It's simplest when you want strict sequential control.
When to add a `@function_tool`:
• Use a tool if you need separate parsing/validation logic, external API calls, or reusable utilities that the LLM should see as tool outputs.
• Keep the task responsible for prompting, waiting for replies, and calling self.complete(...). Call the function tool from the task to parse/validate the raw reply, then complete with the parsed result.
Short integrated example (Python-style):
class AskQuestionTask(AgentTask[QuestionResult]):
async def on_enter(self) -> None:
await self.session.generate_reply(instructions=self.prompt)
async def on_user_message(self, message: str) -> None:
# call a function tool to validate/normalize the answer
parsed = await self.run_tool(validate_answer_tool, raw_answer=message)
if parsed.valid:
self.complete(QuestionResult(question_id=self.question_id, answer=parsed.value))
else:
await self.session.generate_reply(instructions="I didn't understand that. Please answer again.")
• validate_answer_tool can return structured data (e.g., { valid: bool, value: str, reason?: str }). The tool's return will be included in the LLM context; the task then decides to re-prompt or complete.
• This keeps orchestration inside the task while delegating parsing/validation to a reusable tool.
Would you like a full example with the @function_tool implementation and types?cool-salesmen-60705
12/10/2025, 10:43 PMtall-airline-16756
12/10/2025, 10:44 PMclass AskQuestionTask(AgentTask[QuestionResult]):
async def on_enter(self) -> None:
await self.session.generate_reply(instructions=self.prompt)
async def on_user_turn_completed(self, turn_ctx: ChatContext, new_message: ChatMessage) -> None:
answer = new_message.text_content.strip()
if answer:
self.complete(QuestionResult(question_id=self.question_id, answer=answer))
else:
await self.session.generate_reply(instructions="Please provide an answer to the question.")
Use this hook in tasks or in the agent itself for sequential surveys. Want a full example wiring TaskGroup + JobContext with this hook?
Sources: External data and RAG | LiveKit Docs | Agents v0.x migration guide - Python | LiveKit docs | Pipeline nodes and hooks | LiveKit docs | Tasks and task groups | LiveKit docscool-salesmen-60705
12/10/2025, 10:45 PMtall-airline-16756
12/10/2025, 10:45 PMon_user_turn_completed hook, and an optional function tool for validation. It keeps orchestration inside tasks so each question is strictly answered before moving on.
Code (recommended)
from typing import Dict, List
from dataclasses import dataclass
# Typed result for a single question
@dataclass
class QuestionResult:
question_id: str
answer: str
# Final survey results
@dataclass
class SurveyResults:
answers: Dict[str, str]
class AskQuestionTask(AgentTask[QuestionResult]):
def __init__(self, question_id: str, prompt: str):
super().__init__(instructions=prompt)
self.question_id = question_id
self.prompt = prompt
async def on_enter(self) -> None:
# ask the question when the task starts
await self.session.generate_reply(instructions=self.prompt)
async def on_user_turn_completed(self, turn_ctx: ChatContext, new_message: ChatMessage) -> None:
answer = new_message.text_content.strip()
if not answer:
# re-prompt if empty
await self.session.generate_reply(instructions="Please provide an answer to the question.")
return
# Optional: call a function tool for parsing/validation
# parsed = await self.run_tool(validate_answer_tool, raw_answer=answer)
# if not parsed.valid:
# await self.session.generate_reply(instructions=parsed.reason or "I didn't understand. Please answer again.")
# return
# final_answer = parsed.value
final_answer = answer
self.complete(QuestionResult(question_id=self.question_id, answer=final_answer))
class SurveyAgent(Agent):
def __init__(self, questions: List[Dict[str, str]]):
super().__init__()
self.questions = questions # [{"id":"q1","prompt":"..."}]
async def run(self, ctx: JobContext):
collected: Dict[str, str] = {}
for q in self.questions:
tg = TaskGroup()
tg.add(lambda: AskQuestionTask(q["id"], q["prompt"]), id=q["id"])
results = await tg # agent orchestrates; waits until task calls self.complete(...)
qr: QuestionResult = results[q["id"]]
collected[qr.question_id] = qr.answer
survey_results = SurveyResults(answers=collected)
await self.respond(f"Survey complete. Collected {len(collected)} answers.")
return survey_results
Why this is best (short)
• Uses on_user_turn_completed: runs after transcription/turn end so you get the finalized user reply (correct hook).
• Tasks encapsulate per-question lifecycle: prompt, validate, re-prompt, complete — making retries and state local and testable.
• TaskGroup + agent orchestration: agent awaits a task’s completion before proceeding, guaranteeing strict sequential flow.
• Optional function tool: keeps parsing/validation reusable and visible to the LLM if needed; task remains the controller of flow.
• Typed results: returning structured QuestionResult improves clarity and downstream handling.
If you want, I can:
• add the validate_answer_tool implementation,
• show a multiple-choice validation example,
• produce a TypeScript variant. Which would you like next?cool-salesmen-60705
12/10/2025, 10:49 PMvalidate_answer_tool implementation,tall-airline-16756
12/10/2025, 10:49 PMvalidate_answer_tool implementation (Python-style) plus the small integration snippet showing how the task calls it. The tool returns structured data { valid: bool, value: str, reason?: str }. It supports simple presence checks, optional allowed-choices validation, and basic format validation via a validator callback.
Code — validate tool and integration
from typing import Optional, List, Dict, Any
from dataclasses import dataclass
@dataclass
class ValidateResult:
valid: bool
value: Optional[str] = None
reason: Optional[str] = None
# Example function tool used by tasks to validate/normalize answers
@function_tool()
async def validate_answer_tool(
raw_answer: str,
*,
allowed_choices: Optional[List[str]] = None,
normalize_fn: Optional[callable] = None,
min_length: int = 1
) -> Dict[str, Any]:
"""
Validate and normalize a raw answer.
Args:
raw_answer: user's raw text
allowed_choices: optional list of allowed string choices (case-insensitive)
normalize_fn: optional callable(value: str) -> str for normalization
min_length: minimum non-space length required
Returns:
dict with { "valid": bool, "value": str|None, "reason": str|None }
"""
text = (raw_answer or "").strip()
if len(text) < min_length:
return {"valid": False, "value": None, "reason": "Answer is too short."}
# Normalize
final = normalize_fn(text) if normalize_fn is not None else text
# Choices validation (case-insensitive)
if allowed_choices is not None:
lower_choices = [c.lower() for c in allowed_choices]
if final.lower() not in lower_choices:
return {
"valid": False,
"value": None,
"reason": f"Answer must be one of: {', '.join(allowed_choices)}."
}
return {"valid": True, "value": final, "reason": None}
Integration in AskQuestionTask (snippet)
async def on_user_turn_completed(self, turn_ctx: ChatContext, new_message: ChatMessage) -> None:
raw = new_message.text_content.strip()
# Example: require choice from a set for this question
allowed = self.prompt_choices if hasattr(self, "prompt_choices") else None
parsed = await self.run_tool(
validate_answer_tool,
raw_answer=raw,
allowed_choices=allowed,
normalize_fn=lambda v: v.strip()
)
if not parsed["valid"]:
await self.session.generate_reply(instructions=parsed["reason"] or "I didn't understand. Please answer again.")
return
self.complete(QuestionResult(question_id=self.question_id, answer=parsed["value"]))
Why this pattern:
• The tool is reusable across tasks and questions.
• Returning structured validation results keeps tasks simple: decide to re-prompt or complete.
• Allowed choices and normalization are configurable per call.
Want a version that validates numeric ranges, email format, or a multiple-choice UI? Which validator should I add next?cool-salesmen-60705
12/10/2025, 10:58 PMtall-airline-16756
12/10/2025, 10:59 PMon_user_turn_completed fires, or (B) avoid relying on that hook and use Task-based flow which guarantees sequencing. I recommend the Task + validate tool approach (works in both modes). Below is a concise, ready-to-use Python-style example that:
• uses AgentTask per question with on_user_turn_completed
• calls validate_answer_tool via run_tool
• is safe to use when you configure Realtime with client-side turn detection; otherwise TaskGroup still enforces strict sequence because the agent awaits each task's self.complete(...)
Code (survey agent + validate tool)
from typing import Dict, List, Optional
from dataclasses import dataclass
# --- types ---
@dataclass
class QuestionResult:
question_id: str
answer: str
@dataclass
class SurveyResults:
answers: Dict[str, str]
# --- validation tool ---
@function_tool()
async def validate_answer_tool(
raw_answer: str,
*,
allowed_choices: Optional[List[str]] = None,
normalize: Optional[callable] = None,
min_length: int = 1
) -> Dict:
text = (raw_answer or "").strip()
if len(text) < min_length:
return {"valid": False, "value": None, "reason": "Answer is too short."}
final = normalize(text) if normalize else text
if allowed_choices is not None:
choices_lower = [c.lower() for c in allowed_choices]
if final.lower() not in choices_lower:
return {"valid": False, "value": None, "reason": f"Answer must be one of: {', '.join(allowed_choices)}."}
return {"valid": True, "value": final, "reason": None}
# --- per-question task ---
class AskQuestionTask(AgentTask[QuestionResult]):
def __init__(self, question_id: str, prompt: str, allowed_choices: Optional[List[str]] = None):
super().__init__(instructions=prompt)
self.question_id = question_id
self.prompt = prompt
self.allowed_choices = allowed_choices
async def on_enter(self) -> None:
await self.session.generate_reply(instructions=self.prompt)
async def on_user_turn_completed(self, turn_ctx: ChatContext, new_message: ChatMessage) -> None:
raw = (new_message.text_content or "").strip()
if not raw:
await self.session.generate_reply(instructions="Please provide an answer to the question.")
return
parsed = await self.run_tool(
validate_answer_tool,
raw_answer=raw,
allowed_choices=self.allowed_choices,
normalize=lambda v: v.strip()
)
if not parsed["valid"]:
await self.session.generate_reply(instructions=parsed["reason"] or "I didn't understand. Please answer again.")
return
self.complete(QuestionResult(question_id=self.question_id, answer=parsed["value"]))
# --- agent orchestration ---
class SurveyAgent(Agent):
def __init__(self, questions: List[Dict[str, str]]):
super().__init__()
self.questions = questions
async def run(self, ctx: JobContext):
collected: Dict[str, str] = {}
for q in self.questions:
tg = TaskGroup()
# create AskQuestionTask; id is question id for result lookup
tg.add(lambda: AskQuestionTask(q["id"], q["prompt"], q.get("choices")), id=q["id"])
results = await tg # waits until task calls self.complete(...)
qr: QuestionResult = results[q["id"]]
collected[qr.question_id] = qr.answer
await self.respond(f"Survey complete. Collected {len(collected)} answers.")
return SurveyResults(answers=collected)
Why this is best (brief)
• Task-per-question keeps lifecycle, re-prompts, validation, and typed results local and testable.
• TaskGroup + await guarantees strict sequential flow regardless of realtime turn-detection quirks.
• on_user_turn_completed is the correct hook to process final transcribed input when you enable LiveKit-side turn detection (recommended for Realtime).
• validate_answer_tool keeps parsing/validation reusable and visible to the LLM if desired.
Realtime config note (if you want on_user_turn_completed to fire reliably)
• Disable the Realtime model’s built-in turn detection and provide a streaming STT plugin, or set LiveKit turn detection (e.g., turn_detection=turn_detector.MultilingualModel() and llm.turn_detection=None). This ensures transcripts stream to LiveKit and on_user_turn_completed fires after endpointing.
Do you want a ready-to-run variant wired to your Realtime AgentSession config (showing the exact session setup you should use)?
Sources: Turn detection and interruptions | LiveKit Docs | Pipeline nodes and hooks | LiveKit docs | Tasks and task groups | LiveKit docscool-salesmen-60705
12/10/2025, 11:07 PMtall-airline-16756
12/10/2025, 11:08 PMself.complete(...) after validating input; the agent awaits each task, guaranteeing strict sequential behavior regardless of turn-detection behavior.
If you want, I can:
• show the exact AgentSession Realtime config needed to make on_user_turn_completed reliable, or
• provide a Task-only variant that avoids turn-detection entirely. Which would you prefer?cool-salesmen-60705
12/10/2025, 11:11 PMfrom typing import Dict, List
from dataclasses import dataclass
# Typed result for a single question
@dataclass
class QuestionResult:
question_id: str
answer: str
# Final survey results
@dataclass
class SurveyResults:
answers: Dict[str, str]
class AskQuestionTask(AgentTask[QuestionResult]):
def __init__(self, question_id: str, prompt: str) -> None:
super().__init__(instructions=prompt)
self.question_id = question_id
self.prompt = prompt
async def on_enter(self) -> None:
# Ask the question to the user (generates voice/LM reply)
await self.session.generate_reply(instructions=self.prompt)
async def on_user_message(self, message: str) -> None:
# Simple presence check — require non-empty answer
answer = message.strip()
if answer:
result = QuestionResult(question_id=self.question_id, answer=answer)
self.complete(result)
else:
# Re-prompt if no answer provided
await self.session.generate_reply(instructions="Please provide an answer to the question.")
class SurveyAgent(Agent):
def __init__(self, questions: List[dict]):
super().__init__()
self.questions = questions # list of {"id": "...", "prompt": "..."}
async def run(self, ctx: JobContext):
collected: Dict[str, str] = {}
for q in self.questions:
# Create and run a TaskGroup with a single AskQuestionTask so the agent
# can await the typed result and keep orchestration simple.
tg = TaskGroup()
tg.add(lambda: AskQuestionTask(q["id"], q["prompt"]), id=q["id"])
# Agent orchestrates the TaskGroup and receives results
results = await tg
# results is dict keyed by task id
qr: QuestionResult = results[q["id"]]
collected[qr.question_id] = qr.answer
# All questions answered, complete job (or respond)
survey_results = SurveyResults(answers=collected)
await self.respond(f"Survey complete. Collected {len(collected)} answers.")
# Optionally return results or hand off
return survey_resultstall-airline-16756
12/10/2025, 11:11 PMclass AskQuestionTask(AgentTask[QuestionResult]):
def __init__(self, question_id: str, prompt: str) -> None:
super().__init__(instructions=prompt)
self.question_id = question_id
self.prompt = prompt
async def on_enter(self) -> None:
await self.session.generate_reply(instructions=self.prompt)
async def on_user_turn_completed(self, turn_ctx: ChatContext, new_message: ChatMessage) -> None:
answer = (new_message.text_content or "").strip()
if answer:
self.complete(QuestionResult(question_id=self.question_id, answer=answer))
else:
await self.session.generate_reply(instructions="Please provide an answer to the question.")
Would you like me to:
• show the AgentSession Realtime config that makes on_user_turn_completed reliable, or
• produce a Task-only variant that avoids depending on turn detection?cool-salesmen-60705
12/10/2025, 11:13 PMcool-salesmen-60705
12/10/2025, 11:14 PMtall-airline-16756
12/10/2025, 11:15 PMon_user_turn_completed. Use a single clear pattern that works with Realtime server-side turn detection: expose a function tool (declared with @function_tool) that the LLM will call with the user's final transcript. The platform executes that tool and returns its result into the agent flow; your task then completes only after receiving that validated result.
I’ll give one minimal, correct pattern (no decorated task handlers for tool outputs). This shows:
• a function tool the LLM can call to validate/normalize an answer, and
• a task that prompts and then waits for the model to invoke that function call result via await self.wait_for_function_call(...) (or by checking RunContext.function_call if your SDK surfaces it). If your SDK does not provide a helper, use a TaskGroup/agent-level wait that resolves when the platform returns the function-call output to the job — the key is the task does not implement a decorated handler for tool results.
Minimal, supported pattern (Python-style pseudocode — adapt to your SDK's exact helper names):
# validation tool (exposed to the LLM)
@function_tool()
async def validate_answer_tool(question_id: str, answer: str, allowed_choices: Optional[List[str]] = None) -> Dict:
text = (answer or "").strip()
if not text:
return {"valid": False, "reason": "empty"}
if allowed_choices and text.lower() not in [c.lower() for c in allowed_choices]:
return {"valid": False, "reason": f"must be one of: {', '.join(allowed_choices)}"}
return {"valid": True, "question_id": question_id, "value": text}
class AskQuestionTask(AgentTask[QuestionResult]):
def __init__(self, question_id: str, prompt: str, allowed_choices: Optional[List[str]] = None):
super().__init__(instructions=prompt, tools=[validate_answer_tool])
self.question_id = question_id
self.allowed_choices = allowed_choices
async def on_enter(self) -> None:
# Ask question. With model-side turn detection, the model will listen,
# transcribe, then may call validate_answer_tool(...) as a function call.
await self.session.generate_reply(instructions=self.instructions)
# Wait for the platform to surface the function call result for this task.
# Replace `wait_for_function_call` with your SDK's actual mechanism to get the function-call output.
func_result = await self.wait_for_function_call(tool_name="validate_answer_tool", timeout=60)
# func_result is the dict returned by validate_answer_tool
if not func_result or not func_result.get("valid"):
reason = (func_result or {}).get("reason", "Please answer the question.")
await self.session.generate_reply(instructions=reason)
# Option: re-run wait_for_function_call or re-prompt by calling generate_reply again.
return
self.complete(QuestionResult(question_id=self.question_id, answer=func_result["value"]))
Key points and why this is correct:
• Do not use on_user_turn_completed if you keep model-side turn detection — it may not fire.
• Do not attempt to receive tool outputs via a decorated task method. Tools run either because the task called run_tool(...) or because the LLM issued a function call that the platform executes; the platform then surfaces that tool return into the agent/session flow.
• The safe approach with model-side turn detection: prompt in the task, let the model produce a function call (the platform runs the @function_tool), then have the task await the function-call result via the SDK's supported mechanism (example above uses wait_for_function_call as a placeholder).
• Once the task receives a validated tool result, call self.complete(...) to proceed — this preserves strict sequential behavior.
If you tell me which SDK/language and the exact helper your runtime provides for receiving function-call results (e.g., a wait_for_function_call or reading RunContext.function_call), I’ll give a concrete, runnable code sample matching that API.cool-salesmen-60705
12/10/2025, 11:17 PMtall-airline-16756
12/10/2025, 11:18 PMon_user_turn_completed. Use a function tool the LLM can call and have your task wait for that tool result before completing. Below is a concise, runnable Python pattern that matches the LiveKit Agents approach and works with Realtime function-calling.
Code (Python-style)
from typing import Dict, List, Optional
from dataclasses import dataclass
# --- types ---
@dataclass
class QuestionResult:
question_id: str
answer: str
@dataclass
class SurveyResults:
answers: Dict[str, str]
# --- validation tool (exposed to the LLM) ---
@function_tool()
async def validate_answer_tool(question_id: str, answer: str, allowed_choices: Optional[List[str]] = None) -> Dict:
text = (answer or "").strip()
if not text:
return {"valid": False, "reason": "empty"}
if allowed_choices:
if text.lower() not in [c.lower() for c in allowed_choices]:
return {"valid": False, "reason": f"must be one of: {', '.join(allowed_choices)}"}
return {"valid": True, "question_id": question_id, "value": text}
# --- per-question task (prompts, then waits for the LLM to call the tool) ---
class AskQuestionTask(AgentTask[QuestionResult]):
def __init__(self, question_id: str, prompt: str, allowed_choices: Optional[List[str]] = None):
# expose validate tool to the model for this task
super().__init__(instructions=prompt, tools=[validate_answer_tool])
self.question_id = question_id
self.prompt = prompt
self.allowed_choices = allowed_choices
async def on_enter(self) -> None:
# Ask the question; with model-side turn detection the model will listen,
# then may issue a function call like validate_answer_tool(...)
await self.session.generate_reply(instructions=self.prompt)
# Wait for the platform to surface the function-call result.
# The exact helper name may vary by SDK; use your SDK's function-call wait API.
# Here we use a conceptual helper `wait_for_function_call(tool_name, timeout)`:
func_result = await self.wait_for_function_call(tool_name="validate_answer_tool", timeout=60)
if not func_result or not func_result.get("valid"):
reason = (func_result or {}).get("reason", "Please answer the question.")
# re-prompt the user and let the model attempt another function call
await self.session.generate_reply(instructions=reason)
return # the task remains active; you'll re-run wait_for_function_call or re-enter logic
# complete task with the validated value
self.complete(QuestionResult(question_id=self.question_id, answer=func_result["value"]))
# --- agent orchestration (sequential TaskGroup) ---
class SurveyAgent(Agent):
def __init__(self, questions: List[Dict[str, str]]):
super().__init__()
self.questions = questions
async def run(self, ctx: JobContext):
collected: Dict[str, str] = {}
for q in self.questions:
tg = TaskGroup()
tg.add(lambda: AskQuestionTask(q["id"], q["prompt"], q.get("choices")), id=q["id"])
results = await tg # waits until task calls self.complete(...)
qr: QuestionResult = results[q["id"]]
collected[qr.question_id] = qr.answer
await self.respond(f"Survey complete. Collected {len(collected)} answers.")
return SurveyResults(answers=collected)
Notes and next steps
• Replace wait_for_function_call with your SDK's actual mechanism for receiving function-call results (some SDKs surface RunContext.function_call or provide an explicit wait helper).
• This pattern works while keeping the Realtime model's built-in turn detection enabled because the model itself issues the function call; the platform executes the tool and the task awaits that result.
• If you want, tell me which LiveKit Python SDK version you use and I’ll adapt the snippet to the SDK's exact function-call wait API. Sources: Gemini Live API plugin | LiveKit docs | OpenAI and LiveKit partner to turn Advanced Voice into an API | Agent speech and audio | LiveKit docs | Tasks and task groups | LiveKit docscool-salesmen-60705
12/10/2025, 11:19 PMtall-airline-16756
12/10/2025, 11:20 PMsession.wait_for_function_call(...), self.wait_for_function_call(...), or RunContext.function_call)? If yes, which helper name? If unsure, say "unsure" and I’ll provide a safe fallback using the task-initiated pattern (B).
Tell me 1–3 and I’ll return the exact 1.3.6 Python code.
Sources: LiveKit turn detector plugin | LiveKit docs | Turn detection and interruptions | LiveKit Docs | OpenAI Realtime API plugin guide | LiveKit docs | Agents v0.x migration guide - Python | LiveKit docs | Tool definition and use | LiveKit docscool-salesmen-60705
12/10/2025, 11:42 PMtall-airline-16756
12/10/2025, 11:43 PMchat_ctx or full history into each task.
◦ Create a fresh, minimal context/instruction for each task that only contains the current question and any essential static facts (e.g., user locale). Example: instructions = "Ask only: 'What is your age?' Wait for an answer. Do not proceed."
• Use TaskGroup sequencing:
◦ Keep one task per question and let the agent await the task's self.complete(...). TaskGroup guarantees strict sequential flow.
• If you keep model-side turn detection (Realtime):
◦ Use function tools or model function-calling to validate the single answer the model returns, then complete the task only after the tool result is received.
◦ Do not rely on LiveKit hooks that depend on client-side turn detection.
Minimal pattern to fix the problem (summary):
• Per-question AgentTask:
◦ Super with only the question prompt (no shared chat_ctx).
◦ Ask via session.generate_reply(instructions=...).
◦ Validate via run_tool or await the model's function-call result.
◦ Call self.complete(result) only after validation succeeds.
• Orchestrate with TaskGroup so next question doesn't start until completion.
If you want, I can:
• Convert your current code to the isolated-context TaskTaskGroup pattern, or
• Provide a concrete runnable snippet that replaces your current shared chat_ctx usage (send me the current snippet and I’ll patch it). Sources: Pipeline nodes and hooks | LiveKit docs | Tasks and task groups | LiveKit docs | Turn detection and interruptions | LiveKit Docscool-salesmen-60705
12/11/2025, 12:18 AM@dataclass
class QuestionResult:
"""Result from a discussion question task."""
question_number: int
student_response: str
class DiscussionQuestionTask(AgentTask[QuestionResult]):
"""Task for ONE discussion question."""
def __init__(
self,
question_number: int,
question_text: str,
total_questions: int,
running_assessment: RunningAssessment,
turn_index: int,
conversation_id: str,
db_client: Optional["DatabaseClient"] = None,
coaching_disabled: bool = False,
chat_ctx: Optional[Any] = None,
):
self._question_number = question_number
self._question_text = question_text
self._total_questions = total_questions
self._running = running_assessment
self._turn_index = turn_index
self._conversation_id = conversation_id
self._db_client = db_client
self._coaching_disabled = coaching_disabled
super().__init__(
instructions=f"""You will ask the student the question on the card then record the response. Accept the first answer and do not follow up that question.""",
chat_ctx=chat_ctx
)
async def on_enter(self) -> None:
"""Ask the question."""
logger.info(
f"▶️ TASK_START question_{self._question_number} conv={self._conversation_id} "
f"turn={self._turn_index} q={self._question_number}/{self._total_questions}"
)
logger.info(f"❓ ASKING: {self._question_text[:80]}...")
await self.session.generate_reply(
instructions=f'Ask this question in French: "{self._question_text}"'
)
logger.info(f"📤 Question {self._question_number} asked, now waiting for student response")
@function_tool()
async def record_response(self, context: RunContext, student_response: str) -> None:
"""Record the student's response to this question. Call this after the student answers.
Args:
student_response: What the student said in French
"""
logger.info(
f"🎤 STUDENT_RESPONDED q={self._question_number} conv={self._conversation_id} "
f"response={student_response[:50]}... - completing task"
)
result = QuestionResult(
question_number=self._question_number,
student_response=student_response
)
self.complete(result)tall-airline-16756
12/11/2025, 12:18 AMchat_ctx into each task via super().__init__(..., chat_ctx=chat_ctx). That leaks prior messages (including earlier answers) into the new task's prompt so the LLM thinks earlier answers apply to the current question.
What to change (concise)
• Do NOT pass the full/shared chat_ctx into each task.
• Expose the validation tool to the model (so the model calls record_response) but keep each task's instructions minimal and isolated.
• Ensure TaskGroup/agent awaits each task's self.complete(...) before starting the next.
Fixed minimal version of your task (only changed parts)
class DiscussionQuestionTask(AgentTask[QuestionResult]):
def __init__(self, question_number: int, question_text: str, ...):
self._question_number = question_number
self._question_text = question_text
...
# do NOT pass chat_ctx that contains prior Q/A
super().__init__(
instructions=f"Ask only this question and accept the first answer. Do not follow up.",
tools=[record_response] # register the tool so the model can call it
)
async def on_enter(self) -> None:
await self.session.generate_reply(
instructions=f'Ask this question in French: "{self._question_text}"'
)
# Do not await function here; the platform will execute the model's function call
# and call `record_response` when the model invokes it.
@function_tool()
async def record_response(self, context: RunContext, student_response: str) -> None:
# record and complete only for this task
result = QuestionResult(question_number=self._question_number, student_response=student_response)
self.complete(result)
Additional checklist to ensure correct behavior
• Make sure you create a fresh TaskGroup per question (or add tasks to a TaskGroup and await it). Do not pre-populate task chat history.
• Keep the task's instruction explicit: "Ask only this question. Wait for answer. Do not proceed."
• Confirm the tool record_response is registered on the task (as shown with tools=[record_response]), so the model's function call executes in the task's scope.
• If the LLM still answers multiple questions at once, reduce system/instruction verbosity and remove any earlier answers from prompts.
If you want, I can:
• Patch your full agent orchestration (showing how you create/use TaskGroup) so the next task does not start until the previous task's self.complete(...) returns; or
• Produce a minimal end-to-end example showing TaskGroup usage and how the model's function call triggers record_response.
Which would you like?cool-salesmen-60705
12/11/2025, 2:20 PMtall-airline-16756
12/11/2025, 2:20 PMself.complete(...) more than once for the same AgentTask (direct double-call or race between two code paths).
• You added a task instance to TaskGroup instead of a factory lambda (reusing an already-completed task instance).
• A tool or timeout handler also calls complete() (race).
• External code mutates task state or re-enters a task that was already finished.
What to change (apply these in order)
1) Add a completion guard inside the task
• Add a boolean flag and check it before calling self.complete(...) so completion is idempotent.
class MyTask(AgentTask[...]):
def __init__(...):
self._completed = False
...
def _safe_complete(self, result):
if self._completed:
return
self._completed = True
self.complete(result)
Use _safe_complete(...) everywhere instead of calling self.complete(...) directly.
2) Ensure TaskGroup uses factories (fresh instances)
• Always add tasks with a factory lambda:
tg.add(lambda: DiscussionQuestionTask(...), id="q1")
Do NOT do tg.add(DiscussionQuestionTask(...), ...) — that reuses one instance.
3) Avoid multiple code paths that call complete
• If you have a function-tool handler and a timeout or alternative handler, centralize completion logic so only one path calls _safe_complete.
• If you accept a function-tool result, don’t also complete in a separate `on_enter`/timeout path without checking the flag.
4) Log around completion to find races
• Before calling _safe_complete, log task id, caller, timestamp. After fixing, you should see only one completion log per task.
logger.info("completing task", extra={"q": self._question_number})
5) Handle TaskGroup await errors gracefully (optional)
• If you still hit the error while awaiting, capture the exception and read partial results:
try:
results = await task_group
except Exception:
results = task_group.task_results # read what finished
Use this only as a safety net while you root-cause the double-completion.
Why this solves your specific case
• Your earlier code registers a record_response tool that may be invoked by the model and could race with any other path that also calls self.complete(...). The guard prevents completing twice; using factory lambdas prevents reused instances; logging reveals which path triggered completion more than once.
If you'd like, paste the agent orchestration code where you create the TaskGroup and show how tasks/tools/timeouts are wired. I’ll patch it to the guarded pattern and point out the single line causing the double-complete.
Sources: Tasks and task groups | LiveKit docs | Building an Automated IVR Menu Caller | LiveKit docs | Turn detection and interruptions | LiveKit Docscool-salesmen-60705
12/11/2025, 4:14 PMtall-airline-16756
12/11/2025, 4:15 PMself.complete() twice.
Quick clarification and next steps:
• It can be a framework bug, but the same exception is also commonly caused by misuse patterns (re-using a task instance, adding tasks incorrectly, or an internal race where the framework and your task both call complete). Because the stack shows TaskGroup, we should confirm how tasks are being added and whether a task instance is reused.
Please share these two small details so I can pinpoint root cause quickly:
1. The exact code you use to add tasks to the TaskGroup (the lines that call task_group.add(...)).
2. Whether you pass a task instance or a factory lambda (example: lambda: MyTask(...) vs MyTask(...)).
If you prefer, paste the 8–12 lines where the TaskGroup is constructed and awaited. I’ll review and tell you whether this is a usage issue you can fix immediately or if it looks like a framework bug and we should use a safe workaround (completion guard + factory lambdas) while we investigate.cool-salesmen-60705
12/11/2025, 4:17 PM# Create a simple TaskGroup with just DescribePhotoTask
task_group = TaskGroup()
theme = self._content_data.get('theme', '')
task_group.add(
lambda: DescribePhotoTask(
running_assessment=self._running,
turn_index=0,
conversation_id=self._conversation_id,
db_client=self._db_client,
coaching_disabled=self._coaching_disabled,
theme=theme,
),
id="describe_photo",
description="Student describes the photo"
)
logger.info(
f"📋 TASK_GROUP_READY conv={self._conversation_id} "
f"executing DescribePhotoTask only..."
)
# Execute TaskGroup
try:
results = await task_group
logger.info(
f"✅ TASK_GROUP_COMPLETE conv={self._conversation_id} "
f"results={list(results.task_results.keys()) if hasattr(results, 'task_results') else 'N/A'}"
)
except RuntimeError as e:
if "already done" in str(e):
logger.info(
f"✅ TASK_GROUP_COMPLETE conv={self._conversation_id} "
f"(caught 'already done' - task completed successfully)"
)
else:
raisetall-airline-16756
12/11/2025, 4:17 PMclass DescribePhotoTask(AgentTask[QuestionResult]):
def __init__(...):
self._completed = False
...
def _safe_complete(self, result):
if self._completed:
return
self._completed = True
self.complete(result)
• Replace any direct self.complete(...) calls with _safe_complete(...). This rules out double-complete from within the task.
2) Check function-tool handlers and other paths
• If DescribePhotoTask has any @function_tool methods, timeouts, or callbacks, ensure none call self.complete(...) except via _safe_complete.
• If you call run_tool(...) or use wait_for_function_call, ensure you only complete once after receiving tool output.
3) Add short logs around completion
• Log right before calling _safe_complete(...) and inside _safe_complete so you can see if it's triggered multiple times and from which code path.
4) Paste DescribePhotoTask implementation (full class)
• I need the task body showing on_enter, any @function_tool methods, timeouts, and where self.complete() is called to validate there are no hidden double-complete paths.
5) If tests still show "already done" after applying the guard
• Share the exact stack trace (TaskGroup.on_enter line 103) and the DescribePhotoTask class. If after the guard the error persists and logs show only one _safe_complete invocation, it looks like a framework double-complete and I'll provide a safe workaround and a minimal repro you can run while we investigate.
Send the DescribePhotoTask class now and I’ll point to the exact lines to change or confirm a framework bug.cool-salesmen-60705
12/11/2025, 4:23 PM"""Task for describing the photo in a photo card component."""
import logging
from dataclasses import dataclass
from typing import Optional, Any, TYPE_CHECKING
from livekit.agents import AgentTask, function_tool, RunContext
from .base_task import RunningAssessment, ComponentScores
if TYPE_CHECKING:
from database_client import DatabaseClient
logger = logging.getLogger("exam_agent.tasks")
@dataclass
class PhotoDescriptionResult:
"""Result from the photo description task."""
scores: ComponentScores
student_response: str
class DescribePhotoTask(AgentTask[PhotoDescriptionResult]):
"""Task for the 'describe the photo' phase."""
def __init__(
self,
running_assessment: RunningAssessment,
turn_index: int,
conversation_id: str,
db_client: Optional["DatabaseClient"] = None,
coaching_disabled: bool = False,
chat_ctx: Optional[Any] = None,
theme: str = "",
image_url: str = "",
description_prompt: str = "",
):
self._running = running_assessment
self._turn_index = turn_index
self._conversation_id = conversation_id
self._db_client = db_client
self._coaching_disabled = coaching_disabled
self._theme = theme
self._completed = False # Guard against double-completion
super().__init__(
instructions="""You ask questions and wait for the student to respond. After they respond, call record_description() with your evaluation.""",
chat_ctx=chat_ctx
)
async def on_enter(self) -> None:
"""Prompt the student to describe the photo."""
logger.info(
f"▶️ TASK_START describe_photo conv={self._conversation_id} "
f"turn={self._turn_index} theme={self._theme}"
)
await self.session.generate_reply(
instructions='Say: "Hi Describe the photo."'
)
logger.info(f"📤 TASK generate_reply completed conv={self._conversation_id}")
@function_tool()
async def record_description(
self,
context: RunContext,
student_response: str,
score: float,
) -> None:
"""Record the student's response and score it, then move to the next question.
Args:
student_response: What the student said
score: Overall score from 0-5
"""
logger.info(
f"📊 RECORD_DESCRIPTION conv={self._conversation_id} "
f"score={score} response={student_response[:100]}..."
)
# Create simple scores (all same value for now)
scores = ComponentScores(
pronunciation=score,
grammar=score,
vocabulary=score,
fluency=score,
interaction=score,
confidence=score,
)
# Add to running assessment
from .base_task import TurnRecord
import time
record = TurnRecord(
turn_index=self._turn_index,
chars=len(student_response),
timestamp_s=time.time(),
notes="",
scores=scores,
)
self._running.add_turn(record)
logger.info(
f"📊 SCORE_BREAKDOWN conv={self._conversation_id} turn={self._turn_index} "
f"P={scores.pronunciation:.1f} G={scores.grammar:.1f} V={scores.vocabulary:.1f} "
f"F={scores.fluency:.1f} I={scores.interaction:.1f} C={scores.confidence:.1f} "
f"AVG={scores.mean():.2f}"
)
# Signal task completion to TaskGroup with result (guarded)
result = PhotoDescriptionResult(scores=scores, student_response=student_response)
self._safe_complete(result)
def _safe_complete(self, result: PhotoDescriptionResult) -> None:
"""Complete the task only once (idempotent)."""
if self._completed:
logger.warning(
f"⚠️ DOUBLE_COMPLETE_BLOCKED describe_photo conv={self._conversation_id} "
f"- task already completed, ignoring"
)
return
self._completed = True
# logger.info(f"✅ TASK_COMPLETE describe_photo conv={self._conversation_id}")
self.complete(result)tall-airline-16756
12/11/2025, 4:23 PMself._completed) and now call _safe_complete(...) only from the function-tool. That rules out double-completion coming from your task code.
Given that:
• You use a factory lambda when adding the task to the TaskGroup (good).
• The only completion call in the task is through _safe_complete (good).
• Yet you're still seeing the "already done" error originating from TaskGroup.on_enter.
Next steps and actionable checks (concise):
1) Confirm single invocation of your tool
• Add a short log at the very start of record_description to ensure the function-tool is invoked exactly once per task run:
logger.info("record_description invoked for q={self._turn_index}")
• If you see multiple invocations, the model may be issuing the function call multiple times (or the platform retried); that would explain TaskGroup seeing duplicate completions.
2) Capture TaskGroup timing
• Log right before awaiting the group and immediately after to see whether the exception happens during await or after playout:
logger.info("awaiting task_group") results = await task_group logger.info("await completed")
3) Reproduce with minimal flow
• Run a minimal scenario with only this single task in the TaskGroup (looks like you already do this). If the error still appears, collect:
◦ full exception stack trace
◦ timestamps of your _safe_complete log and the exception log
If _safe_complete log appears once and the exception still occurs, this indicates the framework is calling complete() internally a second time.
4) Workaround (safe, immediate)
• Continue using your _safe_complete guard (keeps correctness).
• Wrap awaiting the TaskGroup to tolerate this known error and read partial results:
try: results = await task_group except RuntimeError as e: if "already done" in str(e): logger.info("caught already done, reading task_group.task_results") results = task_group.task_results else: raise
5) If you want me to investigate further
• Paste the full runtime stack trace (including TaskGroup.on_enter line numbers) and the timestamps/log lines from steps 1–2. If _safe_complete shows once but exception still occurs, I will mark this as a likely framework bug and give a minimal repro you can run to file it.
Summary: Your task code is correct. The next step is to confirm whether the function-tool is being invoked multiple times or the TaskGroup itself is double-completing (logs + stack trace will show which). I can craft a minimal repro or help you handle the error gracefully depending on what the logs show. Which logs/stack trace can you share?cool-salesmen-60705
12/11/2025, 4:35 PMtall-airline-16756
12/11/2025, 4:36 PMself.complete(...) when gathering results, but the agent/container has already been marked done, raising RuntimeError: TaskGroup is already done. Given your task code uses a factory lambda and an idempotent completion guard, this strongly indicates the duplicate completion is coming from the TaskGroup/framework side, not your task.
What this means
• TaskGroup is experimental and can race in its finalization logic, producing an "already done" error even though tasks completed successfully.
• Your current guard and logs show the task completed exactly once, so the error is non-fatal and caused by the framework calling complete() a second time.
Recommended immediate actions (safe workaround)
1. Keep your _safe_complete guard in the task (you already have this).
2. Await the TaskGroup inside a try/except and treat the specific error as success, then read the results from `task_group.task_results`:
try:
results = await task_group
except RuntimeError as e:
if "already done" in str(e):
logger.info("caught 'already done' — reading task_group.task_results")
results = task_group.task_results
else:
raise
1. Add a short debug log at the start of your function-tool to confirm it is invoked only once (helps rule out model retries).
Longer-term options
• If you need a more robust flow, avoid TaskGroup and orchestrate tasks manually (create and await each task instance sequentially), which removes the TaskGroup finalization path that triggers the bug.
• If you want me to produce a patched pattern that replaces TaskGroup with explicit per-question awaits, I can provide that snippet.
If you'd like, paste:
• the single _safe_complete invocation log line and timestamp, and
• the exact TaskGroup stack trace lines you already shared,
and I’ll produce a minimal repro you can run locally and a drop-in replacement for TaskGroup orchestration to eliminate the framework race. Which would you prefer?
Sources: Tasks and task groups | LiveKit docs | Events and error handling | LiveKit docs | Tool definition and use | LiveKit docs | Agents and handoffs | LiveKit docs | OpenAI Realtime API plugin guide | LiveKit docs