Am looking at writing a fucntion tool that can tak...
# ask-ai
e
Am looking at writing a fucntion tool that can take complex types is this possible
Copy code
@function_tool
@observe()
async def send_template_data(
    context: RunContext[SessionState],
    template_data: Annotated[
        dict[str, Any],
        TypeInfo(
            description="Dictionary containing structured data matching the lesson's template_schema. For example: {'got_it_right': true, 'accuracy_percentage': 85, 'comments_for_improvement': '...'}",
        ),
    ],
):
t
Thanks for reaching out, Brian. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm happy to share that LiveKit function tools can indeed handle complex types like dictionaries with annotations and type information. There are two main ways to approach this: • Using Python Type Hints: You can define your arguments with Python type hints, like
dict[str, Any]
, and incorporate
Annotated
types to add metadata about the arguments. This helps the system understand structured input requirements, including nested objects and specific data constraints. • Using Raw JSON Schema: If you'd like more control, you can define tools using a raw JSON schema through the
raw_schema
parameter in the
@function_tool
decorator. This approach lets you explicitly specify complex input structures, such as dictionaries with detailed property definitions, nested objects, and required fields. Both of these methods are great for working effectively with structured data. If you'd like, I’m here to provide more details or walk you through some examples to help you get started! Sources: Tool definition and use | LiveKit docs | livekit-agents/livekit/agents/llm/utils.py | mcp_client/agent_tools.py
e
give me examples
t
I'd love to share some helpful examples of how LiveKit function tools can work with complex types. Let's walk through them together: • Using Python Type Hints: You can define arguments using Python type hints and annotations. Here's a friendly example:
Copy code
@function_tool
@observe()
async def send_template_data(
    context: RunContext[SessionState],
    template_data: Annotated[
        dict[str, Any],
        TypeInfo(
            description="Dictionary containing structured data matching the lesson's template_schema. For example: {'got_it_right': true, 'accuracy_percentage': 85, 'comments_for_improvement': '...'}",
        ),
    ],
):
    pass
• Using Raw JSON Schema: If you want a bit more control, you can define tools using a raw JSON schema. Here's how you might do it:
Copy code
raw_schema = {
    "type": "function",
    "name": "get_weather",
    "description": "Get weather for a given location.",
    "parameters": {
        "type": "object",
        "properties": {
            "location": {"type": "string", "description": "City and country e.g. New York"}
        },
        "required": ["location"],
        "additionalProperties": False
    }
}

@function_tool(raw_schema=raw_schema)
async def get_weather(raw_arguments: dict[str, object], context: RunContext):
    location = raw_arguments["location"]
    return f"The weather of {location} is ..."
If you're interested in exploring more, here are some great examples you can check out: • Annotated Tool Arguments Example • Raw JSON Schema Example • Dynamic Tool Creation Example Please feel free to reach out if you'd like me to clarify anything or provide more examples—I'm here to help! Sources: livekit-plugins/livekit-plugins-anthropic/livekit/plugins/anthropic/utils.p... | Tool definition and use | LiveKit docs | mcp_client/agent_tools.py
e
would there be any issues if I just use primitives and designing the prompt to handle the json?
t
I'm glad you're exploring using primitives and designing prompts to handle JSON in LiveKit! It’s a powerful approach, but there are a few things to keep in mind to make your experience smoother: • Malformed JSON: Sometimes, the LLM might generate JSON that’s incomplete or not quite valid, which can cause errors when invoking tools. • Deserialization Errors: If the JSON string from the LLM can’t be parsed properly, the tool execution might fail. The good news is that the system is designed to handle these errors gracefully. • Serialization Issues: It’s important that tool return values are JSON-serializable. If you use non-serializable data like custom objects, it might lead to errors or unexpected string outputs. • Inconsistent Type Hints: Missing or incorrect type annotations can throw off the JSON schemas, which might confuse the LLM and result in invalid tool calls. To help avoid these hiccups, I recommend double-checking your type annotations for tool arguments, validating your JSON structures within prompts, and making sure your return values can be serialized to JSON. If you’d like, I’m here to walk you through any of these steps—just let me know! Sources: tests/test-chat.cpp | mcp_client/util.py | Tool definition and use | LiveKit docs
e
How do I update the state from the function tool. i believe I can access but what is the right way to do this
t
To update the state from a function tool in LiveKit, a great way to handle this is by using the
RunContext
and
UserData
for managing persistent state. Let me walk you through how you can do it: • Define a UserData Class: Start by creating a dataclass to keep track of your session-level state. Here's an example:
Copy code
from dataclasses import dataclass, field
from typing import List, Dict, Any

@dataclass
class UserData:
    user_name: str = ""
    task_list: List[str] = field(default_factory=list)
• Access and Modify State in Function Tools: You can update the state easily by using
context.userdata
. For instance:
Copy code
@function_tool
async def add_task(self, task: str, context: RunContext[UserData]):
    context.userdata.task_list.append(task)
    return f"Task '{task}' added. Total tasks: {len(context.userdata.task_list)}"
• Update Room Attributes: If you want, you can also update room-level attributes like this:
Copy code
await context.userdata.ctx.room.local_participant.set_attributes({
    "task_count": str(len(context.userdata.task_list))
})
This method helps keep your state persistent and available across different function calls. If anything is unclear or you'd like me to provide more examples, just let me know—I'm here to help! Sources: context-readmes/USERDATA_GUIDE.md | livekit-plugins/livekit-plugins-ultravox/livekit/plugins/ultravox/realtime/... | Tool definition and use | LiveKit docs