When my LiveKit voice agent calls a tool, the Gemi...
# ask-ai
s
When my LiveKit voice agent calls a tool, the Gemini LLM plugin fails with a Pydantic schema generation error. This started recently even though the same agent and tools worked fine for months. PydanticSchemaGenerationError: Unable to generate pydantic-core schema for livekit.agents.voice.events.RunContext[__mp_main__.UserData]. Set arbitrary_types_allowed=True in the model_config to ignore this error, or implement __get_pydantic_core_schema__ for the type. This happened while LiveKit tried to convert my tool function to a Gemini function schema: File: livekit/plugins/google/utils.py line 131 fnc = llm.utils.build_legacy_openai_schema(function_tool) Which calls: function_arguments_to_pydantic_model(...) create_model(...) generate_schema(...) and fails while processing a generic type: RunContext[UserData] APIConnectionError: gemini llm: error generating content Unable to generate pydantic-core schema for RunContext[UserData]. (body=None, retryable=True)
t
Thanks for reaching out, Ajay. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks — I’m responding about the Pydantic schema generation error you see when the LiveKit voice agent converts a tool to a Gemini function schema (error: Unable to generate pydantic-core schema for RunContext[UserData]). Quick diagnosis summary: • Pydantic cannot generate a schema for the generic type
RunContext[UserData]
. This commonly happens after a dependency/version change (pydantic or agent/plugin) that tightened schema generation. • The conversion path failing is:
build_legacy_openai_schema(...)
→
function_arguments_to_pydantic_model
→
create_model
→
generate_schema
— failing on
RunContext[UserData]
. Practical fixes (fastest first) 1) Immediate fix — allow arbitrary types • Add Pydantic config to your
UserData
so Pydantic will accept it without generating a strict schema:
Copy code
from pydantic import ConfigDict

@dataclass
class UserData:
    user_name: str | None = None
    age: int | None = None

    model_config = ConfigDict(arbitrary_types_allowed=True)
This usually unblocks the function-schema conversion quickly. 2) Safer refactor — avoid generic typed
RunContext[...]
in tool signatures • Remove the generic typing from the function parameter so schema generation won’t try to process it:
Copy code
@function_tool()
async def my_tool(self, context, location: str):
    userdata: UserData = context.userdata
or accept only serializable inputs and access
context.userdata
inside the body. 3) Use explicit Pydantic input models for tool arguments • Replace passing typed
RunContext
fields with a Pydantic model that contains only the needed serializable fields:
Copy code
from pydantic import BaseModel

class NameInput(BaseModel):
    name: str

@function_tool()
async def record_name(self, context: RunContext, input: NameInput):
    context.userdata.user_name = input.name
4) Advanced — implement custom pydantic core schema (if you must keep complex types) • Implement
__get_pydantic_core_schema__
on
UserData
(advanced, more work). Only needed if you require full schema support for that type. Checks to run now • Verify
UserData
doesn’t embed non-serializable objects (Room, locks, participants, etc.). • Check recent package updates for
pydantic
,
livekit-agents
, or the Gemini plugin that might have changed schema behavior. If you want, I can: • Suggest the minimal code change (showing exact file/line) to add
model_config
if you paste your
UserData
definition, or • Help you refactor one tool signature you paste here so it avoids the generic type and works with Gemini function conversion. Which would you prefer? Sources: AI Agents Framework | livekit/livekit_composite | DeepWiki | Gemini Live API plugin | LiveKit docs | Tool definition and use | LiveKit docs | Agents and handoffs | LiveKit docs
s
2025-11-24 120008,243 - DEBUG livekit.agents - executing tool {"function": "transfer_to_quiz", "arguments": "{}", "speech_id": "speech_2e369a87799d"} 2025-11-24 120008,244 - DEBUG livekit.agents - tools execution completed {"speech_id": "speech_2e369a87799d"} 2025-11-24 120008,246 - INFO Aina-Voice Agent - Entering Quiz 2025-11-24 120008,375 - WARNING livekit.agents - failed to generate LLM completion, retrying in 0.1s {"llm": "livekit.plugins.google.llm.LLM", "attempt": 1} Traceback (most recent call last): File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\livekit\plugins\google\llm.py", line 330, in _run function_declarations = to_fnc_ctx(self._tools) File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\livekit\plugins\google\utils.py", line 58, in to_fnc_ctx tools.append(_build_gemini_fnc(fnc, tool_behavior=tool_behavior)) File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\livekit\plugins\google\utils.py", line 131, in _build_gemini_fnc fnc = llm.utils.build_legacy_openai_schema(function_tool, internally_tagged=True) File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\livekit\agents\llm\utils.py", line 203, in build_legacy_openai_schema model = function_arguments_to_pydantic_model(function_tool) File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\livekit\agents\llm\utils.py", line 345, in function_arguments_to_pydantic_model return create_model(model_name, **fields) File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\pydantic\main.py", line 1804, in create_model return meta( File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\pydantic\_internal\_model_construction.py", line 255, in new complete_model_class( File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\pydantic\_internal\_model_construction.py", line 648, in complete_model_class schema = gen_schema.generate_schema(cls) File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\pydantic\_internal\_generate_schema.py", line 729, in generate_schema schema = self._generate_schema_inner(obj) File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\pydantic\_internal\_generate_schema.py", line 1023, in _generate_schema_inner return self._model_schema(obj) File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\pydantic\_internal\_generate_schema.py", line 856, in _model_schema {k: self._generate_md_field_schema(k, v, decorators) for k, v in fields.items()}, File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\pydantic\_internal\_generate_schema.py", line 856, in <dictcomp> {k: self._generate_md_field_schema(k, v, decorators) for k, v in fields.items()}, File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\pydantic\_internal\_generate_schema.py", line 1228, in _generate_md_field_schema schema, metadata = self._common_field_schema(name, field_info, decorators) File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\pydantic\_internal\_generate_schema.py", line 1282, in _common_field_schema schema = self._apply_annotations( File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\pydantic\_internal\_generate_schema.py", line 2227, in _apply_annotations schema = get_inner_schema(source_type) File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\pydantic\_internal\_schema_generation_shared.py", line 83, in call schema = self._handler(source_type) File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\pydantic\_internal\_generate_schema.py", line 2206, in inner_handler schema = self._generate_schema_inner(obj) File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\pydantic\_internal\_generate_schema.py", line 1028, in _generate_schema_inner return self.match_type(obj) File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\pydantic\_internal\_generate_schema.py", line 1144, in match_type return self._match_generic_type(obj, origin) File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\pydantic\_internal\_generate_schema.py", line 1167, in _match_generic_type return self._union_schema(obj) File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\pydantic\_internal\_generate_schema.py", line 1327, in _union_schema choices.append(self.generate_schema(arg)) File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\pydantic\_internal\_generate_schema.py", line 729, in generate_schema schema = self._generate_schema_inner(obj) File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\pydantic\_internal\_generate_schema.py", line 1028, in _generate_schema_inner return self.match_type(obj) File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\pydantic\_internal\_generate_schema.py", line 1144, in match_type return self._match_generic_type(obj, origin) File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\pydantic\_internal\_generate_schema.py", line 1199, in _match_generic_type return self._unknown_type_schema(obj) File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\pydantic\_internal\_generate_schema.py", line 659, in _unknown_type_schema raise PydanticSchemaGenerationError( pydantic.errors.PydanticSchemaGenerationError: Unable to generate pydantic-core schema for livekit.agents.voice.events.RunContext[__mp_main__.UserData]. Set
arbitrary_types_allowed=True
in the model_config to ignore this error or implement
__get_pydantic_core_schema__
on your type to fully support it. If you got this error by calling handler(<some type>) within
__get_pydantic_core_schema__
then you likely need to call
handler.generate_schema(<some type>)
since we do not call
__get_pydantic_core_schema__
on
<some type>
otherwise to avoid infinite recursion. For further information visit https://errors.pydantic.dev/2.12/u/schema-for-unknown-type The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\livekit\agents\llm\llm.py", line 190, in _main_task return await self._run() File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\livekit\plugins\google\llm.py", line 423, in _run raise APIConnectionError( livekit.agents._exceptions.APIConnectionError: gemini llm: error generating content Unable to generate pydantic-core schema for livekit.agents.voice.events.RunContext[__mp_main__.UserData]. Set
arbitrary_types_allowed=True
in the model_config to ignore this error or implement
__get_pydantic_core_schema__
on your type to fully support it. If you got this error by calling handler(<some type>) within
__get_pydantic_core_schema__
then you likely need to call
handler.generate_schema(<some type>)
since we do not call
__get_pydantic_core_schema__
on
<some type>
otherwise to avoid infinite recursion.
t
Thanks — I’m replying about the error log showing Pydantic failing to generate a schema for
RunContext[UserData]
when converting your tool to a Gemini function schema. Next step I can take to help: please paste the
UserData
class definition and the tool function signature(s) (the
@function_tool
function(s) that reference
RunContext[...]
) so I can suggest the exact minimal change. If you prefer a quick workaround right away, add this to your
UserData
definition:
Copy code
from pydantic import ConfigDict

@dataclass
class UserData:
    user_name: str | None = None
    age: int | None = None

    model_config = ConfigDict(arbitrary_types_allowed=True)
That typically unblocks schema generation. If you paste your definitions I’ll confirm that change or give a safer refactor (remove generic typing from the function signature or replace the input with a serializable Pydantic model) tailored to your code.
s
@function_tool() async def transfer_to_quiz(self, context: RunContext_T) -> Agent: """Use this tool when the user wants to take a quiz.""" userdata = context.userdata student_name = userdata.student_name students_choice_of_exam = userdata.students_choice_of_exam student_grade = userdata.student_grade student_id = userdata.user_id conversation_id = userdata.conversation_id # print(userdata.student_name , "////////////////////////////student_name/////////") return Quiz(student_name=student_name, students_choice_of_exam=students_choice_of_exam, student_grade=student_grade,student_id=student_id, conversation_id=conversation_id,chat_ctx=self.chat_ctx) @dataclass class UserData: """Stores data to be shared across the session""" user_id: str = "" personas: dict[str, Agent] = field(default_factory=dict) persona_factories: dict[str, Callable[[], Agent]] = field(default_factory=dict) prev_agent: Optional[Agent] = None ctx: Optional[JobContext] = None quiz_answers: list = field(default_factory=list) insights: list = field(default_factory=list) recommendations: list = field(default_factory=list) quiz_completed: bool = False counselling_Booked: bool = False course_enrolled: bool = False created_at: datetime = field(default_factory=datetime.now) last_modified: datetime = field(default_factory=datetime.now) student_name: Optional[str] = None student_grade: Optional[str] = None students_choice_of_exam: Optional[str] = None last_agent_name: Optional[str] = None # Tracks the key of the last agent used (e.g., "quiz") conversation_id:Optional[str] = None subject: Optional[str] = None RunContext_T = RunContext[UserData]
t
Thanks — I’m responding about the
RunContext[UserData]
schema error in your
transfer_to_quiz
tool. Recommended immediate fix (minimal change) • Add Pydantic config to
UserData
so Pydantic will skip strict schema generation:
Copy code
from pydantic import ConfigDict
from dataclasses import dataclass, field
from typing import Optional, Callable, Dict, List
from datetime import datetime

@dataclass
class UserData:
    user_id: str = ""
    personas: Dict[str, "Agent"] = field(default_factory=dict)
    persona_factories: Dict[str, Callable[[], "Agent"]] = field(default_factory=dict)
    prev_agent: Optional["Agent"] = None
    ctx: Optional["JobContext"] = None
    quiz_answers: List = field(default_factory=list)
    insights: List = field(default_factory=list)
    recommendations: List = field(default_factory=list)
    quiz_completed: bool = False
    counselling_Booked: bool = False
    course_enrolled: bool = False
    created_at: datetime = field(default_factory=datetime.now)
    last_modified: datetime = field(default_factory=datetime.now)
    student_name: Optional[str] = None
    student_grade: Optional[str] = None
    students_choice_of_exam: Optional[str] = None
    last_agent_name: Optional[str] = None
    conversation_id: Optional[str] = None
    subject: Optional[str] = None

    model_config = ConfigDict(arbitrary_types_allowed=True)
This typically unblocks the schema generation and should stop the Gemini/pydantic error. Safer refactor (if you prefer avoiding arbitrary types) • Remove the generic
RunContext[UserData]
from the tool signature so Pydantic doesn’t attempt to generate a schema for it:
Copy code
@function_tool()
async def transfer_to_quiz(self, context) -> Agent:
    userdata = context.userdata
    ...
or accept only serializable inputs and access
context.userdata
inside the function body, or pass a Pydantic
BaseModel
containing only the fields you need. Which option would you like me to expand into a patch for your repository? If you want, paste the file path(s) and I’ll show the exact diff to apply.
s
if i say context as input parameter how will the agent know it should send the userdata class
t
Good question — typing only affects schema generation and static checks; it doesn’t change what LiveKit passes at runtime. • At runtime LiveKit passes a RunContext instance (including
context.userdata
) into your tool regardless of whether you annotate the parameter as
RunContext[UserData]
. So changing the signature to
async def transfer_to_quiz(self, context)
will still let you access
userdata = context.userdata
inside the function. • The reason we remove
RunContext[UserData]
is to avoid Pydantic trying to generate a function schema for that generic type. The LLM/function-calling layer only needs serializable inputs — it doesn't need the full
RunContext
schema — so keeping
context
untyped prevents the schema error while preserving runtime behavior. Best practice options: • Keep the parameter untyped (
context
) and use
context.userdata
inside the body. • Or accept a small serializable Pydantic
BaseModel
with only the fields the tool needs (preferred if you want the LLM to supply structured arguments). If you want, I can show the exact signature change or convert the fields your tool needs into a simple
BaseModel
and show that patch. Which would you prefer?
s
should i remove the parameter it self
t
You don’t need to remove the
context
parameter — keep it so you can access runtime state (like
context.userdata
). Instead do one of these minimal changes: • Easiest: keep
context
but remove the
RunContext[UserData]
typing so Pydantic won’t try to generate a schema:
Copy code
@function_tool()
async def transfer_to_quiz(self, context) -> Agent:
    userdata = context.userdata
    ...
• If you want LLM-driven structured inputs: remove
context
from the function signature and accept only a serializable Pydantic model with the fields the LLM should supply, then read/update
context.userdata
from elsewhere (e.g., the agent/session). Example:
Copy code
class QuizInput(BaseModel):
    student_name: str
    students_choice_of_exam: Optional[str] = None

@function_tool()
async def transfer_to_quiz(self, input: QuizInput) -> Agent:
    # access session context via self.session or self.chat_ctx
    ...
• Or keep the typed signature but add this to
UserData
as a quick unblock:
Copy code
from pydantic import ConfigDict
@dataclass
class UserData:
    ...
    model_config = ConfigDict(arbitrary_types_allowed=True)
Recommendation: change the signature to accept untyped
context
(first option). It’s the smallest change and preserves runtime behavior while avoiding the Pydantic/Gemini error. Would you like the exact patch/diff for your file?
s
if i keep the context it gave me this error 2025-11-24 120802,087 - INFO Aina-Voice Agent - [METRIC] llm_total_time=4.108s 2025-11-24 120802,087 - INFO Aina-Voice Agent - [METRIC] llm_streaming_time=0s (no tokens) 2025-11-24 120802,087 - ERROR livekit.agents - Error in _llm_inference_task Traceback (most recent call last): File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\livekit\plugins\google\llm.py", line 330, in _run function_declarations = to_fnc_ctx(self._tools) File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\livekit\plugins\google\utils.py", line 58, in to_fnc_ctx tools.append(_build_gemini_fnc(fnc, tool_behavior=tool_behavior)) File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\livekit\plugins\google\utils.py", line 131, in _build_gemini_fnc fnc = llm.utils.build_legacy_openai_schema(function_tool, internally_tagged=True) File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\livekit\agents\llm\utils.py", line 203, in build_legacy_openai_schema model = function_arguments_to_pydantic_model(function_tool) File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\livekit\agents\llm\utils.py", line 321, in function_arguments_to_pydantic_model type_hint = type_hints[param_name] KeyError: 'context' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\livekit\agents\llm\llm.py", line 190, in _main_task return await self._run() File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\livekit\plugins\google\llm.py", line 423, in _run raise APIConnectionError( livekit.agents._exceptions.APIConnectionError: gemini llm: error generating content 'context' (body=None, retryable=True) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\livekit\agents\utils\log.py", line 16, in async_fn_logs return await fn(*args, **kwargs) File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\opentelemetry\util\_decorator.py", line 71, in async_wrapper return await func(*args, **kwargs) # type: ignore File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\livekit\agents\voice\generation.py", line 125, in _llm_inference_task async for chunk in llm_node: File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\livekit\agents\voice\agent.py", line 402, in llm_node async for chunk in stream: File "C:\Intel_IL\AINA_voice_bot\AGENT\main.py", line 625, in timed_stream async for chunk in original_aiter: File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\livekit\agents\llm\llm.py", line 344, in anext raise exc # noqa: B904 File "C:\Intel_IL\AINA_voice_bot\AGENT\venv\lib\site-packages\opentelemetry\util\_decorator.py", line 71, in async_wrapper return await func(*args, **kwargs) # type: ignore File "C:\Intel_IL\AINA_voice_bot\AGENT\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
You're seeing two related problems: 1) Pydantic fails on the generic
RunContext[UserData]
, and 2) when you remove the type hint entirely the schema builder trips on a missing type for
"context"
(KeyError). Don't remove `context`; instead exclude it from the LLM-visible schema so runtime injection still works but schema generation skips it. Minimal fix — use Annotated + ExcludeFromSchema 1. Import Annotated and the ExcludeFromSchema marker:
Copy code
from typing import Annotated
from livekit.agents.llm import ExcludeFromSchema
from livekit.agents.events import RunContext
1. Update your tool signature:
Copy code
@function_tool()
async def transfer_to_quiz(
    self,
    context: Annotated[RunContext[UserData], ExcludeFromSchema]
) -> Agent:
    userdata = context.userdata
    ...
This tells LiveKit to skip
context
when building the Pydantic model for Gemini, preventing both the schema generation error and the KeyError. Optional safety: keep
UserData
tolerant If you still hit schema issues for other reasons, add this to
UserData
as a fast unblock:
Copy code
from pydantic import ConfigDict

@dataclass
class UserData:
    ...
    model_config = ConfigDict(arbitrary_types_allowed=True)
But prefer the Annotated+ExcludeFromSchema approach first. Would you like me to generate the exact diff for the file you showed? Sources: AI Agents Framework | livekit/livekit_composite | DeepWiki | Agents v0.x migration guide - Python | LiveKit docs | Tool definition and use | LiveKit docs
s
cant import ExcludeFromSchema error
t
Thanks — you're blocked because
ExcludeFromSchema
isn't available in your install. Two safe options: 1) Quick workaround (no special imports) • Keep
context
parameter but type it as plain
RunContext
(no generic) so schema builder can skip complex generics:
Copy code
from livekit.agents.events import RunContext

@function_tool()
async def transfer_to_quiz(self, context: RunContext) -> Agent:
    userdata = context.userdata
    ...
• Also add the
UserData
Pydantic tolerance to be safe:
Copy code
from pydantic import ConfigDict
@dataclass
class UserData:
    ...
    model_config = ConfigDict(arbitrary_types_allowed=True)
2) Preferred fix if your LiveKit version supports it • Use an explicit exclusion marker. If your package exposes it, import and use
Annotated
to exclude
context
from the LLM schema:
Copy code
from typing import Annotated
from livekit.agents.llm import ExcludeFromSchema
from livekit.agents.events import RunContext

@function_tool()
async def transfer_to_quiz(self, context: Annotated[RunContext[UserData], ExcludeFromSchema]) -> Agent:
    userdata = context.userdata
    ...
If
from livekit.agents.llm import ExcludeFromSchema
raises ImportError, that marker isn't present in your installed release. Which would you like to try first? If you want, tell me your livekit-agents and pydantic versions (
pip show livekit-agents pydantic
) and I’ll recommend the exact change. Sources: Company directory phone assistant | LiveKit Docs | Tool definition and use | LiveKit docs | Models | LiveKit Docs
s
i tried all 3 methods it is not working
t
I don't have the answer you're looking for. You could also try asking your question: • in one of the other Slack channels or • to https://deepwiki.com/livekit/livekit_composite which is trained on all LiveKit source code If you find the answer, please post it here to help others!