mirror of
https://github.com/livekit/agents.git
synced 2026-12-06 04:38:33 +00:00
381 lines
13 KiB
Python
381 lines
13 KiB
Python
import datetime
|
||
from typing import Literal
|
||
|
||
import pytest
|
||
from google.genai import types
|
||
from pydantic import BaseModel, Field
|
||
|
||
from livekit.agents import llm
|
||
from livekit.agents.llm import function_tool
|
||
from livekit.plugins.google import utils
|
||
|
||
pytestmark = pytest.mark.unit
|
||
|
||
# Gemini Schema Tests
|
||
|
||
|
||
# Test for inlining $ref definitions
|
||
async def test_json_def_replaced():
|
||
class Location(BaseModel):
|
||
lat: float
|
||
lng: float = 1.1
|
||
|
||
class Locations(BaseModel):
|
||
locations: list[Location]
|
||
|
||
json_schema = Locations.model_json_schema()
|
||
# Original schema with $defs as produced by Pydantic.
|
||
expected_schema = {
|
||
"$defs": {
|
||
"Location": {
|
||
"properties": {
|
||
"lat": {"title": "Lat", "type": "number"},
|
||
"lng": {"default": 1.1, "title": "Lng", "type": "number"},
|
||
},
|
||
"required": ["lat"],
|
||
"title": "Location",
|
||
"type": "object",
|
||
}
|
||
},
|
||
"properties": {
|
||
"locations": {
|
||
"items": {"$ref": "#/$defs/Location"},
|
||
"title": "Locations",
|
||
"type": "array",
|
||
}
|
||
},
|
||
"required": ["locations"],
|
||
"title": "Locations",
|
||
"type": "object",
|
||
}
|
||
assert json_schema == expected_schema
|
||
|
||
gemini_schema = utils._GeminiJsonSchema(json_schema).simplify()
|
||
|
||
expected_gemini_schema = {
|
||
"properties": {
|
||
"locations": {
|
||
"items": {
|
||
"properties": {
|
||
"lat": {"type": types.Type.NUMBER},
|
||
"lng": {"type": types.Type.NUMBER},
|
||
},
|
||
"property_ordering": ["lat", "lng"],
|
||
"required": ["lat"],
|
||
"type": types.Type.OBJECT,
|
||
},
|
||
"type": types.Type.ARRAY,
|
||
}
|
||
},
|
||
"property_ordering": ["locations"],
|
||
"required": ["locations"],
|
||
"type": types.Type.OBJECT,
|
||
}
|
||
assert gemini_schema == expected_gemini_schema
|
||
|
||
|
||
# Test for handling anyOf (optional field)
|
||
async def test_json_def_replaced_any_of():
|
||
class Location(BaseModel):
|
||
lat: float
|
||
lng: float
|
||
|
||
class Locations(BaseModel):
|
||
op_location: Location | None = None
|
||
|
||
json_schema = Locations.model_json_schema()
|
||
|
||
gemini_schema = utils._GeminiJsonSchema(json_schema).simplify()
|
||
|
||
# The anyOf containing the Location ref and {"type": "null"} is merged,
|
||
# so op_location becomes the inlined Location with "nullable": True.
|
||
expected_gemini_schema = {
|
||
"properties": {
|
||
"op_location": {
|
||
"properties": {
|
||
"lat": {"type": types.Type.NUMBER},
|
||
"lng": {"type": types.Type.NUMBER},
|
||
},
|
||
"property_ordering": ["lat", "lng"],
|
||
"required": ["lat", "lng"],
|
||
"type": types.Type.OBJECT,
|
||
"nullable": True,
|
||
}
|
||
},
|
||
"property_ordering": ["op_location"],
|
||
"type": types.Type.OBJECT,
|
||
}
|
||
assert gemini_schema == expected_gemini_schema
|
||
|
||
|
||
# Test for recursive $ref – should raise ValueError
|
||
async def test_json_def_recursive():
|
||
class Location(BaseModel):
|
||
lat: float
|
||
lng: float
|
||
nested_locations: list["Location"]
|
||
|
||
Location.model_rebuild()
|
||
json_schema = Location.model_json_schema()
|
||
expected_schema = {
|
||
"$defs": {
|
||
"Location": {
|
||
"properties": {
|
||
"lat": {"title": "Lat", "type": "number"},
|
||
"lng": {"title": "Lng", "type": "number"},
|
||
"nested_locations": {
|
||
"items": {"$ref": "#/$defs/Location"},
|
||
"title": "Nested Locations",
|
||
"type": "array",
|
||
},
|
||
},
|
||
"required": ["lat", "lng", "nested_locations"],
|
||
"title": "Location",
|
||
"type": "object",
|
||
}
|
||
},
|
||
"$ref": "#/$defs/Location",
|
||
}
|
||
assert json_schema == expected_schema
|
||
|
||
with pytest.raises(
|
||
ValueError,
|
||
match=r"Recursive `\$ref`s in JSON Schema are not supported by Gemini",
|
||
):
|
||
utils._GeminiJsonSchema(json_schema).simplify()
|
||
|
||
|
||
# Test for preserving format, and description on string fields
|
||
async def test_json_def_date():
|
||
class FormattedStringFields(BaseModel):
|
||
d: datetime.date
|
||
dt: datetime.datetime
|
||
t: datetime.time = Field(description="")
|
||
td: datetime.timedelta = Field(description="my timedelta")
|
||
|
||
json_schema = FormattedStringFields.model_json_schema()
|
||
expected_schema = {
|
||
"properties": {
|
||
"d": {"format": "date", "title": "D", "type": "string"},
|
||
"dt": {"format": "date-time", "title": "Dt", "type": "string"},
|
||
"t": {"format": "time", "title": "T", "type": "string", "description": ""},
|
||
"td": {
|
||
"format": "duration",
|
||
"title": "Td",
|
||
"type": "string",
|
||
"description": "my timedelta",
|
||
},
|
||
},
|
||
"required": ["d", "dt", "t", "td"],
|
||
"title": "FormattedStringFields",
|
||
"type": "object",
|
||
}
|
||
assert json_schema == expected_schema
|
||
|
||
gemini_schema = utils._GeminiJsonSchema(json_schema).simplify()
|
||
expected_gemini_schema = {
|
||
"properties": {
|
||
"d": {"format": "date", "type": types.Type.STRING},
|
||
"dt": {"format": "date-time", "type": types.Type.STRING},
|
||
"t": {
|
||
"format": "time",
|
||
"type": types.Type.STRING,
|
||
"description": "",
|
||
},
|
||
"td": {
|
||
"format": "duration",
|
||
"type": types.Type.STRING,
|
||
"description": "my timedelta",
|
||
},
|
||
},
|
||
"property_ordering": ["d", "dt", "t", "td"],
|
||
"required": ["d", "dt", "t", "td"],
|
||
"type": types.Type.OBJECT,
|
||
}
|
||
assert gemini_schema == expected_gemini_schema
|
||
|
||
|
||
# FunctionTool: Gemini FunctionDeclaration tests
|
||
|
||
|
||
@function_tool
|
||
async def save_contact(fields: dict[str, str]) -> None:
|
||
"""Save the contact fields gathered in the conversation (free-form keys)."""
|
||
|
||
|
||
@function_tool
|
||
async def ping() -> None:
|
||
"""A tool without parameters."""
|
||
|
||
|
||
class DecisionDetails(BaseModel):
|
||
zeta: str
|
||
alpha: str
|
||
|
||
|
||
@function_tool
|
||
async def decide(reasoning: str, answer: Literal["a", "b"], details: DecisionDetails) -> None:
|
||
"""Reason first, then answer."""
|
||
|
||
|
||
# Test for Gemini Text API. It should emit parameters_json_schema
|
||
async def test_function_tool_uses_parameters_json_schema_on_text_api():
|
||
[schema] = llm.ToolContext([save_contact]).parse_function_tools("google")
|
||
|
||
assert "parameters" not in schema
|
||
fields = schema["parameters_json_schema"]["properties"]["fields"]
|
||
assert fields["type"] == "object"
|
||
assert fields["additionalProperties"] == {"type": "string"}
|
||
assert schema["parameters_json_schema"]["required"] == ["fields"]
|
||
|
||
decl = types.FunctionDeclaration.model_validate(schema)
|
||
assert decl.parameters is None
|
||
assert decl.parameters_json_schema is not None
|
||
|
||
|
||
# Test for Gemini Live API. It should keep the simplified legacy parameters
|
||
async def test_function_tool_uses_legacy_parameters_on_live_api():
|
||
[schema] = llm.ToolContext([save_contact]).parse_function_tools(
|
||
"google", use_parameters_json_schema=False
|
||
)
|
||
|
||
assert "parameters_json_schema" not in schema
|
||
assert schema["parameters"] == {
|
||
"type": types.Type.OBJECT,
|
||
"properties": {"fields": {"type": types.Type.OBJECT}},
|
||
"required": ["fields"],
|
||
"property_ordering": ["fields"],
|
||
}
|
||
types.FunctionDeclaration.model_validate(schema)
|
||
|
||
|
||
async def test_function_tool_orders_live_api_parameters_as_declared():
|
||
tools, _ = utils.create_tools_config(
|
||
llm.ToolContext([decide]), use_parameters_json_schema=False
|
||
)
|
||
|
||
declarations = tools[0].function_declarations
|
||
assert declarations is not None
|
||
parameters = declarations[0].parameters
|
||
assert parameters is not None
|
||
assert parameters.property_ordering == ["reasoning", "answer", "details"]
|
||
assert parameters.properties is not None
|
||
assert parameters.properties["details"].property_ordering == ["zeta", "alpha"]
|
||
|
||
|
||
@pytest.mark.parametrize("key", ["propertyOrdering", "property_ordering"])
|
||
async def test_raw_tool_keeps_explicit_property_ordering_on_live_api(key: str):
|
||
@function_tool(
|
||
raw_schema={
|
||
"name": "order",
|
||
"description": "A raw tool with an explicit property order.",
|
||
"parameters": {
|
||
"type": "object",
|
||
"properties": {"a": {"type": "string"}, "b": {"type": "string"}},
|
||
key: ["b", "a"],
|
||
},
|
||
}
|
||
)
|
||
async def order(raw_arguments: dict[str, object]) -> None: ...
|
||
|
||
tools, _ = utils.create_tools_config(llm.ToolContext([order]), use_parameters_json_schema=False)
|
||
|
||
declarations = tools[0].function_declarations
|
||
assert declarations is not None
|
||
parameters = declarations[0].parameters
|
||
assert parameters is not None
|
||
assert parameters.property_ordering == ["b", "a"]
|
||
|
||
|
||
# Test for a FunctionTool with no parameters. Both APIs should omit the schema
|
||
async def test_function_tool_without_parameters():
|
||
[text_schema] = llm.ToolContext([ping]).parse_function_tools("google")
|
||
assert "parameters_json_schema" not in text_schema
|
||
assert "parameters" not in text_schema
|
||
|
||
[live_schema] = llm.ToolContext([ping]).parse_function_tools(
|
||
"google", use_parameters_json_schema=False
|
||
)
|
||
assert "parameters" not in live_schema
|
||
assert "parameters_json_schema" not in live_schema
|
||
|
||
|
||
# #7349: JSON Schema annotation keywords that a real MCP server emits are legal input
|
||
# but reach types.FunctionDeclaration, whose Schema model is declared extra="forbid".
|
||
|
||
|
||
async def test_unknown_schema_keywords_are_dropped():
|
||
schema = {
|
||
"type": "object",
|
||
"properties": {
|
||
"view": {
|
||
"type": "string",
|
||
"enum": ["THREAD_VIEW_UNSPECIFIED", "THREAD_VIEW_MINIMAL"],
|
||
"x-google-enum-descriptions": ["a", "b"],
|
||
},
|
||
"limit": {"type": "integer", "readOnly": True, "deprecated": True},
|
||
},
|
||
"required": ["view"],
|
||
}
|
||
params = utils._GeminiJsonSchema(schema).simplify()
|
||
assert "x-google-enum-descriptions" not in params["properties"]["view"]
|
||
types.FunctionDeclaration.model_validate(
|
||
{"name": "search_threads", "description": "", "parameters": params}
|
||
)
|
||
|
||
|
||
async def test_unknown_keyword_inside_ref_definition_is_dropped():
|
||
schema = {
|
||
"type": "object",
|
||
"properties": {
|
||
"attachments": {"type": "array", "items": {"$ref": "#/$defs/Attachment"}},
|
||
},
|
||
"$defs": {
|
||
"Attachment": {
|
||
"type": "object",
|
||
"properties": {"id": {"type": "string", "readOnly": True}},
|
||
}
|
||
},
|
||
}
|
||
params = utils._GeminiJsonSchema(schema).simplify()
|
||
types.FunctionDeclaration.model_validate(
|
||
{"name": "create_draft", "description": "", "parameters": params}
|
||
)
|
||
|
||
|
||
# `const` is not a types.Schema field either, but unlike the keywords above the
|
||
# transformer itself consumes it: it converts a literal into the single-value `enum`
|
||
# Gemini does support. Dropping it before that conversion would silently widen the
|
||
# parameter to any value of its type.
|
||
async def test_const_becomes_a_single_value_enum():
|
||
schema = {
|
||
"type": "object",
|
||
"properties": {
|
||
"mode": {"type": "string", "const": "only", "readOnly": True},
|
||
},
|
||
"required": ["mode"],
|
||
}
|
||
params = utils._GeminiJsonSchema(schema).simplify()
|
||
assert params["properties"]["mode"] == {"type": types.Type.STRING, "enum": ["only"]}
|
||
types.FunctionDeclaration.model_validate(
|
||
{"name": "run", "description": "", "parameters": params}
|
||
)
|
||
|
||
|
||
def _raw_tool(name: str, parameters: dict) -> llm.RawFunctionTool:
|
||
return function_tool(
|
||
lambda raw_arguments: None,
|
||
raw_schema={"name": name, "description": "d", "parameters": parameters},
|
||
)
|
||
|
||
|
||
# Test that a declaration Gemini rejects names the tool it came from
|
||
async def test_rejected_tool_names_itself():
|
||
# minLength is a Schema field, so it reaches validation whatever the transformer drops
|
||
bad = _raw_tool(
|
||
"bad", {"type": "object", "properties": {"a": {"type": "string", "minLength": "many"}}}
|
||
)
|
||
|
||
with pytest.raises(ValueError, match="tool bad has a schema Gemini rejected"):
|
||
utils.create_tools_config(llm.ToolContext([bad]), use_parameters_json_schema=False)
|