My tools are built as @langChain tools. So, in ord...
# ask-ai
r
My tools are built as @langChain tools. So, in order to use them with LiveKit agent, I create the below wrapper. Fix the schema generation to expose actual parameters so the AI can read them correctly,
Copy code
# voice_agent/tools.py
from __future__ import annotations

import importlib
import inspect
import logging
from typing import Any, Dict, Iterable, List, Callable

import anyio
from livekit.agents import RunContext, function_tool

from .context_builder import RuntimeMock

logger = logging.getLogger(__name__)

# Service → module mapping for tools
SERVICE_TO_MODULES: Dict[str, List[str]] = {
    # Google
    "gmail": ["libs.services.gmail"],
    "google-calendar": ["libs.services.calendar"],
    "google-docs": ["libs.services.googledocs"],
    "google-drive": ["libs.services.googledrive"],
    "google-sheets": ["libs.services.googlesheets"],
    "google-slides": ["libs.services.googleslides"],
    "google-workspace": [
        "libs.services.gmail",
        "libs.services.calendar",
        "libs.services.googledocs",
        "libs.services.googledrive",
        "libs.services.googlesheets",
        "libs.services.googleslides",
    ],
    # Microsoft
    "outlook-mail": ["libs.services.microsoft.outlook_mail"],
    "outlook-calendar": ["libs.services.microsoft.outlook_calendar"],
    "teams": ["libs.services.microsoft.teams"],
    "microsoft-365": [
        "libs.services.microsoft.outlook_mail",
        "libs.services.microsoft.outlook_calendar",
        "libs.services.microsoft.teams",
    ],
    # Others
    "slack": ["libs.services.slack"],
    "clickup": ["libs.services.clickup"],
    "notion": ["libs.services.notion"],
    "zoho": ["libs.services.zoho"],
}

CORE_CONTEXT_MODULES: List[str] = [
    "libs.context.GET_user_context",
    "libs.context.GET_organization_context",
    "libs.context.GET_integrations_context",
    "libs.context.GET_contacts_context",
]


def _service_to_modules(connected: Iterable[str]) -> List[str]:
    out: List[str] = []
    for s in connected or []:
        ms = SERVICE_TO_MODULES.get((s or "").lower())
        if ms:
            out.extend(ms)
        else:
            guess = f"libs.services.{(s or '').lower().replace('-', '_')}"
            try:
                importlib.import_module(guess)
                out.append(guess)
            except Exception:
                logger.warning(f"[Voice] No module for service '{s}'")
    # de-dup preserve order
    seen = set()
    uniq = [m for m in out if not (m in seen or seen.add(m))]
    return uniq


def _load_module_tools(module_path: str) -> List[Any]:
    """
    Return a flat list of tools from a module.

    Priority:
      1) If SAFE_TOOLS or SENSITIVE_TOOLS exist, use the union of both.
      2) Else, use everything in __all__.
    """
    try:
        mod = importlib.import_module(module_path)
    except Exception as e:
        logger.warning(f"[Voice] Import failed: {module_path}: {e}")
        return []

    tools: List[Any] = []
    safe = list(getattr(mod, "SAFE_TOOLS", []) or [])
    sens = list(getattr(mod, "SENSITIVE_TOOLS", []) or [])
    tools.extend(safe)
    tools.extend(sens)

    if not tools:
        names = list(getattr(mod, "__all__", []) or [])
        for n in names:
            try:
                obj = getattr(mod, n)
                tools.append(obj)
            except Exception:
                continue

    logger.info(f"[Voice] {module_path}: tools={len(tools)}")
    return tools


def _dedup_tools(xs: List[Any]) -> List[Any]:
    seen = set()
    out: List[Any] = []
    for x in xs:
        if id(x) in seen:
            continue
        seen.add(id(x))
        out.append(x)
    return out


def collect_all_tools(connected_services: Iterable[str]) -> List[Any]:
    """
    Collect all tools from all modules for the connected services,
    plus core context tools, as a single flat list.
    """
    all_tools: List[Any] = []

    # Service-driven tools
    for mod in _service_to_modules(connected_services):
        all_tools.extend(_load_module_tools(mod))

    # Core context tools
    for module_path in CORE_CONTEXT_MODULES:
        all_tools.extend(_load_module_tools(module_path))

    logger.info(f"[Voice] All tools: {[x.name for x in all_tools]}")
    return _dedup_tools(all_tools)


def _tool_name(tool: Any) -> str:
    return getattr(tool, "name", None) or getattr(tool, "__name__", None) or "tool"


def _tool_desc(tool: Any) -> str:
    return getattr(tool, "description", None) or (
        tool.__doc__ or "" if hasattr(tool, "__doc__") else ""
    )


def build_tool_index(tools: List[Any]) -> Dict[str, Any]:
    idx: Dict[str, Any] = {}

    def _aliases(n: str):
        yield n
        yield n.lower()
        yield n.replace("-", "_")
        yield n.replace("_", "-")
        yield n.lower().replace("-", "_")
        yield n.lower().replace("_", "-")

    for t in tools:
        n = _tool_name(t)
        if not n:
            continue
        for a in _aliases(n):
            idx[a] = t
    return idx


async def _exec_tool(tool: Any, args: Dict[str, Any], runtime: RuntimeMock) -> Any:
    """Execute a tool with runtime context, compatible with LangChain @tool and plain callables."""
    target = getattr(tool, "coroutine", None) or getattr(tool, "func", None)

    if target is not None:
        if inspect.iscoroutinefunction(target):
            return await target(runtime=runtime, **args)
        return await anyio.to_thread.run_sync(lambda: target(runtime=runtime, **args))

    full_args = dict(args)
    full_args.setdefault("runtime", runtime)

    if hasattr(tool, "ainvoke"):
        return await tool.ainvoke(full_args)
    if hasattr(tool, "arun"):
        return await tool.arun(runtime=runtime, **args)

    def _sync():
        if hasattr(tool, "invoke"):
            return tool.invoke(full_args)
        if hasattr(tool, "run"):
            return tool.run(runtime=runtime, **args)
        return tool(runtime=runtime, **args)

    return await anyio.to_thread.run_sync(_sync)


def make_wrapper(name: str, desc: str) -> Callable:
    """
    Create a LiveKit function_tool wrapper around a single underlying tool.
    """
    schema = {
        "type": "function",
        "name": name,
        "description": desc or f"Run {name}",
        "parameters": {
            "type": "object",
            "properties": {
                "raw_args": {
                    "type": "object",
                    "additionalProperties": True,
                    "description": "Arguments for the underlying tool.",
                }
            },
            "required": ["raw_args"],
        },
    }

    @function_tool(raw_schema=schema)
    async def wrapper(raw_arguments: dict, context: RunContext):
        userdata = context.userdata or {}
        runtime: RuntimeMock = userdata.get("runtime")
        tool_index: Dict[str, Any] = userdata.get("tool_index") or {}

        candidates = [
            name,
            name.lower(),
            name.replace("-", "_"),
            name.replace("_", "-"),
            name.lower().replace("-", "_"),
            name.lower().replace("_", "-"),
        ]
        key = next((k for k in candidates if k in tool_index), None)
        logger.info(f"[Voice] Resolved alias for {name}: key={key}")

        if not key:
            return {"error": f"Tool '{name}' not found."}

        try:
            result = await _exec_tool(tool_index[key], raw_arguments, runtime)
            logger.info(f"[Voice] Voice Agent Result: {result}")
            return {"result": result}
        except Exception as e:
            logger.error(f"[Voice] Error executing tool {name}: {e}")
            return {"error": str(e)}

    return wrapper
t
Thanks for reaching out, Roaa. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'm here to help you get your schema generation working smoothly in your LiveKit agent wrapper and make sure the actual parameters for LangChain tools are properly exposed. Here's a friendly step-by-step guide to walk you through it: 1. Tool Type Detection: Try using utilities like
is_function_tool
and
is_raw_function_tool
to identify the tool type. This way, you can handle its schema just right. 2. Pydantic Model Generation: The
function_arguments_to_pydantic_model
utility is super helpful to turn function signatures into Pydantic models. Just double-check that all your function parameters have clear type annotations. 3. Schema Validation: Once you have the Pydantic model, pull out the JSON schema and give it a good look to make sure all required parameters are there and everything looks solid. 4. Dynamic Tool Creation: For tools that are dynamic, you can map the schema parameters to function arguments using Python's
inspect
module. It’s a neat way to keep things flexible. 5. Debugging: If you run into any hiccups like missing parameters or type mismatches, adding some logging can really help you track down what’s going on. Please feel free to reach out if you'd like me to walk you through any of these steps in more detail or provide some examples. I'm happy to help! Sources: mcp_client/agent_tools.py | livekit-agents/livekit/agents/inference/llm.py | Tool definition and use | LiveKit docs
r
provide the code please
t
Here is the code to fix the schema generation in your LiveKit agent wrapper:
Copy code
from livekit.agents.llm.tool_context import (
    get_function_info,
    get_raw_function_info,
    is_function_tool,
    is_raw_function_tool,
)
from livekit.agents.llm.utils import function_arguments_to_pydantic_model

def process_tool_schema(tool):
    if is_raw_function_tool(tool):
        # Handle raw function tools
        raw_fnc_info = get_raw_function_info(tool)
        name = raw_fnc_info.name
        description = raw_fnc_info.raw_schema.get("description", None)
        parameters = raw_fnc_info.raw_schema.get("parameters", {})
    elif is_function_tool(tool):
        # Handle regular function tools
        fnc_info = get_function_info(tool)
        model = function_arguments_to_pydantic_model(tool)
        name = fnc_info.name
        description = fnc_info.description
        parameters = model.model_json_schema()
    
    return name, description, parameters

def function_arguments_to_pydantic_model(func: Callable[..., Any]) -> type[BaseModel]:
    """Create a Pydantic model from a function's signature."""
    from docstring_parser import parse_from_object

    fnc_names = func.__name__.split("_")
    fnc_name = "".join(x.capitalize() for x in fnc_names)
    model_name = fnc_name + "Args"

    docstring = parse_from_object(func)
    param_docs = {p.arg_name: p.description for p in docstring.params}

    signature = inspect.signature(func)
    type_hints = get_type_hints(func, include_extras=True)

    fields: dict[str, Any] = {}

    for param_name, param in signature.parameters.items():
        type_hint = type_hints[param_name]

        if is_context_type(type_hint):
            continue

        default_value = param.default if param.default is not param.empty else ...
        field_info = Field()

        if get_origin(type_hint) is Annotated:
            annotated_args = get_args(type_hint)
            type_hint = annotated_args[0]
            field_info = next(
                (x for x in annotated_args[1:] if isinstance(x, FieldInfo)), field_info
            )

        if default_value is not ... and field_info.default is PydanticUndefined:
            field_info.default = default_value

        if field_info.description is None:
            field_info.description = param_docs.get(param_name, None)

        fields[param_name] = (type_hint, field_info)

    return create_model(model_name, **fields)

def extract_and_validate_schema(tool):
    name, description, parameters = process_tool_schema(tool)

    if "properties" not in parameters:
        raise ValueError(f"Schema for tool '{name}' missing 'properties' field")

    required_params = parameters.get("required", [])
    properties = parameters.get("properties", {})

    for param_name in required_params:
        if param_name not in properties:
            raise ValueError(f"Required parameter '{param_name}' not found in properties")

    return {
        "name": name,
        "description": description,
        "parameters": parameters
    }
This code includes functions for processing tool schemas, generating Pydantic models, and validating schemas. If you have any questions or would like me to walk you through any part of it, please don’t hesitate to ask. I’m here to help you get this working smoothly!