maitai-python 1.2.6b0__py3-none-any.whl → 1.2.7__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
maitai/_maitai.py CHANGED
@@ -28,11 +28,11 @@ from maitai._types import (
28
28
  ToolFunction,
29
29
  )
30
30
  from maitai._utils import (
31
- OpenAISchemaGenerator,
32
31
  convert_open_ai_chat_completion_chunk,
33
32
  convert_openai_chat_completion,
34
33
  get_chat_completion_params,
35
34
  required_args,
35
+ type_to_response_format_param,
36
36
  )
37
37
  from maitai.tools import Tools
38
38
  from maitai_gen.chat import (
@@ -427,9 +427,7 @@ class Completions:
427
427
  if hasattr(response_format, "model_json_schema"):
428
428
  response_format = {
429
429
  "type": "json_schema",
430
- "json_schema": response_format.model_json_schema(
431
- schema_generator=OpenAISchemaGenerator, mode="serialization"
432
- ),
430
+ "json_schema": type_to_response_format_param(response_format),
433
431
  }
434
432
  response = self._client.chat.completions.create(
435
433
  messages=messages,
maitai/_maitai_async.py CHANGED
@@ -28,11 +28,11 @@ from maitai._types import (
28
28
  ToolFunction,
29
29
  )
30
30
  from maitai._utils import (
31
- OpenAISchemaGenerator,
32
31
  convert_open_ai_chat_completion_chunk,
33
32
  convert_openai_chat_completion,
34
33
  get_chat_completion_params,
35
34
  required_args,
35
+ type_to_response_format_param,
36
36
  )
37
37
  from maitai.tools import Tools
38
38
  from maitai_gen.chat import (
@@ -424,9 +424,7 @@ class AsyncCompletions:
424
424
  if hasattr(response_format, "model_json_schema"):
425
425
  response_format = {
426
426
  "type": "json_schema",
427
- "json_schema": response_format.model_json_schema(
428
- schema_generator=OpenAISchemaGenerator, mode="serialization"
429
- ),
427
+ "json_schema": type_to_response_format_param(response_format),
430
428
  }
431
429
  response = await self._client.chat.completions.create(
432
430
  messages=messages,
maitai/_pydantic.py ADDED
@@ -0,0 +1,181 @@
1
+ import inspect
2
+ from typing import Any, TypeVar
3
+
4
+ import pydantic
5
+
6
+ from maitai._types import NOT_GIVEN
7
+
8
+ PYDANTIC_V2 = pydantic.VERSION.startswith("2.")
9
+
10
+ _ModelT = TypeVar("_ModelT", bound=pydantic.BaseModel)
11
+
12
+
13
+ def is_basemodel_type(typ: type):
14
+ return issubclass(typ, pydantic.BaseModel)
15
+
16
+
17
+ def is_dataclass_like_type(typ: type) -> bool:
18
+ """Returns True if the given type likely used `@pydantic.dataclass`"""
19
+ return hasattr(typ, "__pydantic_config__")
20
+
21
+
22
+ def model_json_schema(model: type[_ModelT]) -> dict[str, Any]:
23
+ if PYDANTIC_V2:
24
+ return model.model_json_schema()
25
+ return model.schema() # pyright: ignore[reportDeprecated]
26
+
27
+
28
+ def to_strict_json_schema(
29
+ model: type[pydantic.BaseModel] | pydantic.TypeAdapter[Any],
30
+ ) -> dict[str, Any]:
31
+ if inspect.isclass(model) and is_basemodel_type(model):
32
+ schema = model_json_schema(model)
33
+ elif PYDANTIC_V2 and isinstance(model, pydantic.TypeAdapter):
34
+ schema = model.json_schema()
35
+ else:
36
+ raise TypeError(
37
+ f"Non BaseModel types are only supported with Pydantic v2 - {model}"
38
+ )
39
+
40
+ return _ensure_strict_json_schema(schema, path=(), root=schema)
41
+
42
+
43
+ def is_dict(obj: object) -> dict[object, object]:
44
+ return isinstance(obj, dict)
45
+
46
+
47
+ def is_list(obj: object) -> list[object]:
48
+ return isinstance(obj, list)
49
+
50
+
51
+ def has_more_than_n_keys(obj: dict[str, object], n: int) -> bool:
52
+ i = 0
53
+ for _ in obj.keys():
54
+ i += 1
55
+ if i > n:
56
+ return True
57
+ return False
58
+
59
+
60
+ def _ensure_strict_json_schema(
61
+ json_schema: object,
62
+ *,
63
+ path: tuple[str, ...],
64
+ root: dict[str, object],
65
+ ) -> dict[str, Any]:
66
+ """Mutates the given JSON schema to ensure it conforms to the `strict` standard
67
+ that the API expects.
68
+ """
69
+ if not is_dict(json_schema):
70
+ raise TypeError(f"Expected {json_schema} to be a dictionary; path={path}")
71
+
72
+ defs = json_schema.get("$defs")
73
+ if is_dict(defs):
74
+ for def_name, def_schema in defs.items():
75
+ _ensure_strict_json_schema(
76
+ def_schema, path=(*path, "$defs", def_name), root=root
77
+ )
78
+
79
+ definitions = json_schema.get("definitions")
80
+ if is_dict(definitions):
81
+ for definition_name, definition_schema in definitions.items():
82
+ _ensure_strict_json_schema(
83
+ definition_schema,
84
+ path=(*path, "definitions", definition_name),
85
+ root=root,
86
+ )
87
+
88
+ typ = json_schema.get("type")
89
+ if typ == "object" and "additionalProperties" not in json_schema:
90
+ json_schema["additionalProperties"] = False
91
+
92
+ # object types
93
+ # { 'type': 'object', 'properties': { 'a': {...} } }
94
+ properties = json_schema.get("properties")
95
+ if is_dict(properties):
96
+ json_schema["required"] = [prop for prop in properties.keys()]
97
+ json_schema["properties"] = {
98
+ key: _ensure_strict_json_schema(
99
+ prop_schema, path=(*path, "properties", key), root=root
100
+ )
101
+ for key, prop_schema in properties.items()
102
+ }
103
+
104
+ # arrays
105
+ # { 'type': 'array', 'items': {...} }
106
+ items = json_schema.get("items")
107
+ if is_dict(items):
108
+ json_schema["items"] = _ensure_strict_json_schema(
109
+ items, path=(*path, "items"), root=root
110
+ )
111
+
112
+ # unions
113
+ any_of = json_schema.get("anyOf")
114
+ if is_list(any_of):
115
+ json_schema["anyOf"] = [
116
+ _ensure_strict_json_schema(
117
+ variant, path=(*path, "anyOf", str(i)), root=root
118
+ )
119
+ for i, variant in enumerate(any_of)
120
+ ]
121
+
122
+ # intersections
123
+ all_of = json_schema.get("allOf")
124
+ if is_list(all_of):
125
+ if len(all_of) == 1:
126
+ json_schema.update(
127
+ _ensure_strict_json_schema(
128
+ all_of[0], path=(*path, "allOf", "0"), root=root
129
+ )
130
+ )
131
+ json_schema.pop("allOf")
132
+ else:
133
+ json_schema["allOf"] = [
134
+ _ensure_strict_json_schema(
135
+ entry, path=(*path, "allOf", str(i)), root=root
136
+ )
137
+ for i, entry in enumerate(all_of)
138
+ ]
139
+
140
+ # strip `None` defaults as there's no meaningful distinction here
141
+ # the schema will still be `nullable` and the model will default
142
+ # to using `None` anyway
143
+ if json_schema.get("default", NOT_GIVEN) is None:
144
+ json_schema.pop("default")
145
+
146
+ # we can't use `$ref`s if there are also other properties defined, e.g.
147
+ # `{"$ref": "...", "description": "my description"}`
148
+ #
149
+ # so we unravel the ref
150
+ # `{"type": "string", "description": "my description"}`
151
+ ref = json_schema.get("$ref")
152
+ if ref and has_more_than_n_keys(json_schema, 1):
153
+ assert isinstance(ref, str), f"Received non-string $ref - {ref}"
154
+
155
+ resolved = resolve_ref(root=root, ref=ref)
156
+ if not is_dict(resolved):
157
+ raise ValueError(
158
+ f"Expected `$ref: {ref}` to resolved to a dictionary but got {resolved}"
159
+ )
160
+
161
+ # properties from the json schema take priority over the ones on the `$ref`
162
+ json_schema.update({**resolved, **json_schema})
163
+ json_schema.pop("$ref")
164
+
165
+ return json_schema
166
+
167
+
168
+ def resolve_ref(*, root: dict[str, object], ref: str) -> object:
169
+ if not ref.startswith("#/"):
170
+ raise ValueError(f"Unexpected $ref format {ref!r}; Does not start with #/")
171
+
172
+ path = ref[2:].split("/")
173
+ resolved = root
174
+ for key in path:
175
+ value = resolved[key]
176
+ assert is_dict(
177
+ value
178
+ ), f"encountered non-dictionary entry while resolving {ref} - {resolved}"
179
+ resolved = value
180
+
181
+ return resolved
maitai/_types.py CHANGED
@@ -1,7 +1,16 @@
1
1
  import asyncio
2
2
  import json
3
3
  import queue
4
- from typing import Any, Callable, Mapping, Optional, Protocol, TypedDict, Union
4
+ from typing import (
5
+ Any,
6
+ Callable,
7
+ Mapping,
8
+ Optional,
9
+ Protocol,
10
+ TypedDict,
11
+ Union,
12
+ override,
13
+ )
5
14
 
6
15
  import openai.types.chat as openai_chat_types
7
16
  from betterproto import Casing
@@ -191,3 +200,32 @@ class FallbackConfig(TypedDict):
191
200
  model: Optional[str]
192
201
  strategy: Literal["reactive", "first_response", "timeout"]
193
202
  timeout: Optional[float]
203
+
204
+
205
+ # Sentinel class used until PEP 0661 is accepted
206
+ class NotGiven:
207
+ """
208
+ A sentinel singleton class used to distinguish omitted keyword arguments
209
+ from those passed in with the value None (which may have different behavior).
210
+
211
+ For example:
212
+
213
+ ```py
214
+ def get(timeout: Union[int, NotGiven, None] = NotGiven()) -> Response: ...
215
+
216
+
217
+ get(timeout=1) # 1s timeout
218
+ get(timeout=None) # No timeout
219
+ get() # Default timeout behavior, which may not be statically known at the method definition.
220
+ ```
221
+ """
222
+
223
+ def __bool__(self) -> Literal[False]:
224
+ return False
225
+
226
+ @override
227
+ def __repr__(self) -> str:
228
+ return "NOT_GIVEN"
229
+
230
+
231
+ NOT_GIVEN = NotGiven()
maitai/_utils.py CHANGED
@@ -15,11 +15,16 @@ from typing import (
15
15
 
16
16
  import openai
17
17
  import openai.types.chat as openai_types
18
+ import pydantic
18
19
  from betterproto import Casing
19
20
  from openai.types import ChatModel
20
- from pydantic.json_schema import GenerateJsonSchema
21
21
 
22
22
  import maitai_gen.chat as chat_types
23
+ from maitai._pydantic import (
24
+ is_basemodel_type,
25
+ is_dataclass_like_type,
26
+ to_strict_json_schema,
27
+ )
23
28
  from maitai._types import ToolFunction
24
29
  from maitai.tools import Tools
25
30
  from maitai_common.version import version
@@ -29,62 +34,23 @@ __version__ = f"{version}_python_{sys.version_info.major}.{sys.version_info.mino
29
34
  CallableT = TypeVar("CallableT", bound=Callable[..., Any])
30
35
 
31
36
 
32
- class OpenAISchemaGenerator(GenerateJsonSchema):
33
- def generate(self, schema, mode="validation") -> dict:
34
- json_schema = super().generate(schema, mode=mode)
35
-
36
- # Inline the referenced objects
37
- def resolve_refs(obj, processed_refs=None):
38
- if processed_refs is None:
39
- processed_refs = set()
40
-
41
- if isinstance(obj, dict):
42
- if "$ref" in obj and obj["$ref"].startswith("#/$defs/"):
43
- ref_name = obj["$ref"].split("/")[-1]
37
+ def type_to_response_format_param(response_format):
38
+ json_schema_type: type[pydantic.BaseModel] | pydantic.TypeAdapter[Any] | None = None
44
39
 
45
- # If we've seen this ref before, return a simplified version
46
- if ref_name in processed_refs:
47
- return {"type": "object"}
48
-
49
- processed_refs.add(ref_name)
50
- return resolve_refs(
51
- json_schema.get("$defs", {}).get(ref_name, {}), processed_refs
52
- )
40
+ if is_basemodel_type(response_format):
41
+ name = response_format.__name__
42
+ json_schema_type = response_format
43
+ elif is_dataclass_like_type(response_format):
44
+ name = response_format.__name__
45
+ json_schema_type = pydantic.TypeAdapter(response_format)
46
+ else:
47
+ raise TypeError(f"Unsupported response_format type - {response_format}")
53
48
 
54
- return {k: resolve_refs(v, processed_refs) for k, v in obj.items()}
55
- elif isinstance(obj, list):
56
- return [resolve_refs(item, processed_refs) for item in obj]
57
- return obj
58
-
59
- # Get the main schema from $defs if it exists
60
- main_schema = None
61
- if "allOf" in json_schema and json_schema["allOf"]:
62
- ref = json_schema["allOf"][0].get("$ref")
63
- if ref and ref.startswith("#/$defs/"):
64
- ref_name = ref.split("/")[-1]
65
- main_schema = json_schema["$defs"][ref_name]
66
-
67
- properties = resolve_refs(
68
- main_schema["properties"] if main_schema else json_schema["properties"]
69
- )
70
-
71
- return {
72
- "name": (
73
- main_schema.get("title", "") if main_schema else schema.get("title", "")
74
- ).lower()
75
- + "_schema",
76
- "strict": True,
77
- "schema": {
78
- "type": "object",
79
- "properties": properties,
80
- "required": (
81
- main_schema.get("required", [])
82
- if main_schema
83
- else json_schema.get("required", [])
84
- ),
85
- "additionalProperties": False,
86
- },
87
- }
49
+ return {
50
+ "schema": to_strict_json_schema(json_schema_type),
51
+ "name": name,
52
+ "strict": True,
53
+ }
88
54
 
89
55
 
90
56
  def required_args(*variants: Sequence[str]) -> Callable[[CallableT], CallableT]:
@@ -255,9 +221,7 @@ def get_chat_completion_params(
255
221
  if hasattr(response_format, "model_json_schema"):
256
222
  response_format = {
257
223
  "type": "json_schema",
258
- "json_schema": response_format.model_json_schema(
259
- schema_generator=OpenAISchemaGenerator, mode="serialization"
260
- ),
224
+ "json_schema": type_to_response_format_param(response_format),
261
225
  }
262
226
  params["response_format"] = {"type": response_format["type"]}
263
227
  if response_format.get("json_schema"):
maitai_common/version.py CHANGED
@@ -1,3 +1,3 @@
1
- version = "1.2.6b0"
1
+ version = "1.2.7"
2
2
  if __name__ == "__main__":
3
3
  print(version)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: maitai-python
3
- Version: 1.2.6b0
3
+ Version: 1.2.7
4
4
  Summary: Maitai SDK for Python
5
5
  Home-page: https://docs.trymaitai.ai
6
6
  Author: Maitai
@@ -4,14 +4,15 @@ maitai/_config_listener_thread.py,sha256=VaftjUXrP8oe6yg0TXUlIZW2vGw7bTk8p_95o4d
4
4
  maitai/_context.py,sha256=WmCLGd7BK1ViImd7uDTsjly7ECcugioZhGjxXwETHfI,2401
5
5
  maitai/_evaluator.py,sha256=x2XSKv6h90VcYBnqb1BRcPOrX7O3gQ4hShZCJzXfO9Y,10344
6
6
  maitai/_inference.py,sha256=4cijo8J7LDLOZFxD9jPeF9KMUmPk8xG-NaT8cGYaITs,12597
7
- maitai/_maitai.py,sha256=5aF0SGbpt3O7Lu-9zHCWdPq133SlyW-uwJ9c6gMlco4,25561
8
- maitai/_maitai_async.py,sha256=1Wh5KDOYesC-7xAw58iITAI5RRA4DvmCES1lRpboXzI,25636
7
+ maitai/_maitai.py,sha256=5p_WKxNuMKO0oJNRISsvD26uxvJAVaeki-pmO2494X8,25474
8
+ maitai/_maitai_async.py,sha256=YJ1nW021xmGnwWoneMZc9ihnoYCbYB9jOuhPxkDOlPw,25549
9
9
  maitai/_maitai_client.py,sha256=VE6c_xMUYrq5RME08JuKW1nfTsmwWo9Oa24asHrmfMg,7817
10
- maitai/_types.py,sha256=uIYm1YQv6ZmGZ4GG6p6xrCjfVGq8VSxkehLgRqtr1Rw,6436
11
- maitai/_utils.py,sha256=-LGF6I13KBj10DSWyh_OmE5ouOsD4DIjmx4jZOuej0A,12351
10
+ maitai/_pydantic.py,sha256=aUSKTDCGrCnn7OoQGHrqZN2Ukest7fvow6H7CM1C9HM,5670
11
+ maitai/_types.py,sha256=xVE5yBJDFJ4jKLqjHwnHquMn2rl2NEdpctia11bfwbQ,7173
12
+ maitai/_utils.py,sha256=AlHqK06jDdnL2RfgOJJOaK70oaMeXcxrNfiZynxtiDY,10811
12
13
  maitai/tools/__init__.py,sha256=TxJ-g4A0eIzoIMD60ctIPVppCWcdcuZWms3hPGrqkSs,4043
13
14
  maitai_common/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
- maitai_common/version.py,sha256=YXzR5gUYveJdFk1mtye4XKXgp4BwWFloV6lY0N1WCXY,66
15
+ maitai_common/version.py,sha256=oSwF0gaGtfbL-chLE5APizlrWIZhKdz-aLlpqEbvFro,64
15
16
  maitai_common/config/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
16
17
  maitai_common/config/config_service.py,sha256=U8hU0F9juZtrZwIayOM_OBShxynUS8gu5K0F40KvcA0,940
17
18
  maitai_common/processes/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -37,7 +38,7 @@ maitai_gen/rates/__init__.py,sha256=Aho7HzMKRfjQz10tMJCoRVttq_cGlYh2DxxpSyTQAzU,
37
38
  maitai_gen/sandbox/__init__.py,sha256=IZ4hf76V1aZrYk5S-4p7z38e-op_s341utVG2domE_g,1549
38
39
  maitai_gen/sentinel/__init__.py,sha256=3yR28usTBIAC-M_uxEUFgqXo2PWylEKEPYmWX_dp7Cs,2513
39
40
  maitai_gen/session/__init__.py,sha256=kCJweCFagUqGkzktucaWLti9HSLaO5AML8Jewl89yM0,1242
40
- maitai_python-1.2.6b0.dist-info/METADATA,sha256=8z35-Efo1iwT86HcA2Vu2RNx37AcPo069zjEXpxOdIA,1496
41
- maitai_python-1.2.6b0.dist-info/WHEEL,sha256=A3WOREP4zgxI0fKrHUG8DC8013e3dK3n7a6HDbcEIwE,91
42
- maitai_python-1.2.6b0.dist-info/top_level.txt,sha256=-5U1krxnwlqB-AY7nEe29ZcNvwByNc-SnBe-mph-QjI,32
43
- maitai_python-1.2.6b0.dist-info/RECORD,,
41
+ maitai_python-1.2.7.dist-info/METADATA,sha256=p2Glr3Z0ZbZq6awM1aojRscLlCfQRQElgsGdMQ6p0S8,1494
42
+ maitai_python-1.2.7.dist-info/WHEEL,sha256=A3WOREP4zgxI0fKrHUG8DC8013e3dK3n7a6HDbcEIwE,91
43
+ maitai_python-1.2.7.dist-info/top_level.txt,sha256=-5U1krxnwlqB-AY7nEe29ZcNvwByNc-SnBe-mph-QjI,32
44
+ maitai_python-1.2.7.dist-info/RECORD,,