Skip to content

default value for function tool argument doesn't work for some types #1987

Closed

Description

@longcw

Create an ticket to track this issue:

I was not able to create a tool with default argument like

    @function_tool
    async def get_weather(self, location: str = "") -> str:
        """
        Called when the user asks about the weather.

        Args:
            location: The location to get the weather for
        """

OAI raises error Invalid schema for function 'get_weather': In context=('properties', 'location'), 'default' is not permitted.

2025-04-11 15:01:20,350 - WARNING livekit.agents - failed to generate LLM completion, retrying in 2.0s
Traceback (most recent call last):
  File "/home/longc/data/code/agents/livekit-agents/livekit/agents/llm/llm.py", line 137, in _main_task
    return await self._run()
           ^^^^^^^^^^^^^^^^^
  File "/home/longc/data/code/agents/livekit-plugins/livekit-plugins-openai/livekit/plugins/openai/llm.py", line 599, in _run
    raise APIStatusError(
livekit.agents._exceptions.APIStatusError: Error code: 400 - {'error': {'message': "Invalid schema for function 'get_weather': In context=('properties', 'location'), 'default' is not permitted.", 'type': 'invalid_request_error', 'param': 'tools[0].function.parameters', 'code': 'invalid_function_parameters'}} (status_code=400, request_id=req_6da84b4da8310ea5c55054fa50e9113e, body={'message': "Invalid schema for function 'get_weather': In context=('properties', 'location'), 'default' is not permitted.", 'type': 'invalid_request_error', 'param': 'tools[0].function.parameters', 'code': 'invalid_function_parameters'})

But something like this works, seems it has to be an enum to have the default value?

    @function_tool
    async def toggle_light(
        self,
        switch_to: Literal["on", "off"] = "on",
    ) -> str:
        ...

their schemas are

# failed
{'properties': {'location': {'default': 'New York', 'description': 'The location to get the weather for', 'title': 'Location', 'type': 'string'}}, 'title': 'GetWeatherArgs', 'type': 'object', 'additionalProperties': False, 'required': ['location']}

# succ
{'properties': {'switch_to': {'default': 'on', 'description': 'The state to turn the light to', 'enum': ['on', 'off'], 'title': 'Switch To', 'type': 'string'}}, 'title': 'ToggleLightArgs', 'type': 'object', 'additionalProperties': False, 'required': ['switch_to']}

also, can we remove the arg from required if it has a default value?

Activity

  1. added
    bug
    on Apr 14, 2025
  2. changed the title [-]default value for function tool argument mark require to False[/-] [+]default value for function tool argument doesn't work for some types[/+] on Apr 14, 2025
  3. nickderobertis commented on Apr 21, 2025

    @nickderobertis

    We are running into this as well and it's preventing us from upgrading to 1.0. We noticed that it can be reproduced with the weather example by adding an additional arg. Note that it seems to only affect LLM and not RealtimeModel, if you use this same script with RealtimeModel it works fine.

    import logging
    
    import aiohttp
    from dotenv import load_dotenv
    
    from livekit.agents import JobContext, WorkerOptions, cli
    from livekit.agents.llm import function_tool
    from livekit.agents.voice import Agent, AgentSession
    from livekit.agents.voice.room_io import RoomInputOptions, RoomOutputOptions
    from livekit.plugins import openai, deepgram, silero, cartesia
    
    logger = logging.getLogger("weather-example")
    logger.setLevel(logging.INFO)
    
    load_dotenv()
    
    
    class WeatherAgent(Agent):
        def __init__(self) -> None:
            super().__init__(
                instructions="You are a weather agent.",
                stt=deepgram.STT(),
                llm=openai.LLM(model="gpt-4o-mini"),
                tts=cartesia.TTS(),
                vad=silero.VAD.load(),
            )
    
        @function_tool
        async def get_weather(
            self,
            latitude: str,
            longitude: str,
            not_actually_needed_argument: str = "not needed",
        ):
            """Called when the user asks about the weather. This function will return the weather for
            the given location. When given a location, please estimate the latitude and longitude of the
            location and do not ask the user for them.
    
            Args:
                latitude: The latitude of the location
                longitude: The longitude of the location
                not_actually_needed_argument: An argument that is not actually needed
            """
    
            logger.info(f"getting weather for {latitude}, {longitude}")
            url = f"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}&current=temperature_2m"
            weather_data = {}
            async with aiohttp.ClientSession() as session:
                async with session.get(url) as response:
                    if response.status == 200:
                        data = await response.json()
                        # response from the function call is returned to the LLM
                        weather_data = {
                            "temperature": data["current"]["temperature_2m"],
                            "temperature_unit": "Celsius",
                        }
                    else:
                        raise Exception(
                            f"Failed to get weather data, status code: {response.status}"
                        )
    
            return weather_data
    
    
    async def entrypoint(ctx: JobContext):
        await ctx.connect()
        # each log entry will include these fields
        ctx.log_context_fields = {
            "room_name": ctx.room.name,
            "user_id": "your user_id",
        }
    
        session = AgentSession()
    
        await session.start(
            agent=WeatherAgent(),
            room=ctx.room,
            room_input_options=RoomInputOptions(),
            room_output_options=RoomOutputOptions(transcription_enabled=True),
        )
    
    
    if __name__ == "__main__":
        cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
  4. self-assigned this
    on Apr 21, 2025
  5. blakemjones commented on May 1, 2025

    @blakemjones

    I've upgraded to livekit-agents==1.0.18 and validated that the code trying to fix this is installed locally, but I'm still getting the following error message:

    livekit.agents._exceptions.APIStatusError: Error code: 400 - {'error': {'message': "Invalid schema for function 'collect_demographic_information': In context=('properties', 'patient_preferred_name'), 'default' is not permitted.", 'type': 'invalid_request_error', 'param': 'tools[0].function.parameters', 'code': 'invalid_function_parameters'}} (status_code=400, request_id=req_556615444828c36af8bddc99704e76c3, body={'message': "Invalid schema for function 'collect_demographic_information': In context=('properties', 'patient_preferred_name'), 'default' is not permitted.", 'type': 'invalid_request_error', 'param': 'tools[0].function.parameters', 'code': 'invalid_function_parameters'})
    

    This is my tool definition:

    @function_tool()
        async def collect_demographic_information(
                self,
                patient_first_name: str,
                patient_last_name: str,
                patient_date_of_birth: str,
                patient_demographic_race: DemographicRace,
                patient_demographic_ethnicity: DemographicEthnicity,
                patient_preferred_name: Optional[str] = None,
        ) -> dict:
            """Collect the patient's demographic information.
    
            Args:
                patient_first_name: The patient's legal first name.
                patient_last_name: The patient's legal last name.
                patient_date_of_birth: The patient's date of birth.
                patient_demographic_race: The patient's demographic race.
                patient_demographic_ethnicity: The patient's demographic ethnicity.
                patient_preferred_name: The patient's preferred name.
            """
            demographic_information = {
                "patient_first_name": patient_first_name,
                "patient_last_name": patient_last_name,
                "patient_date_of_birth": patient_date_of_birth,
                "patient_demographic_race": patient_demographic_race.value,
                "patient_demographic_ethnicity": patient_demographic_ethnicity.value,
                "patient_preferred_name": patient_preferred_name,
            }
            return demographic_information
    

    After running the debugger, I found that the patient_preferred_name was still set with a default key at livekit/agents/llm/utils.py:209 in the build_strict_openai_schema method and that the line in _strict.py:111 in _ensure_strict_json_schema never gets hit.

    This is because your check for the "default" key is dependent on the value, I've left a comment on your PR.

    One more note: the description for this optional parameter isn't getting populated. I'm not sure why yet, looking into it.

    Thank you!

  6. theomonnom commented on May 3, 2025

    @theomonnom
    Member

    Thanks for the report @blakemjones, done here #2187 !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions