Spaces:
Runtime error
Runtime error
File size: 1,969 Bytes
ef60d00 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | from __future__ import annotations
from typing import Any, Dict, cast
import pydantic
from ._pydantic import to_strict_json_schema
from ..types.chat import ChatCompletionFunctionToolParam
from ..types.shared_params import FunctionDefinition
from ..types.responses.function_tool_param import FunctionToolParam as ResponsesFunctionToolParam
class PydanticFunctionTool(Dict[str, Any]):
"""Dictionary wrapper so we can pass the given base model
throughout the entire request stack without having to special
case it.
"""
model: type[pydantic.BaseModel]
def __init__(self, defn: FunctionDefinition, model: type[pydantic.BaseModel]) -> None:
super().__init__(defn)
self.model = model
def cast(self) -> FunctionDefinition:
return cast(FunctionDefinition, self)
class ResponsesPydanticFunctionTool(Dict[str, Any]):
model: type[pydantic.BaseModel]
def __init__(self, tool: ResponsesFunctionToolParam, model: type[pydantic.BaseModel]) -> None:
super().__init__(tool)
self.model = model
def cast(self) -> ResponsesFunctionToolParam:
return cast(ResponsesFunctionToolParam, self)
def pydantic_function_tool(
model: type[pydantic.BaseModel],
*,
name: str | None = None, # inferred from class name by default
description: str | None = None, # inferred from class docstring by default
) -> ChatCompletionFunctionToolParam:
if description is None:
# note: we intentionally don't use `.getdoc()` to avoid
# including pydantic's docstrings
description = model.__doc__
function = PydanticFunctionTool(
{
"name": name or model.__name__,
"strict": True,
"parameters": to_strict_json_schema(model),
},
model,
).cast()
if description is not None:
function["description"] = description
return {
"type": "function",
"function": function,
}
|