|
18 | 18 | from jsonschema.exceptions import SchemaError |
19 | 19 | from jsonschema.validators import Draft202012Validator as JSONValidator |
20 | 20 | from pydantic import ValidationError, create_model |
21 | | -from pydantic.alias_generators import to_pascal |
22 | 21 | from pydantic.fields import FieldInfo |
23 | 22 |
|
| 23 | +from camel.utils import PYDANTIC_V2, to_pascal |
| 24 | + |
24 | 25 |
|
25 | 26 | def _remove_a_key(d: Dict, remove_key: Any) -> None: |
26 | 27 | r"""Remove a key from a dictionary recursively.""" |
@@ -107,8 +108,13 @@ def _create_mol(name, field): |
107 | 108 | return create_model(name, **field) |
108 | 109 |
|
109 | 110 | model = _create_mol(to_pascal(func.__name__), fields) |
110 | | - parameters_dict = model.model_json_schema() |
111 | | - # The "title" is generated by model.model_json_schema() |
| 111 | + # NOTE: Method `.schema()` is deprecated in pydantic v2. |
| 112 | + # the result would be identical to `.model_json_schema()` in v2 |
| 113 | + if PYDANTIC_V2: |
| 114 | + parameters_dict = model.model_json_schema() # type: ignore |
| 115 | + else: |
| 116 | + parameters_dict = model.schema() # type: ignore |
| 117 | + # The `"title"` is generated by `model.model_json_schema()` |
112 | 118 | # but is useless for openai json schema |
113 | 119 | _remove_a_key(parameters_dict, "title") |
114 | 120 |
|
@@ -190,10 +196,23 @@ def validate_openai_tool_schema( |
190 | 196 | # Automatically validates whether the openai_tool_schema passed |
191 | 197 | # complies with the specifications of the ToolAssistantToolsFunction. |
192 | 198 | from openai.types.beta.threads.run import ToolAssistantToolsFunction |
193 | | - try: |
194 | | - ToolAssistantToolsFunction.model_validate(openai_tool_schema) |
195 | | - except ValidationError as e: |
196 | | - raise e |
| 199 | + |
| 200 | + # NOTE: Pydantic v1 does not have a strict mode to check input types |
| 201 | + # Below is a compromise solution. |
| 202 | + # refs: https://docs.pydantic.dev/1.10/blog/pydantic-v2/#strict-mode |
| 203 | + if PYDANTIC_V2: |
| 204 | + try: |
| 205 | + ToolAssistantToolsFunction.model_validate( # type: ignore |
| 206 | + openai_tool_schema) |
| 207 | + except ValidationError as e: |
| 208 | + raise e |
| 209 | + elif ToolAssistantToolsFunction( |
| 210 | + **openai_tool_schema) != openai_tool_schema: |
| 211 | + raise ValidationError( # type: ignore |
| 212 | + errors="Validation error for `ToolAssistantToolsFunction`." |
| 213 | + "Please check the input data types.", |
| 214 | + model=ToolAssistantToolsFunction, |
| 215 | + ) |
197 | 216 | # Check the function description |
198 | 217 | if not openai_tool_schema["function"]["description"]: |
199 | 218 | raise ValueError("miss function description") |
|
0 commit comments