hxrron commited on
Commit
9d0e593
·
verified ·
1 Parent(s): 070e6ee

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +4 -0
  2. python_embeded/Lib/site-packages/openai-1.92.3.dist-info/licenses/LICENSE +201 -0
  3. python_embeded/Lib/site-packages/openai/_extras/__init__.py +3 -0
  4. python_embeded/Lib/site-packages/openai/_extras/_common.py +21 -0
  5. python_embeded/Lib/site-packages/openai/_extras/numpy_proxy.py +37 -0
  6. python_embeded/Lib/site-packages/openai/_extras/pandas_proxy.py +28 -0
  7. python_embeded/Lib/site-packages/openai/_extras/sounddevice_proxy.py +28 -0
  8. python_embeded/Lib/site-packages/openai/_utils/__init__.py +60 -0
  9. python_embeded/Lib/site-packages/openai/_utils/_logs.py +42 -0
  10. python_embeded/Lib/site-packages/openai/_utils/_proxy.py +65 -0
  11. python_embeded/Lib/site-packages/openai/_utils/_reflection.py +45 -0
  12. python_embeded/Lib/site-packages/openai/_utils/_resources_proxy.py +24 -0
  13. python_embeded/Lib/site-packages/openai/_utils/_streams.py +12 -0
  14. python_embeded/Lib/site-packages/openai/_utils/_sync.py +86 -0
  15. python_embeded/Lib/site-packages/openai/_utils/_transform.py +447 -0
  16. python_embeded/Lib/site-packages/openai/_utils/_typing.py +151 -0
  17. python_embeded/Lib/site-packages/openai/_utils/_utils.py +438 -0
  18. python_embeded/Lib/site-packages/openai/cli/__init__.py +1 -0
  19. python_embeded/Lib/site-packages/openai/cli/_cli.py +233 -0
  20. python_embeded/Lib/site-packages/openai/cli/_errors.py +21 -0
  21. python_embeded/Lib/site-packages/openai/cli/_models.py +17 -0
  22. python_embeded/Lib/site-packages/openai/cli/_progress.py +59 -0
  23. python_embeded/Lib/site-packages/openai/cli/_utils.py +45 -0
  24. python_embeded/Lib/site-packages/openai/helpers/__init__.py +4 -0
  25. python_embeded/Lib/site-packages/openai/helpers/local_audio_player.py +165 -0
  26. python_embeded/Lib/site-packages/openai/helpers/microphone.py +100 -0
  27. python_embeded/Lib/site-packages/openai/lib/.keep +4 -0
  28. python_embeded/Lib/site-packages/openai/lib/__init__.py +2 -0
  29. python_embeded/Lib/site-packages/openai/lib/_old_api.py +72 -0
  30. python_embeded/Lib/site-packages/openai/lib/_pydantic.py +155 -0
  31. python_embeded/Lib/site-packages/openai/lib/_tools.py +66 -0
  32. python_embeded/Lib/site-packages/openai/lib/_validators.py +809 -0
  33. python_embeded/Lib/site-packages/openai/lib/azure.py +647 -0
  34. python_embeded/Lib/site-packages/openai/resources/__init__.py +215 -0
  35. python_embeded/Lib/site-packages/openai/resources/batches.py +514 -0
  36. python_embeded/Lib/site-packages/openai/resources/completions.py +1160 -0
  37. python_embeded/Lib/site-packages/openai/resources/embeddings.py +292 -0
  38. python_embeded/Lib/site-packages/openai/resources/files.py +762 -0
  39. python_embeded/Lib/site-packages/openai/resources/images.py +753 -0
  40. python_embeded/Lib/site-packages/openai/resources/models.py +306 -0
  41. python_embeded/Lib/site-packages/openai/resources/moderations.py +197 -0
  42. python_embeded/Lib/site-packages/openai/resources/webhooks.py +210 -0
  43. python_embeded/Lib/site-packages/openai/types/__init__.py +95 -0
  44. python_embeded/Lib/site-packages/openai/types/audio/__init__.py +20 -0
  45. python_embeded/Lib/site-packages/openai/types/audio/speech_create_params.py +59 -0
  46. python_embeded/Lib/site-packages/openai/types/audio/speech_model.py +7 -0
  47. python_embeded/Lib/site-packages/openai/types/audio/transcription.py +71 -0
  48. python_embeded/Lib/site-packages/openai/types/audio/transcription_create_params.py +149 -0
  49. python_embeded/Lib/site-packages/openai/types/audio/transcription_create_response.py +11 -0
  50. python_embeded/Lib/site-packages/openai/types/audio/transcription_include.py +7 -0
.gitattributes CHANGED
@@ -325,3 +325,7 @@ python_embeded/Lib/site-packages/skimage/data/rocket.jpg filter=lfs diff=lfs mer
325
  python_embeded/Lib/site-packages/skimage/data/camera.png filter=lfs diff=lfs merge=lfs -text
326
  python_embeded/Lib/site-packages/scipy/special/libsf_error_state.dll filter=lfs diff=lfs merge=lfs -text
327
  python_embeded/Lib/site-packages/pydantic_core/_pydantic_core.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
325
  python_embeded/Lib/site-packages/skimage/data/camera.png filter=lfs diff=lfs merge=lfs -text
326
  python_embeded/Lib/site-packages/scipy/special/libsf_error_state.dll filter=lfs diff=lfs merge=lfs -text
327
  python_embeded/Lib/site-packages/pydantic_core/_pydantic_core.cp312-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
328
+ python_embeded/Lib/site-packages/pip/_vendor/distlib/t64-arm.exe filter=lfs diff=lfs merge=lfs -text
329
+ python_embeded/Lib/site-packages/pip/_vendor/distlib/t64.exe filter=lfs diff=lfs merge=lfs -text
330
+ python_embeded/Lib/site-packages/pip/_vendor/distlib/w64.exe filter=lfs diff=lfs merge=lfs -text
331
+ python_embeded/Lib/site-packages/pip/_vendor/distlib/w64-arm.exe filter=lfs diff=lfs merge=lfs -text
python_embeded/Lib/site-packages/openai-1.92.3.dist-info/licenses/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 OpenAI
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
python_embeded/Lib/site-packages/openai/_extras/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .numpy_proxy import numpy as numpy, has_numpy as has_numpy
2
+ from .pandas_proxy import pandas as pandas
3
+ from .sounddevice_proxy import sounddevice as sounddevice
python_embeded/Lib/site-packages/openai/_extras/_common.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .._exceptions import OpenAIError
2
+
3
+ INSTRUCTIONS = """
4
+
5
+ OpenAI error:
6
+
7
+ missing `{library}`
8
+
9
+ This feature requires additional dependencies:
10
+
11
+ $ pip install openai[{extra}]
12
+
13
+ """
14
+
15
+
16
+ def format_instructions(*, library: str, extra: str) -> str:
17
+ return INSTRUCTIONS.format(library=library, extra=extra)
18
+
19
+
20
+ class MissingDependencyError(OpenAIError):
21
+ pass
python_embeded/Lib/site-packages/openai/_extras/numpy_proxy.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, Any
4
+ from typing_extensions import override
5
+
6
+ from .._utils import LazyProxy
7
+ from ._common import MissingDependencyError, format_instructions
8
+
9
+ if TYPE_CHECKING:
10
+ import numpy as numpy
11
+
12
+
13
+ NUMPY_INSTRUCTIONS = format_instructions(library="numpy", extra="voice_helpers")
14
+
15
+
16
+ class NumpyProxy(LazyProxy[Any]):
17
+ @override
18
+ def __load__(self) -> Any:
19
+ try:
20
+ import numpy
21
+ except ImportError as err:
22
+ raise MissingDependencyError(NUMPY_INSTRUCTIONS) from err
23
+
24
+ return numpy
25
+
26
+
27
+ if not TYPE_CHECKING:
28
+ numpy = NumpyProxy()
29
+
30
+
31
+ def has_numpy() -> bool:
32
+ try:
33
+ import numpy # noqa: F401 # pyright: ignore[reportUnusedImport]
34
+ except ImportError:
35
+ return False
36
+
37
+ return True
python_embeded/Lib/site-packages/openai/_extras/pandas_proxy.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, Any
4
+ from typing_extensions import override
5
+
6
+ from .._utils import LazyProxy
7
+ from ._common import MissingDependencyError, format_instructions
8
+
9
+ if TYPE_CHECKING:
10
+ import pandas as pandas
11
+
12
+
13
+ PANDAS_INSTRUCTIONS = format_instructions(library="pandas", extra="datalib")
14
+
15
+
16
+ class PandasProxy(LazyProxy[Any]):
17
+ @override
18
+ def __load__(self) -> Any:
19
+ try:
20
+ import pandas
21
+ except ImportError as err:
22
+ raise MissingDependencyError(PANDAS_INSTRUCTIONS) from err
23
+
24
+ return pandas
25
+
26
+
27
+ if not TYPE_CHECKING:
28
+ pandas = PandasProxy()
python_embeded/Lib/site-packages/openai/_extras/sounddevice_proxy.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, Any
4
+ from typing_extensions import override
5
+
6
+ from .._utils import LazyProxy
7
+ from ._common import MissingDependencyError, format_instructions
8
+
9
+ if TYPE_CHECKING:
10
+ import sounddevice as sounddevice # type: ignore
11
+
12
+
13
+ SOUNDDEVICE_INSTRUCTIONS = format_instructions(library="sounddevice", extra="voice_helpers")
14
+
15
+
16
+ class SounddeviceProxy(LazyProxy[Any]):
17
+ @override
18
+ def __load__(self) -> Any:
19
+ try:
20
+ import sounddevice # type: ignore
21
+ except ImportError as err:
22
+ raise MissingDependencyError(SOUNDDEVICE_INSTRUCTIONS) from err
23
+
24
+ return sounddevice
25
+
26
+
27
+ if not TYPE_CHECKING:
28
+ sounddevice = SounddeviceProxy()
python_embeded/Lib/site-packages/openai/_utils/__init__.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ._logs import SensitiveHeadersFilter as SensitiveHeadersFilter
2
+ from ._sync import asyncify as asyncify
3
+ from ._proxy import LazyProxy as LazyProxy
4
+ from ._utils import (
5
+ flatten as flatten,
6
+ is_dict as is_dict,
7
+ is_list as is_list,
8
+ is_given as is_given,
9
+ is_tuple as is_tuple,
10
+ json_safe as json_safe,
11
+ lru_cache as lru_cache,
12
+ is_mapping as is_mapping,
13
+ is_tuple_t as is_tuple_t,
14
+ parse_date as parse_date,
15
+ is_iterable as is_iterable,
16
+ is_sequence as is_sequence,
17
+ coerce_float as coerce_float,
18
+ is_mapping_t as is_mapping_t,
19
+ removeprefix as removeprefix,
20
+ removesuffix as removesuffix,
21
+ extract_files as extract_files,
22
+ is_sequence_t as is_sequence_t,
23
+ required_args as required_args,
24
+ coerce_boolean as coerce_boolean,
25
+ coerce_integer as coerce_integer,
26
+ file_from_path as file_from_path,
27
+ parse_datetime as parse_datetime,
28
+ is_azure_client as is_azure_client,
29
+ strip_not_given as strip_not_given,
30
+ deepcopy_minimal as deepcopy_minimal,
31
+ get_async_library as get_async_library,
32
+ maybe_coerce_float as maybe_coerce_float,
33
+ get_required_header as get_required_header,
34
+ maybe_coerce_boolean as maybe_coerce_boolean,
35
+ maybe_coerce_integer as maybe_coerce_integer,
36
+ is_async_azure_client as is_async_azure_client,
37
+ )
38
+ from ._typing import (
39
+ is_list_type as is_list_type,
40
+ is_union_type as is_union_type,
41
+ extract_type_arg as extract_type_arg,
42
+ is_iterable_type as is_iterable_type,
43
+ is_required_type as is_required_type,
44
+ is_annotated_type as is_annotated_type,
45
+ is_type_alias_type as is_type_alias_type,
46
+ strip_annotated_type as strip_annotated_type,
47
+ extract_type_var_from_base as extract_type_var_from_base,
48
+ )
49
+ from ._streams import consume_sync_iterator as consume_sync_iterator, consume_async_iterator as consume_async_iterator
50
+ from ._transform import (
51
+ PropertyInfo as PropertyInfo,
52
+ transform as transform,
53
+ async_transform as async_transform,
54
+ maybe_transform as maybe_transform,
55
+ async_maybe_transform as async_maybe_transform,
56
+ )
57
+ from ._reflection import (
58
+ function_has_argument as function_has_argument,
59
+ assert_signatures_in_sync as assert_signatures_in_sync,
60
+ )
python_embeded/Lib/site-packages/openai/_utils/_logs.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ from typing_extensions import override
4
+
5
+ from ._utils import is_dict
6
+
7
+ logger: logging.Logger = logging.getLogger("openai")
8
+ httpx_logger: logging.Logger = logging.getLogger("httpx")
9
+
10
+
11
+ SENSITIVE_HEADERS = {"api-key", "authorization"}
12
+
13
+
14
+ def _basic_config() -> None:
15
+ # e.g. [2023-10-05 14:12:26 - openai._base_client:818 - DEBUG] HTTP Request: POST http://127.0.0.1:4010/foo/bar "200 OK"
16
+ logging.basicConfig(
17
+ format="[%(asctime)s - %(name)s:%(lineno)d - %(levelname)s] %(message)s",
18
+ datefmt="%Y-%m-%d %H:%M:%S",
19
+ )
20
+
21
+
22
+ def setup_logging() -> None:
23
+ env = os.environ.get("OPENAI_LOG")
24
+ if env == "debug":
25
+ _basic_config()
26
+ logger.setLevel(logging.DEBUG)
27
+ httpx_logger.setLevel(logging.DEBUG)
28
+ elif env == "info":
29
+ _basic_config()
30
+ logger.setLevel(logging.INFO)
31
+ httpx_logger.setLevel(logging.INFO)
32
+
33
+
34
+ class SensitiveHeadersFilter(logging.Filter):
35
+ @override
36
+ def filter(self, record: logging.LogRecord) -> bool:
37
+ if is_dict(record.args) and "headers" in record.args and is_dict(record.args["headers"]):
38
+ headers = record.args["headers"] = {**record.args["headers"]}
39
+ for header in headers:
40
+ if str(header).lower() in SENSITIVE_HEADERS:
41
+ headers[header] = "<redacted>"
42
+ return True
python_embeded/Lib/site-packages/openai/_utils/_proxy.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from abc import ABC, abstractmethod
4
+ from typing import Generic, TypeVar, Iterable, cast
5
+ from typing_extensions import override
6
+
7
+ T = TypeVar("T")
8
+
9
+
10
+ class LazyProxy(Generic[T], ABC):
11
+ """Implements data methods to pretend that an instance is another instance.
12
+
13
+ This includes forwarding attribute access and other methods.
14
+ """
15
+
16
+ # Note: we have to special case proxies that themselves return proxies
17
+ # to support using a proxy as a catch-all for any random access, e.g. `proxy.foo.bar.baz`
18
+
19
+ def __getattr__(self, attr: str) -> object:
20
+ proxied = self.__get_proxied__()
21
+ if isinstance(proxied, LazyProxy):
22
+ return proxied # pyright: ignore
23
+ return getattr(proxied, attr)
24
+
25
+ @override
26
+ def __repr__(self) -> str:
27
+ proxied = self.__get_proxied__()
28
+ if isinstance(proxied, LazyProxy):
29
+ return proxied.__class__.__name__
30
+ return repr(self.__get_proxied__())
31
+
32
+ @override
33
+ def __str__(self) -> str:
34
+ proxied = self.__get_proxied__()
35
+ if isinstance(proxied, LazyProxy):
36
+ return proxied.__class__.__name__
37
+ return str(proxied)
38
+
39
+ @override
40
+ def __dir__(self) -> Iterable[str]:
41
+ proxied = self.__get_proxied__()
42
+ if isinstance(proxied, LazyProxy):
43
+ return []
44
+ return proxied.__dir__()
45
+
46
+ @property # type: ignore
47
+ @override
48
+ def __class__(self) -> type: # pyright: ignore
49
+ try:
50
+ proxied = self.__get_proxied__()
51
+ except Exception:
52
+ return type(self)
53
+ if issubclass(type(proxied), LazyProxy):
54
+ return type(proxied)
55
+ return proxied.__class__
56
+
57
+ def __get_proxied__(self) -> T:
58
+ return self.__load__()
59
+
60
+ def __as_proxied__(self) -> T:
61
+ """Helper method that returns the current proxy, typed as the loaded object"""
62
+ return cast(T, self)
63
+
64
+ @abstractmethod
65
+ def __load__(self) -> T: ...
python_embeded/Lib/site-packages/openai/_utils/_reflection.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ from typing import Any, Callable
5
+
6
+
7
+ def function_has_argument(func: Callable[..., Any], arg_name: str) -> bool:
8
+ """Returns whether or not the given function has a specific parameter"""
9
+ sig = inspect.signature(func)
10
+ return arg_name in sig.parameters
11
+
12
+
13
+ def assert_signatures_in_sync(
14
+ source_func: Callable[..., Any],
15
+ check_func: Callable[..., Any],
16
+ *,
17
+ exclude_params: set[str] = set(),
18
+ description: str = "",
19
+ ) -> None:
20
+ """Ensure that the signature of the second function matches the first."""
21
+
22
+ check_sig = inspect.signature(check_func)
23
+ source_sig = inspect.signature(source_func)
24
+
25
+ errors: list[str] = []
26
+
27
+ for name, source_param in source_sig.parameters.items():
28
+ if name in exclude_params:
29
+ continue
30
+
31
+ custom_param = check_sig.parameters.get(name)
32
+ if not custom_param:
33
+ errors.append(f"the `{name}` param is missing")
34
+ continue
35
+
36
+ if custom_param.annotation != source_param.annotation:
37
+ errors.append(
38
+ f"types for the `{name}` param are do not match; source={repr(source_param.annotation)} checking={repr(custom_param.annotation)}"
39
+ )
40
+ continue
41
+
42
+ if errors:
43
+ raise AssertionError(
44
+ f"{len(errors)} errors encountered when comparing signatures{description}:\n\n" + "\n\n".join(errors)
45
+ )
python_embeded/Lib/site-packages/openai/_utils/_resources_proxy.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+ from typing_extensions import override
5
+
6
+ from ._proxy import LazyProxy
7
+
8
+
9
+ class ResourcesProxy(LazyProxy[Any]):
10
+ """A proxy for the `openai.resources` module.
11
+
12
+ This is used so that we can lazily import `openai.resources` only when
13
+ needed *and* so that users can just import `openai` and reference `openai.resources`
14
+ """
15
+
16
+ @override
17
+ def __load__(self) -> Any:
18
+ import importlib
19
+
20
+ mod = importlib.import_module("openai.resources")
21
+ return mod
22
+
23
+
24
+ resources = ResourcesProxy().__as_proxied__()
python_embeded/Lib/site-packages/openai/_utils/_streams.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+ from typing_extensions import Iterator, AsyncIterator
3
+
4
+
5
+ def consume_sync_iterator(iterator: Iterator[Any]) -> None:
6
+ for _ in iterator:
7
+ ...
8
+
9
+
10
+ async def consume_async_iterator(iterator: AsyncIterator[Any]) -> None:
11
+ async for _ in iterator:
12
+ ...
python_embeded/Lib/site-packages/openai/_utils/_sync.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ import asyncio
5
+ import functools
6
+ import contextvars
7
+ from typing import Any, TypeVar, Callable, Awaitable
8
+ from typing_extensions import ParamSpec
9
+
10
+ import anyio
11
+ import sniffio
12
+ import anyio.to_thread
13
+
14
+ T_Retval = TypeVar("T_Retval")
15
+ T_ParamSpec = ParamSpec("T_ParamSpec")
16
+
17
+
18
+ if sys.version_info >= (3, 9):
19
+ _asyncio_to_thread = asyncio.to_thread
20
+ else:
21
+ # backport of https://docs.python.org/3/library/asyncio-task.html#asyncio.to_thread
22
+ # for Python 3.8 support
23
+ async def _asyncio_to_thread(
24
+ func: Callable[T_ParamSpec, T_Retval], /, *args: T_ParamSpec.args, **kwargs: T_ParamSpec.kwargs
25
+ ) -> Any:
26
+ """Asynchronously run function *func* in a separate thread.
27
+
28
+ Any *args and **kwargs supplied for this function are directly passed
29
+ to *func*. Also, the current :class:`contextvars.Context` is propagated,
30
+ allowing context variables from the main thread to be accessed in the
31
+ separate thread.
32
+
33
+ Returns a coroutine that can be awaited to get the eventual result of *func*.
34
+ """
35
+ loop = asyncio.events.get_running_loop()
36
+ ctx = contextvars.copy_context()
37
+ func_call = functools.partial(ctx.run, func, *args, **kwargs)
38
+ return await loop.run_in_executor(None, func_call)
39
+
40
+
41
+ async def to_thread(
42
+ func: Callable[T_ParamSpec, T_Retval], /, *args: T_ParamSpec.args, **kwargs: T_ParamSpec.kwargs
43
+ ) -> T_Retval:
44
+ if sniffio.current_async_library() == "asyncio":
45
+ return await _asyncio_to_thread(func, *args, **kwargs)
46
+
47
+ return await anyio.to_thread.run_sync(
48
+ functools.partial(func, *args, **kwargs),
49
+ )
50
+
51
+
52
+ # inspired by `asyncer`, https://github.com/tiangolo/asyncer
53
+ def asyncify(function: Callable[T_ParamSpec, T_Retval]) -> Callable[T_ParamSpec, Awaitable[T_Retval]]:
54
+ """
55
+ Take a blocking function and create an async one that receives the same
56
+ positional and keyword arguments. For python version 3.9 and above, it uses
57
+ asyncio.to_thread to run the function in a separate thread. For python version
58
+ 3.8, it uses locally defined copy of the asyncio.to_thread function which was
59
+ introduced in python 3.9.
60
+
61
+ Usage:
62
+
63
+ ```python
64
+ def blocking_func(arg1, arg2, kwarg1=None):
65
+ # blocking code
66
+ return result
67
+
68
+
69
+ result = asyncify(blocking_function)(arg1, arg2, kwarg1=value1)
70
+ ```
71
+
72
+ ## Arguments
73
+
74
+ `function`: a blocking regular callable (e.g. a function)
75
+
76
+ ## Return
77
+
78
+ An async function that takes the same positional and keyword arguments as the
79
+ original one, that when called runs the same original function in a thread worker
80
+ and returns the result.
81
+ """
82
+
83
+ async def wrapper(*args: T_ParamSpec.args, **kwargs: T_ParamSpec.kwargs) -> T_Retval:
84
+ return await to_thread(function, *args, **kwargs)
85
+
86
+ return wrapper
python_embeded/Lib/site-packages/openai/_utils/_transform.py ADDED
@@ -0,0 +1,447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ import base64
5
+ import pathlib
6
+ from typing import Any, Mapping, TypeVar, cast
7
+ from datetime import date, datetime
8
+ from typing_extensions import Literal, get_args, override, get_type_hints as _get_type_hints
9
+
10
+ import anyio
11
+ import pydantic
12
+
13
+ from ._utils import (
14
+ is_list,
15
+ is_given,
16
+ lru_cache,
17
+ is_mapping,
18
+ is_iterable,
19
+ )
20
+ from .._files import is_base64_file_input
21
+ from ._typing import (
22
+ is_list_type,
23
+ is_union_type,
24
+ extract_type_arg,
25
+ is_iterable_type,
26
+ is_required_type,
27
+ is_annotated_type,
28
+ strip_annotated_type,
29
+ )
30
+ from .._compat import get_origin, model_dump, is_typeddict
31
+
32
+ _T = TypeVar("_T")
33
+
34
+
35
+ # TODO: support for drilling globals() and locals()
36
+ # TODO: ensure works correctly with forward references in all cases
37
+
38
+
39
+ PropertyFormat = Literal["iso8601", "base64", "custom"]
40
+
41
+
42
+ class PropertyInfo:
43
+ """Metadata class to be used in Annotated types to provide information about a given type.
44
+
45
+ For example:
46
+
47
+ class MyParams(TypedDict):
48
+ account_holder_name: Annotated[str, PropertyInfo(alias='accountHolderName')]
49
+
50
+ This means that {'account_holder_name': 'Robert'} will be transformed to {'accountHolderName': 'Robert'} before being sent to the API.
51
+ """
52
+
53
+ alias: str | None
54
+ format: PropertyFormat | None
55
+ format_template: str | None
56
+ discriminator: str | None
57
+
58
+ def __init__(
59
+ self,
60
+ *,
61
+ alias: str | None = None,
62
+ format: PropertyFormat | None = None,
63
+ format_template: str | None = None,
64
+ discriminator: str | None = None,
65
+ ) -> None:
66
+ self.alias = alias
67
+ self.format = format
68
+ self.format_template = format_template
69
+ self.discriminator = discriminator
70
+
71
+ @override
72
+ def __repr__(self) -> str:
73
+ return f"{self.__class__.__name__}(alias='{self.alias}', format={self.format}, format_template='{self.format_template}', discriminator='{self.discriminator}')"
74
+
75
+
76
+ def maybe_transform(
77
+ data: object,
78
+ expected_type: object,
79
+ ) -> Any | None:
80
+ """Wrapper over `transform()` that allows `None` to be passed.
81
+
82
+ See `transform()` for more details.
83
+ """
84
+ if data is None:
85
+ return None
86
+ return transform(data, expected_type)
87
+
88
+
89
+ # Wrapper over _transform_recursive providing fake types
90
+ def transform(
91
+ data: _T,
92
+ expected_type: object,
93
+ ) -> _T:
94
+ """Transform dictionaries based off of type information from the given type, for example:
95
+
96
+ ```py
97
+ class Params(TypedDict, total=False):
98
+ card_id: Required[Annotated[str, PropertyInfo(alias="cardID")]]
99
+
100
+
101
+ transformed = transform({"card_id": "<my card ID>"}, Params)
102
+ # {'cardID': '<my card ID>'}
103
+ ```
104
+
105
+ Any keys / data that does not have type information given will be included as is.
106
+
107
+ It should be noted that the transformations that this function does are not represented in the type system.
108
+ """
109
+ transformed = _transform_recursive(data, annotation=cast(type, expected_type))
110
+ return cast(_T, transformed)
111
+
112
+
113
+ @lru_cache(maxsize=8096)
114
+ def _get_annotated_type(type_: type) -> type | None:
115
+ """If the given type is an `Annotated` type then it is returned, if not `None` is returned.
116
+
117
+ This also unwraps the type when applicable, e.g. `Required[Annotated[T, ...]]`
118
+ """
119
+ if is_required_type(type_):
120
+ # Unwrap `Required[Annotated[T, ...]]` to `Annotated[T, ...]`
121
+ type_ = get_args(type_)[0]
122
+
123
+ if is_annotated_type(type_):
124
+ return type_
125
+
126
+ return None
127
+
128
+
129
+ def _maybe_transform_key(key: str, type_: type) -> str:
130
+ """Transform the given `data` based on the annotations provided in `type_`.
131
+
132
+ Note: this function only looks at `Annotated` types that contain `PropertyInfo` metadata.
133
+ """
134
+ annotated_type = _get_annotated_type(type_)
135
+ if annotated_type is None:
136
+ # no `Annotated` definition for this type, no transformation needed
137
+ return key
138
+
139
+ # ignore the first argument as it is the actual type
140
+ annotations = get_args(annotated_type)[1:]
141
+ for annotation in annotations:
142
+ if isinstance(annotation, PropertyInfo) and annotation.alias is not None:
143
+ return annotation.alias
144
+
145
+ return key
146
+
147
+
148
+ def _no_transform_needed(annotation: type) -> bool:
149
+ return annotation == float or annotation == int
150
+
151
+
152
+ def _transform_recursive(
153
+ data: object,
154
+ *,
155
+ annotation: type,
156
+ inner_type: type | None = None,
157
+ ) -> object:
158
+ """Transform the given data against the expected type.
159
+
160
+ Args:
161
+ annotation: The direct type annotation given to the particular piece of data.
162
+ This may or may not be wrapped in metadata types, e.g. `Required[T]`, `Annotated[T, ...]` etc
163
+
164
+ inner_type: If applicable, this is the "inside" type. This is useful in certain cases where the outside type
165
+ is a container type such as `List[T]`. In that case `inner_type` should be set to `T` so that each entry in
166
+ the list can be transformed using the metadata from the container type.
167
+
168
+ Defaults to the same value as the `annotation` argument.
169
+ """
170
+ if inner_type is None:
171
+ inner_type = annotation
172
+
173
+ stripped_type = strip_annotated_type(inner_type)
174
+ origin = get_origin(stripped_type) or stripped_type
175
+ if is_typeddict(stripped_type) and is_mapping(data):
176
+ return _transform_typeddict(data, stripped_type)
177
+
178
+ if origin == dict and is_mapping(data):
179
+ items_type = get_args(stripped_type)[1]
180
+ return {key: _transform_recursive(value, annotation=items_type) for key, value in data.items()}
181
+
182
+ if (
183
+ # List[T]
184
+ (is_list_type(stripped_type) and is_list(data))
185
+ # Iterable[T]
186
+ or (is_iterable_type(stripped_type) and is_iterable(data) and not isinstance(data, str))
187
+ ):
188
+ # dicts are technically iterable, but it is an iterable on the keys of the dict and is not usually
189
+ # intended as an iterable, so we don't transform it.
190
+ if isinstance(data, dict):
191
+ return cast(object, data)
192
+
193
+ inner_type = extract_type_arg(stripped_type, 0)
194
+ if _no_transform_needed(inner_type):
195
+ # for some types there is no need to transform anything, so we can get a small
196
+ # perf boost from skipping that work.
197
+ #
198
+ # but we still need to convert to a list to ensure the data is json-serializable
199
+ if is_list(data):
200
+ return data
201
+ return list(data)
202
+
203
+ return [_transform_recursive(d, annotation=annotation, inner_type=inner_type) for d in data]
204
+
205
+ if is_union_type(stripped_type):
206
+ # For union types we run the transformation against all subtypes to ensure that everything is transformed.
207
+ #
208
+ # TODO: there may be edge cases where the same normalized field name will transform to two different names
209
+ # in different subtypes.
210
+ for subtype in get_args(stripped_type):
211
+ data = _transform_recursive(data, annotation=annotation, inner_type=subtype)
212
+ return data
213
+
214
+ if isinstance(data, pydantic.BaseModel):
215
+ return model_dump(data, exclude_unset=True, mode="json", exclude=getattr(data, "__api_exclude__", None))
216
+
217
+ annotated_type = _get_annotated_type(annotation)
218
+ if annotated_type is None:
219
+ return data
220
+
221
+ # ignore the first argument as it is the actual type
222
+ annotations = get_args(annotated_type)[1:]
223
+ for annotation in annotations:
224
+ if isinstance(annotation, PropertyInfo) and annotation.format is not None:
225
+ return _format_data(data, annotation.format, annotation.format_template)
226
+
227
+ return data
228
+
229
+
230
+ def _format_data(data: object, format_: PropertyFormat, format_template: str | None) -> object:
231
+ if isinstance(data, (date, datetime)):
232
+ if format_ == "iso8601":
233
+ return data.isoformat()
234
+
235
+ if format_ == "custom" and format_template is not None:
236
+ return data.strftime(format_template)
237
+
238
+ if format_ == "base64" and is_base64_file_input(data):
239
+ binary: str | bytes | None = None
240
+
241
+ if isinstance(data, pathlib.Path):
242
+ binary = data.read_bytes()
243
+ elif isinstance(data, io.IOBase):
244
+ binary = data.read()
245
+
246
+ if isinstance(binary, str): # type: ignore[unreachable]
247
+ binary = binary.encode()
248
+
249
+ if not isinstance(binary, bytes):
250
+ raise RuntimeError(f"Could not read bytes from {data}; Received {type(binary)}")
251
+
252
+ return base64.b64encode(binary).decode("ascii")
253
+
254
+ return data
255
+
256
+
257
+ def _transform_typeddict(
258
+ data: Mapping[str, object],
259
+ expected_type: type,
260
+ ) -> Mapping[str, object]:
261
+ result: dict[str, object] = {}
262
+ annotations = get_type_hints(expected_type, include_extras=True)
263
+ for key, value in data.items():
264
+ if not is_given(value):
265
+ # we don't need to include `NotGiven` values here as they'll
266
+ # be stripped out before the request is sent anyway
267
+ continue
268
+
269
+ type_ = annotations.get(key)
270
+ if type_ is None:
271
+ # we do not have a type annotation for this field, leave it as is
272
+ result[key] = value
273
+ else:
274
+ result[_maybe_transform_key(key, type_)] = _transform_recursive(value, annotation=type_)
275
+ return result
276
+
277
+
278
+ async def async_maybe_transform(
279
+ data: object,
280
+ expected_type: object,
281
+ ) -> Any | None:
282
+ """Wrapper over `async_transform()` that allows `None` to be passed.
283
+
284
+ See `async_transform()` for more details.
285
+ """
286
+ if data is None:
287
+ return None
288
+ return await async_transform(data, expected_type)
289
+
290
+
291
+ async def async_transform(
292
+ data: _T,
293
+ expected_type: object,
294
+ ) -> _T:
295
+ """Transform dictionaries based off of type information from the given type, for example:
296
+
297
+ ```py
298
+ class Params(TypedDict, total=False):
299
+ card_id: Required[Annotated[str, PropertyInfo(alias="cardID")]]
300
+
301
+
302
+ transformed = transform({"card_id": "<my card ID>"}, Params)
303
+ # {'cardID': '<my card ID>'}
304
+ ```
305
+
306
+ Any keys / data that does not have type information given will be included as is.
307
+
308
+ It should be noted that the transformations that this function does are not represented in the type system.
309
+ """
310
+ transformed = await _async_transform_recursive(data, annotation=cast(type, expected_type))
311
+ return cast(_T, transformed)
312
+
313
+
314
+ async def _async_transform_recursive(
315
+ data: object,
316
+ *,
317
+ annotation: type,
318
+ inner_type: type | None = None,
319
+ ) -> object:
320
+ """Transform the given data against the expected type.
321
+
322
+ Args:
323
+ annotation: The direct type annotation given to the particular piece of data.
324
+ This may or may not be wrapped in metadata types, e.g. `Required[T]`, `Annotated[T, ...]` etc
325
+
326
+ inner_type: If applicable, this is the "inside" type. This is useful in certain cases where the outside type
327
+ is a container type such as `List[T]`. In that case `inner_type` should be set to `T` so that each entry in
328
+ the list can be transformed using the metadata from the container type.
329
+
330
+ Defaults to the same value as the `annotation` argument.
331
+ """
332
+ if inner_type is None:
333
+ inner_type = annotation
334
+
335
+ stripped_type = strip_annotated_type(inner_type)
336
+ origin = get_origin(stripped_type) or stripped_type
337
+ if is_typeddict(stripped_type) and is_mapping(data):
338
+ return await _async_transform_typeddict(data, stripped_type)
339
+
340
+ if origin == dict and is_mapping(data):
341
+ items_type = get_args(stripped_type)[1]
342
+ return {key: _transform_recursive(value, annotation=items_type) for key, value in data.items()}
343
+
344
+ if (
345
+ # List[T]
346
+ (is_list_type(stripped_type) and is_list(data))
347
+ # Iterable[T]
348
+ or (is_iterable_type(stripped_type) and is_iterable(data) and not isinstance(data, str))
349
+ ):
350
+ # dicts are technically iterable, but it is an iterable on the keys of the dict and is not usually
351
+ # intended as an iterable, so we don't transform it.
352
+ if isinstance(data, dict):
353
+ return cast(object, data)
354
+
355
+ inner_type = extract_type_arg(stripped_type, 0)
356
+ if _no_transform_needed(inner_type):
357
+ # for some types there is no need to transform anything, so we can get a small
358
+ # perf boost from skipping that work.
359
+ #
360
+ # but we still need to convert to a list to ensure the data is json-serializable
361
+ if is_list(data):
362
+ return data
363
+ return list(data)
364
+
365
+ return [await _async_transform_recursive(d, annotation=annotation, inner_type=inner_type) for d in data]
366
+
367
+ if is_union_type(stripped_type):
368
+ # For union types we run the transformation against all subtypes to ensure that everything is transformed.
369
+ #
370
+ # TODO: there may be edge cases where the same normalized field name will transform to two different names
371
+ # in different subtypes.
372
+ for subtype in get_args(stripped_type):
373
+ data = await _async_transform_recursive(data, annotation=annotation, inner_type=subtype)
374
+ return data
375
+
376
+ if isinstance(data, pydantic.BaseModel):
377
+ return model_dump(data, exclude_unset=True, mode="json")
378
+
379
+ annotated_type = _get_annotated_type(annotation)
380
+ if annotated_type is None:
381
+ return data
382
+
383
+ # ignore the first argument as it is the actual type
384
+ annotations = get_args(annotated_type)[1:]
385
+ for annotation in annotations:
386
+ if isinstance(annotation, PropertyInfo) and annotation.format is not None:
387
+ return await _async_format_data(data, annotation.format, annotation.format_template)
388
+
389
+ return data
390
+
391
+
392
+ async def _async_format_data(data: object, format_: PropertyFormat, format_template: str | None) -> object:
393
+ if isinstance(data, (date, datetime)):
394
+ if format_ == "iso8601":
395
+ return data.isoformat()
396
+
397
+ if format_ == "custom" and format_template is not None:
398
+ return data.strftime(format_template)
399
+
400
+ if format_ == "base64" and is_base64_file_input(data):
401
+ binary: str | bytes | None = None
402
+
403
+ if isinstance(data, pathlib.Path):
404
+ binary = await anyio.Path(data).read_bytes()
405
+ elif isinstance(data, io.IOBase):
406
+ binary = data.read()
407
+
408
+ if isinstance(binary, str): # type: ignore[unreachable]
409
+ binary = binary.encode()
410
+
411
+ if not isinstance(binary, bytes):
412
+ raise RuntimeError(f"Could not read bytes from {data}; Received {type(binary)}")
413
+
414
+ return base64.b64encode(binary).decode("ascii")
415
+
416
+ return data
417
+
418
+
419
+ async def _async_transform_typeddict(
420
+ data: Mapping[str, object],
421
+ expected_type: type,
422
+ ) -> Mapping[str, object]:
423
+ result: dict[str, object] = {}
424
+ annotations = get_type_hints(expected_type, include_extras=True)
425
+ for key, value in data.items():
426
+ if not is_given(value):
427
+ # we don't need to include `NotGiven` values here as they'll
428
+ # be stripped out before the request is sent anyway
429
+ continue
430
+
431
+ type_ = annotations.get(key)
432
+ if type_ is None:
433
+ # we do not have a type annotation for this field, leave it as is
434
+ result[key] = value
435
+ else:
436
+ result[_maybe_transform_key(key, type_)] = await _async_transform_recursive(value, annotation=type_)
437
+ return result
438
+
439
+
440
+ @lru_cache(maxsize=8096)
441
+ def get_type_hints(
442
+ obj: Any,
443
+ globalns: dict[str, Any] | None = None,
444
+ localns: Mapping[str, Any] | None = None,
445
+ include_extras: bool = False,
446
+ ) -> dict[str, Any]:
447
+ return _get_type_hints(obj, globalns=globalns, localns=localns, include_extras=include_extras)
python_embeded/Lib/site-packages/openai/_utils/_typing.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ import typing
5
+ import typing_extensions
6
+ from typing import Any, TypeVar, Iterable, cast
7
+ from collections import abc as _c_abc
8
+ from typing_extensions import (
9
+ TypeIs,
10
+ Required,
11
+ Annotated,
12
+ get_args,
13
+ get_origin,
14
+ )
15
+
16
+ from ._utils import lru_cache
17
+ from .._types import InheritsGeneric
18
+ from .._compat import is_union as _is_union
19
+
20
+
21
+ def is_annotated_type(typ: type) -> bool:
22
+ return get_origin(typ) == Annotated
23
+
24
+
25
+ def is_list_type(typ: type) -> bool:
26
+ return (get_origin(typ) or typ) == list
27
+
28
+
29
+ def is_iterable_type(typ: type) -> bool:
30
+ """If the given type is `typing.Iterable[T]`"""
31
+ origin = get_origin(typ) or typ
32
+ return origin == Iterable or origin == _c_abc.Iterable
33
+
34
+
35
+ def is_union_type(typ: type) -> bool:
36
+ return _is_union(get_origin(typ))
37
+
38
+
39
+ def is_required_type(typ: type) -> bool:
40
+ return get_origin(typ) == Required
41
+
42
+
43
+ def is_typevar(typ: type) -> bool:
44
+ # type ignore is required because type checkers
45
+ # think this expression will always return False
46
+ return type(typ) == TypeVar # type: ignore
47
+
48
+
49
+ _TYPE_ALIAS_TYPES: tuple[type[typing_extensions.TypeAliasType], ...] = (typing_extensions.TypeAliasType,)
50
+ if sys.version_info >= (3, 12):
51
+ _TYPE_ALIAS_TYPES = (*_TYPE_ALIAS_TYPES, typing.TypeAliasType)
52
+
53
+
54
+ def is_type_alias_type(tp: Any, /) -> TypeIs[typing_extensions.TypeAliasType]:
55
+ """Return whether the provided argument is an instance of `TypeAliasType`.
56
+
57
+ ```python
58
+ type Int = int
59
+ is_type_alias_type(Int)
60
+ # > True
61
+ Str = TypeAliasType("Str", str)
62
+ is_type_alias_type(Str)
63
+ # > True
64
+ ```
65
+ """
66
+ return isinstance(tp, _TYPE_ALIAS_TYPES)
67
+
68
+
69
+ # Extracts T from Annotated[T, ...] or from Required[Annotated[T, ...]]
70
+ @lru_cache(maxsize=8096)
71
+ def strip_annotated_type(typ: type) -> type:
72
+ if is_required_type(typ) or is_annotated_type(typ):
73
+ return strip_annotated_type(cast(type, get_args(typ)[0]))
74
+
75
+ return typ
76
+
77
+
78
+ def extract_type_arg(typ: type, index: int) -> type:
79
+ args = get_args(typ)
80
+ try:
81
+ return cast(type, args[index])
82
+ except IndexError as err:
83
+ raise RuntimeError(f"Expected type {typ} to have a type argument at index {index} but it did not") from err
84
+
85
+
86
+ def extract_type_var_from_base(
87
+ typ: type,
88
+ *,
89
+ generic_bases: tuple[type, ...],
90
+ index: int,
91
+ failure_message: str | None = None,
92
+ ) -> type:
93
+ """Given a type like `Foo[T]`, returns the generic type variable `T`.
94
+
95
+ This also handles the case where a concrete subclass is given, e.g.
96
+ ```py
97
+ class MyResponse(Foo[bytes]):
98
+ ...
99
+
100
+ extract_type_var(MyResponse, bases=(Foo,), index=0) -> bytes
101
+ ```
102
+
103
+ And where a generic subclass is given:
104
+ ```py
105
+ _T = TypeVar('_T')
106
+ class MyResponse(Foo[_T]):
107
+ ...
108
+
109
+ extract_type_var(MyResponse[bytes], bases=(Foo,), index=0) -> bytes
110
+ ```
111
+ """
112
+ cls = cast(object, get_origin(typ) or typ)
113
+ if cls in generic_bases: # pyright: ignore[reportUnnecessaryContains]
114
+ # we're given the class directly
115
+ return extract_type_arg(typ, index)
116
+
117
+ # if a subclass is given
118
+ # ---
119
+ # this is needed as __orig_bases__ is not present in the typeshed stubs
120
+ # because it is intended to be for internal use only, however there does
121
+ # not seem to be a way to resolve generic TypeVars for inherited subclasses
122
+ # without using it.
123
+ if isinstance(cls, InheritsGeneric):
124
+ target_base_class: Any | None = None
125
+ for base in cls.__orig_bases__:
126
+ if base.__origin__ in generic_bases:
127
+ target_base_class = base
128
+ break
129
+
130
+ if target_base_class is None:
131
+ raise RuntimeError(
132
+ "Could not find the generic base class;\n"
133
+ "This should never happen;\n"
134
+ f"Does {cls} inherit from one of {generic_bases} ?"
135
+ )
136
+
137
+ extracted = extract_type_arg(target_base_class, index)
138
+ if is_typevar(extracted):
139
+ # If the extracted type argument is itself a type variable
140
+ # then that means the subclass itself is generic, so we have
141
+ # to resolve the type argument from the class itself, not
142
+ # the base class.
143
+ #
144
+ # Note: if there is more than 1 type argument, the subclass could
145
+ # change the ordering of the type arguments, this is not currently
146
+ # supported.
147
+ return extract_type_arg(typ, index)
148
+
149
+ return extracted
150
+
151
+ raise RuntimeError(failure_message or f"Could not resolve inner type variable at index {index} for {typ}")
python_embeded/Lib/site-packages/openai/_utils/_utils.py ADDED
@@ -0,0 +1,438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import re
5
+ import inspect
6
+ import functools
7
+ from typing import (
8
+ TYPE_CHECKING,
9
+ Any,
10
+ Tuple,
11
+ Mapping,
12
+ TypeVar,
13
+ Callable,
14
+ Iterable,
15
+ Sequence,
16
+ cast,
17
+ overload,
18
+ )
19
+ from pathlib import Path
20
+ from datetime import date, datetime
21
+ from typing_extensions import TypeGuard
22
+
23
+ import sniffio
24
+
25
+ from .._types import NotGiven, FileTypes, NotGivenOr, HeadersLike
26
+ from .._compat import parse_date as parse_date, parse_datetime as parse_datetime
27
+
28
+ _T = TypeVar("_T")
29
+ _TupleT = TypeVar("_TupleT", bound=Tuple[object, ...])
30
+ _MappingT = TypeVar("_MappingT", bound=Mapping[str, object])
31
+ _SequenceT = TypeVar("_SequenceT", bound=Sequence[object])
32
+ CallableT = TypeVar("CallableT", bound=Callable[..., Any])
33
+
34
+ if TYPE_CHECKING:
35
+ from ..lib.azure import AzureOpenAI, AsyncAzureOpenAI
36
+
37
+
38
+ def flatten(t: Iterable[Iterable[_T]]) -> list[_T]:
39
+ return [item for sublist in t for item in sublist]
40
+
41
+
42
+ def extract_files(
43
+ # TODO: this needs to take Dict but variance issues.....
44
+ # create protocol type ?
45
+ query: Mapping[str, object],
46
+ *,
47
+ paths: Sequence[Sequence[str]],
48
+ ) -> list[tuple[str, FileTypes]]:
49
+ """Recursively extract files from the given dictionary based on specified paths.
50
+
51
+ A path may look like this ['foo', 'files', '<array>', 'data'].
52
+
53
+ Note: this mutates the given dictionary.
54
+ """
55
+ files: list[tuple[str, FileTypes]] = []
56
+ for path in paths:
57
+ files.extend(_extract_items(query, path, index=0, flattened_key=None))
58
+ return files
59
+
60
+
61
+ def _extract_items(
62
+ obj: object,
63
+ path: Sequence[str],
64
+ *,
65
+ index: int,
66
+ flattened_key: str | None,
67
+ ) -> list[tuple[str, FileTypes]]:
68
+ try:
69
+ key = path[index]
70
+ except IndexError:
71
+ if isinstance(obj, NotGiven):
72
+ # no value was provided - we can safely ignore
73
+ return []
74
+
75
+ # cyclical import
76
+ from .._files import assert_is_file_content
77
+
78
+ # We have exhausted the path, return the entry we found.
79
+ assert flattened_key is not None
80
+
81
+ if is_list(obj):
82
+ files: list[tuple[str, FileTypes]] = []
83
+ for entry in obj:
84
+ assert_is_file_content(entry, key=flattened_key + "[]" if flattened_key else "")
85
+ files.append((flattened_key + "[]", cast(FileTypes, entry)))
86
+ return files
87
+
88
+ assert_is_file_content(obj, key=flattened_key)
89
+ return [(flattened_key, cast(FileTypes, obj))]
90
+
91
+ index += 1
92
+ if is_dict(obj):
93
+ try:
94
+ # We are at the last entry in the path so we must remove the field
95
+ if (len(path)) == index:
96
+ item = obj.pop(key)
97
+ else:
98
+ item = obj[key]
99
+ except KeyError:
100
+ # Key was not present in the dictionary, this is not indicative of an error
101
+ # as the given path may not point to a required field. We also do not want
102
+ # to enforce required fields as the API may differ from the spec in some cases.
103
+ return []
104
+ if flattened_key is None:
105
+ flattened_key = key
106
+ else:
107
+ flattened_key += f"[{key}]"
108
+ return _extract_items(
109
+ item,
110
+ path,
111
+ index=index,
112
+ flattened_key=flattened_key,
113
+ )
114
+ elif is_list(obj):
115
+ if key != "<array>":
116
+ return []
117
+
118
+ return flatten(
119
+ [
120
+ _extract_items(
121
+ item,
122
+ path,
123
+ index=index,
124
+ flattened_key=flattened_key + "[]" if flattened_key is not None else "[]",
125
+ )
126
+ for item in obj
127
+ ]
128
+ )
129
+
130
+ # Something unexpected was passed, just ignore it.
131
+ return []
132
+
133
+
134
+ def is_given(obj: NotGivenOr[_T]) -> TypeGuard[_T]:
135
+ return not isinstance(obj, NotGiven)
136
+
137
+
138
+ # Type safe methods for narrowing types with TypeVars.
139
+ # The default narrowing for isinstance(obj, dict) is dict[unknown, unknown],
140
+ # however this cause Pyright to rightfully report errors. As we know we don't
141
+ # care about the contained types we can safely use `object` in it's place.
142
+ #
143
+ # There are two separate functions defined, `is_*` and `is_*_t` for different use cases.
144
+ # `is_*` is for when you're dealing with an unknown input
145
+ # `is_*_t` is for when you're narrowing a known union type to a specific subset
146
+
147
+
148
+ def is_tuple(obj: object) -> TypeGuard[tuple[object, ...]]:
149
+ return isinstance(obj, tuple)
150
+
151
+
152
+ def is_tuple_t(obj: _TupleT | object) -> TypeGuard[_TupleT]:
153
+ return isinstance(obj, tuple)
154
+
155
+
156
+ def is_sequence(obj: object) -> TypeGuard[Sequence[object]]:
157
+ return isinstance(obj, Sequence)
158
+
159
+
160
+ def is_sequence_t(obj: _SequenceT | object) -> TypeGuard[_SequenceT]:
161
+ return isinstance(obj, Sequence)
162
+
163
+
164
+ def is_mapping(obj: object) -> TypeGuard[Mapping[str, object]]:
165
+ return isinstance(obj, Mapping)
166
+
167
+
168
+ def is_mapping_t(obj: _MappingT | object) -> TypeGuard[_MappingT]:
169
+ return isinstance(obj, Mapping)
170
+
171
+
172
+ def is_dict(obj: object) -> TypeGuard[dict[object, object]]:
173
+ return isinstance(obj, dict)
174
+
175
+
176
+ def is_list(obj: object) -> TypeGuard[list[object]]:
177
+ return isinstance(obj, list)
178
+
179
+
180
+ def is_iterable(obj: object) -> TypeGuard[Iterable[object]]:
181
+ return isinstance(obj, Iterable)
182
+
183
+
184
+ def deepcopy_minimal(item: _T) -> _T:
185
+ """Minimal reimplementation of copy.deepcopy() that will only copy certain object types:
186
+
187
+ - mappings, e.g. `dict`
188
+ - list
189
+
190
+ This is done for performance reasons.
191
+ """
192
+ if is_mapping(item):
193
+ return cast(_T, {k: deepcopy_minimal(v) for k, v in item.items()})
194
+ if is_list(item):
195
+ return cast(_T, [deepcopy_minimal(entry) for entry in item])
196
+ return item
197
+
198
+
199
+ # copied from https://github.com/Rapptz/RoboDanny
200
+ def human_join(seq: Sequence[str], *, delim: str = ", ", final: str = "or") -> str:
201
+ size = len(seq)
202
+ if size == 0:
203
+ return ""
204
+
205
+ if size == 1:
206
+ return seq[0]
207
+
208
+ if size == 2:
209
+ return f"{seq[0]} {final} {seq[1]}"
210
+
211
+ return delim.join(seq[:-1]) + f" {final} {seq[-1]}"
212
+
213
+
214
+ def quote(string: str) -> str:
215
+ """Add single quotation marks around the given string. Does *not* do any escaping."""
216
+ return f"'{string}'"
217
+
218
+
219
+ def required_args(*variants: Sequence[str]) -> Callable[[CallableT], CallableT]:
220
+ """Decorator to enforce a given set of arguments or variants of arguments are passed to the decorated function.
221
+
222
+ Useful for enforcing runtime validation of overloaded functions.
223
+
224
+ Example usage:
225
+ ```py
226
+ @overload
227
+ def foo(*, a: str) -> str: ...
228
+
229
+
230
+ @overload
231
+ def foo(*, b: bool) -> str: ...
232
+
233
+
234
+ # This enforces the same constraints that a static type checker would
235
+ # i.e. that either a or b must be passed to the function
236
+ @required_args(["a"], ["b"])
237
+ def foo(*, a: str | None = None, b: bool | None = None) -> str: ...
238
+ ```
239
+ """
240
+
241
+ def inner(func: CallableT) -> CallableT:
242
+ params = inspect.signature(func).parameters
243
+ positional = [
244
+ name
245
+ for name, param in params.items()
246
+ if param.kind
247
+ in {
248
+ param.POSITIONAL_ONLY,
249
+ param.POSITIONAL_OR_KEYWORD,
250
+ }
251
+ ]
252
+
253
+ @functools.wraps(func)
254
+ def wrapper(*args: object, **kwargs: object) -> object:
255
+ given_params: set[str] = set()
256
+ for i, _ in enumerate(args):
257
+ try:
258
+ given_params.add(positional[i])
259
+ except IndexError:
260
+ raise TypeError(
261
+ f"{func.__name__}() takes {len(positional)} argument(s) but {len(args)} were given"
262
+ ) from None
263
+
264
+ for key in kwargs.keys():
265
+ given_params.add(key)
266
+
267
+ for variant in variants:
268
+ matches = all((param in given_params for param in variant))
269
+ if matches:
270
+ break
271
+ else: # no break
272
+ if len(variants) > 1:
273
+ variations = human_join(
274
+ ["(" + human_join([quote(arg) for arg in variant], final="and") + ")" for variant in variants]
275
+ )
276
+ msg = f"Missing required arguments; Expected either {variations} arguments to be given"
277
+ else:
278
+ assert len(variants) > 0
279
+
280
+ # TODO: this error message is not deterministic
281
+ missing = list(set(variants[0]) - given_params)
282
+ if len(missing) > 1:
283
+ msg = f"Missing required arguments: {human_join([quote(arg) for arg in missing])}"
284
+ else:
285
+ msg = f"Missing required argument: {quote(missing[0])}"
286
+ raise TypeError(msg)
287
+ return func(*args, **kwargs)
288
+
289
+ return wrapper # type: ignore
290
+
291
+ return inner
292
+
293
+
294
+ _K = TypeVar("_K")
295
+ _V = TypeVar("_V")
296
+
297
+
298
+ @overload
299
+ def strip_not_given(obj: None) -> None: ...
300
+
301
+
302
+ @overload
303
+ def strip_not_given(obj: Mapping[_K, _V | NotGiven]) -> dict[_K, _V]: ...
304
+
305
+
306
+ @overload
307
+ def strip_not_given(obj: object) -> object: ...
308
+
309
+
310
+ def strip_not_given(obj: object | None) -> object:
311
+ """Remove all top-level keys where their values are instances of `NotGiven`"""
312
+ if obj is None:
313
+ return None
314
+
315
+ if not is_mapping(obj):
316
+ return obj
317
+
318
+ return {key: value for key, value in obj.items() if not isinstance(value, NotGiven)}
319
+
320
+
321
+ def coerce_integer(val: str) -> int:
322
+ return int(val, base=10)
323
+
324
+
325
+ def coerce_float(val: str) -> float:
326
+ return float(val)
327
+
328
+
329
+ def coerce_boolean(val: str) -> bool:
330
+ return val == "true" or val == "1" or val == "on"
331
+
332
+
333
+ def maybe_coerce_integer(val: str | None) -> int | None:
334
+ if val is None:
335
+ return None
336
+ return coerce_integer(val)
337
+
338
+
339
+ def maybe_coerce_float(val: str | None) -> float | None:
340
+ if val is None:
341
+ return None
342
+ return coerce_float(val)
343
+
344
+
345
+ def maybe_coerce_boolean(val: str | None) -> bool | None:
346
+ if val is None:
347
+ return None
348
+ return coerce_boolean(val)
349
+
350
+
351
+ def removeprefix(string: str, prefix: str) -> str:
352
+ """Remove a prefix from a string.
353
+
354
+ Backport of `str.removeprefix` for Python < 3.9
355
+ """
356
+ if string.startswith(prefix):
357
+ return string[len(prefix) :]
358
+ return string
359
+
360
+
361
+ def removesuffix(string: str, suffix: str) -> str:
362
+ """Remove a suffix from a string.
363
+
364
+ Backport of `str.removesuffix` for Python < 3.9
365
+ """
366
+ if string.endswith(suffix):
367
+ return string[: -len(suffix)]
368
+ return string
369
+
370
+
371
+ def file_from_path(path: str) -> FileTypes:
372
+ contents = Path(path).read_bytes()
373
+ file_name = os.path.basename(path)
374
+ return (file_name, contents)
375
+
376
+
377
+ def get_required_header(headers: HeadersLike, header: str) -> str:
378
+ lower_header = header.lower()
379
+ if is_mapping_t(headers):
380
+ # mypy doesn't understand the type narrowing here
381
+ for k, v in headers.items(): # type: ignore
382
+ if k.lower() == lower_header and isinstance(v, str):
383
+ return v
384
+
385
+ # to deal with the case where the header looks like Stainless-Event-Id
386
+ intercaps_header = re.sub(r"([^\w])(\w)", lambda pat: pat.group(1) + pat.group(2).upper(), header.capitalize())
387
+
388
+ for normalized_header in [header, lower_header, header.upper(), intercaps_header]:
389
+ value = headers.get(normalized_header)
390
+ if value:
391
+ return value
392
+
393
+ raise ValueError(f"Could not find {header} header")
394
+
395
+
396
+ def get_async_library() -> str:
397
+ try:
398
+ return sniffio.current_async_library()
399
+ except Exception:
400
+ return "false"
401
+
402
+
403
+ def lru_cache(*, maxsize: int | None = 128) -> Callable[[CallableT], CallableT]:
404
+ """A version of functools.lru_cache that retains the type signature
405
+ for the wrapped function arguments.
406
+ """
407
+ wrapper = functools.lru_cache( # noqa: TID251
408
+ maxsize=maxsize,
409
+ )
410
+ return cast(Any, wrapper) # type: ignore[no-any-return]
411
+
412
+
413
+ def json_safe(data: object) -> object:
414
+ """Translates a mapping / sequence recursively in the same fashion
415
+ as `pydantic` v2's `model_dump(mode="json")`.
416
+ """
417
+ if is_mapping(data):
418
+ return {json_safe(key): json_safe(value) for key, value in data.items()}
419
+
420
+ if is_iterable(data) and not isinstance(data, (str, bytes, bytearray)):
421
+ return [json_safe(item) for item in data]
422
+
423
+ if isinstance(data, (datetime, date)):
424
+ return data.isoformat()
425
+
426
+ return data
427
+
428
+
429
+ def is_azure_client(client: object) -> TypeGuard[AzureOpenAI]:
430
+ from ..lib.azure import AzureOpenAI
431
+
432
+ return isinstance(client, AzureOpenAI)
433
+
434
+
435
+ def is_async_azure_client(client: object) -> TypeGuard[AsyncAzureOpenAI]:
436
+ from ..lib.azure import AsyncAzureOpenAI
437
+
438
+ return isinstance(client, AsyncAzureOpenAI)
python_embeded/Lib/site-packages/openai/cli/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from ._cli import main as main
python_embeded/Lib/site-packages/openai/cli/_cli.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ import logging
5
+ import argparse
6
+ from typing import Any, List, Type, Optional
7
+ from typing_extensions import ClassVar
8
+
9
+ import httpx
10
+ import pydantic
11
+
12
+ import openai
13
+
14
+ from . import _tools
15
+ from .. import _ApiType, __version__
16
+ from ._api import register_commands
17
+ from ._utils import can_use_http2
18
+ from ._errors import CLIError, display_error
19
+ from .._compat import PYDANTIC_V2, ConfigDict, model_parse
20
+ from .._models import BaseModel
21
+ from .._exceptions import APIError
22
+
23
+ logger = logging.getLogger()
24
+ formatter = logging.Formatter("[%(asctime)s] %(message)s")
25
+ handler = logging.StreamHandler(sys.stderr)
26
+ handler.setFormatter(formatter)
27
+ logger.addHandler(handler)
28
+
29
+
30
+ class Arguments(BaseModel):
31
+ if PYDANTIC_V2:
32
+ model_config: ClassVar[ConfigDict] = ConfigDict(
33
+ extra="ignore",
34
+ )
35
+ else:
36
+
37
+ class Config(pydantic.BaseConfig): # type: ignore
38
+ extra: Any = pydantic.Extra.ignore # type: ignore
39
+
40
+ verbosity: int
41
+ version: Optional[str] = None
42
+
43
+ api_key: Optional[str]
44
+ api_base: Optional[str]
45
+ organization: Optional[str]
46
+ proxy: Optional[List[str]]
47
+ api_type: Optional[_ApiType] = None
48
+ api_version: Optional[str] = None
49
+
50
+ # azure
51
+ azure_endpoint: Optional[str] = None
52
+ azure_ad_token: Optional[str] = None
53
+
54
+ # internal, set by subparsers to parse their specific args
55
+ args_model: Optional[Type[BaseModel]] = None
56
+
57
+ # internal, used so that subparsers can forward unknown arguments
58
+ unknown_args: List[str] = []
59
+ allow_unknown_args: bool = False
60
+
61
+
62
+ def _build_parser() -> argparse.ArgumentParser:
63
+ parser = argparse.ArgumentParser(description=None, prog="openai")
64
+ parser.add_argument(
65
+ "-v",
66
+ "--verbose",
67
+ action="count",
68
+ dest="verbosity",
69
+ default=0,
70
+ help="Set verbosity.",
71
+ )
72
+ parser.add_argument("-b", "--api-base", help="What API base url to use.")
73
+ parser.add_argument("-k", "--api-key", help="What API key to use.")
74
+ parser.add_argument("-p", "--proxy", nargs="+", help="What proxy to use.")
75
+ parser.add_argument(
76
+ "-o",
77
+ "--organization",
78
+ help="Which organization to run as (will use your default organization if not specified)",
79
+ )
80
+ parser.add_argument(
81
+ "-t",
82
+ "--api-type",
83
+ type=str,
84
+ choices=("openai", "azure"),
85
+ help="The backend API to call, must be `openai` or `azure`",
86
+ )
87
+ parser.add_argument(
88
+ "--api-version",
89
+ help="The Azure API version, e.g. 'https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#rest-api-versioning'",
90
+ )
91
+
92
+ # azure
93
+ parser.add_argument(
94
+ "--azure-endpoint",
95
+ help="The Azure endpoint, e.g. 'https://endpoint.openai.azure.com'",
96
+ )
97
+ parser.add_argument(
98
+ "--azure-ad-token",
99
+ help="A token from Azure Active Directory, https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id",
100
+ )
101
+
102
+ # prints the package version
103
+ parser.add_argument(
104
+ "-V",
105
+ "--version",
106
+ action="version",
107
+ version="%(prog)s " + __version__,
108
+ )
109
+
110
+ def help() -> None:
111
+ parser.print_help()
112
+
113
+ parser.set_defaults(func=help)
114
+
115
+ subparsers = parser.add_subparsers()
116
+ sub_api = subparsers.add_parser("api", help="Direct API calls")
117
+
118
+ register_commands(sub_api)
119
+
120
+ sub_tools = subparsers.add_parser("tools", help="Client side tools for convenience")
121
+ _tools.register_commands(sub_tools, subparsers)
122
+
123
+ return parser
124
+
125
+
126
+ def main() -> int:
127
+ try:
128
+ _main()
129
+ except (APIError, CLIError, pydantic.ValidationError) as err:
130
+ display_error(err)
131
+ return 1
132
+ except KeyboardInterrupt:
133
+ sys.stderr.write("\n")
134
+ return 1
135
+ return 0
136
+
137
+
138
+ def _parse_args(parser: argparse.ArgumentParser) -> tuple[argparse.Namespace, Arguments, list[str]]:
139
+ # argparse by default will strip out the `--` but we want to keep it for unknown arguments
140
+ if "--" in sys.argv:
141
+ idx = sys.argv.index("--")
142
+ known_args = sys.argv[1:idx]
143
+ unknown_args = sys.argv[idx:]
144
+ else:
145
+ known_args = sys.argv[1:]
146
+ unknown_args = []
147
+
148
+ parsed, remaining_unknown = parser.parse_known_args(known_args)
149
+
150
+ # append any remaining unknown arguments from the initial parsing
151
+ remaining_unknown.extend(unknown_args)
152
+
153
+ args = model_parse(Arguments, vars(parsed))
154
+ if not args.allow_unknown_args:
155
+ # we have to parse twice to ensure any unknown arguments
156
+ # result in an error if that behaviour is desired
157
+ parser.parse_args()
158
+
159
+ return parsed, args, remaining_unknown
160
+
161
+
162
+ def _main() -> None:
163
+ parser = _build_parser()
164
+ parsed, args, unknown = _parse_args(parser)
165
+
166
+ if args.verbosity != 0:
167
+ sys.stderr.write("Warning: --verbosity isn't supported yet\n")
168
+
169
+ proxies: dict[str, httpx.BaseTransport] = {}
170
+ if args.proxy is not None:
171
+ for proxy in args.proxy:
172
+ key = "https://" if proxy.startswith("https") else "http://"
173
+ if key in proxies:
174
+ raise CLIError(f"Multiple {key} proxies given - only the last one would be used")
175
+
176
+ proxies[key] = httpx.HTTPTransport(proxy=httpx.Proxy(httpx.URL(proxy)))
177
+
178
+ http_client = httpx.Client(
179
+ mounts=proxies or None,
180
+ http2=can_use_http2(),
181
+ )
182
+ openai.http_client = http_client
183
+
184
+ if args.organization:
185
+ openai.organization = args.organization
186
+
187
+ if args.api_key:
188
+ openai.api_key = args.api_key
189
+
190
+ if args.api_base:
191
+ openai.base_url = args.api_base
192
+
193
+ # azure
194
+ if args.api_type is not None:
195
+ openai.api_type = args.api_type
196
+
197
+ if args.azure_endpoint is not None:
198
+ openai.azure_endpoint = args.azure_endpoint
199
+
200
+ if args.api_version is not None:
201
+ openai.api_version = args.api_version
202
+
203
+ if args.azure_ad_token is not None:
204
+ openai.azure_ad_token = args.azure_ad_token
205
+
206
+ try:
207
+ if args.args_model:
208
+ parsed.func(
209
+ model_parse(
210
+ args.args_model,
211
+ {
212
+ **{
213
+ # we omit None values so that they can be defaulted to `NotGiven`
214
+ # and we'll strip it from the API request
215
+ key: value
216
+ for key, value in vars(parsed).items()
217
+ if value is not None
218
+ },
219
+ "unknown_args": unknown,
220
+ },
221
+ )
222
+ )
223
+ else:
224
+ parsed.func()
225
+ finally:
226
+ try:
227
+ http_client.close()
228
+ except Exception:
229
+ pass
230
+
231
+
232
+ if __name__ == "__main__":
233
+ sys.exit(main())
python_embeded/Lib/site-packages/openai/cli/_errors.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+
5
+ import pydantic
6
+
7
+ from ._utils import Colors, organization_info
8
+ from .._exceptions import APIError, OpenAIError
9
+
10
+
11
+ class CLIError(OpenAIError): ...
12
+
13
+
14
+ class SilentCLIError(CLIError): ...
15
+
16
+
17
+ def display_error(err: CLIError | APIError | pydantic.ValidationError) -> None:
18
+ if isinstance(err, SilentCLIError):
19
+ return
20
+
21
+ sys.stderr.write("{}{}Error:{} {}\n".format(organization_info(), Colors.FAIL, Colors.ENDC, err))
python_embeded/Lib/site-packages/openai/cli/_models.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+ from typing_extensions import ClassVar
3
+
4
+ import pydantic
5
+
6
+ from .. import _models
7
+ from .._compat import PYDANTIC_V2, ConfigDict
8
+
9
+
10
+ class BaseModel(_models.BaseModel):
11
+ if PYDANTIC_V2:
12
+ model_config: ClassVar[ConfigDict] = ConfigDict(extra="ignore", arbitrary_types_allowed=True)
13
+ else:
14
+
15
+ class Config(pydantic.BaseConfig): # type: ignore
16
+ extra: Any = pydantic.Extra.ignore # type: ignore
17
+ arbitrary_types_allowed: bool = True
python_embeded/Lib/site-packages/openai/cli/_progress.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ from typing import Callable
5
+ from typing_extensions import override
6
+
7
+
8
+ class CancelledError(Exception):
9
+ def __init__(self, msg: str) -> None:
10
+ self.msg = msg
11
+ super().__init__(msg)
12
+
13
+ @override
14
+ def __str__(self) -> str:
15
+ return self.msg
16
+
17
+ __repr__ = __str__
18
+
19
+
20
+ class BufferReader(io.BytesIO):
21
+ def __init__(self, buf: bytes = b"", desc: str | None = None) -> None:
22
+ super().__init__(buf)
23
+ self._len = len(buf)
24
+ self._progress = 0
25
+ self._callback = progress(len(buf), desc=desc)
26
+
27
+ def __len__(self) -> int:
28
+ return self._len
29
+
30
+ @override
31
+ def read(self, n: int | None = -1) -> bytes:
32
+ chunk = io.BytesIO.read(self, n)
33
+ self._progress += len(chunk)
34
+
35
+ try:
36
+ self._callback(self._progress)
37
+ except Exception as e: # catches exception from the callback
38
+ raise CancelledError("The upload was cancelled: {}".format(e)) from e
39
+
40
+ return chunk
41
+
42
+
43
+ def progress(total: float, desc: str | None) -> Callable[[float], None]:
44
+ import tqdm
45
+
46
+ meter = tqdm.tqdm(total=total, unit_scale=True, desc=desc)
47
+
48
+ def incr(progress: float) -> None:
49
+ meter.n = progress
50
+ if progress == total:
51
+ meter.close()
52
+ else:
53
+ meter.refresh()
54
+
55
+ return incr
56
+
57
+
58
+ def MB(i: int) -> int:
59
+ return int(i // 1024**2)
python_embeded/Lib/site-packages/openai/cli/_utils.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+
5
+ import openai
6
+
7
+ from .. import OpenAI, _load_client
8
+ from .._compat import model_json
9
+ from .._models import BaseModel
10
+
11
+
12
+ class Colors:
13
+ HEADER = "\033[95m"
14
+ OKBLUE = "\033[94m"
15
+ OKGREEN = "\033[92m"
16
+ WARNING = "\033[93m"
17
+ FAIL = "\033[91m"
18
+ ENDC = "\033[0m"
19
+ BOLD = "\033[1m"
20
+ UNDERLINE = "\033[4m"
21
+
22
+
23
+ def get_client() -> OpenAI:
24
+ return _load_client()
25
+
26
+
27
+ def organization_info() -> str:
28
+ organization = openai.organization
29
+ if organization is not None:
30
+ return "[organization={}] ".format(organization)
31
+
32
+ return ""
33
+
34
+
35
+ def print_model(model: BaseModel) -> None:
36
+ sys.stdout.write(model_json(model, indent=2) + "\n")
37
+
38
+
39
+ def can_use_http2() -> bool:
40
+ try:
41
+ import h2 # type: ignore # noqa
42
+ except ImportError:
43
+ return False
44
+
45
+ return True
python_embeded/Lib/site-packages/openai/helpers/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .microphone import Microphone
2
+ from .local_audio_player import LocalAudioPlayer
3
+
4
+ __all__ = ["Microphone", "LocalAudioPlayer"]
python_embeded/Lib/site-packages/openai/helpers/local_audio_player.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+ from __future__ import annotations
3
+
4
+ import queue
5
+ import asyncio
6
+ from typing import Any, Union, Callable, AsyncGenerator, cast
7
+ from typing_extensions import TYPE_CHECKING
8
+
9
+ from .. import _legacy_response
10
+ from .._extras import numpy as np, sounddevice as sd
11
+ from .._response import StreamedBinaryAPIResponse, AsyncStreamedBinaryAPIResponse
12
+
13
+ if TYPE_CHECKING:
14
+ import numpy.typing as npt
15
+
16
+ SAMPLE_RATE = 24000
17
+
18
+
19
+ class LocalAudioPlayer:
20
+ def __init__(
21
+ self,
22
+ should_stop: Union[Callable[[], bool], None] = None,
23
+ ):
24
+ self.channels = 1
25
+ self.dtype = np.float32
26
+ self.should_stop = should_stop
27
+
28
+ async def _tts_response_to_buffer(
29
+ self,
30
+ response: Union[
31
+ _legacy_response.HttpxBinaryResponseContent,
32
+ AsyncStreamedBinaryAPIResponse,
33
+ StreamedBinaryAPIResponse,
34
+ ],
35
+ ) -> npt.NDArray[np.float32]:
36
+ chunks: list[bytes] = []
37
+ if isinstance(response, _legacy_response.HttpxBinaryResponseContent) or isinstance(
38
+ response, StreamedBinaryAPIResponse
39
+ ):
40
+ for chunk in response.iter_bytes(chunk_size=1024):
41
+ if chunk:
42
+ chunks.append(chunk)
43
+ else:
44
+ async for chunk in response.iter_bytes(chunk_size=1024):
45
+ if chunk:
46
+ chunks.append(chunk)
47
+
48
+ audio_bytes = b"".join(chunks)
49
+ audio_np = np.frombuffer(audio_bytes, dtype=np.int16).astype(np.float32) / 32767.0
50
+ audio_np = audio_np.reshape(-1, 1)
51
+ return audio_np
52
+
53
+ async def play(
54
+ self,
55
+ input: Union[
56
+ npt.NDArray[np.int16],
57
+ npt.NDArray[np.float32],
58
+ _legacy_response.HttpxBinaryResponseContent,
59
+ AsyncStreamedBinaryAPIResponse,
60
+ StreamedBinaryAPIResponse,
61
+ ],
62
+ ) -> None:
63
+ audio_content: npt.NDArray[np.float32]
64
+ if isinstance(input, np.ndarray):
65
+ if input.dtype == np.int16 and self.dtype == np.float32:
66
+ audio_content = (input.astype(np.float32) / 32767.0).reshape(-1, self.channels)
67
+ elif input.dtype == np.float32:
68
+ audio_content = cast("npt.NDArray[np.float32]", input)
69
+ else:
70
+ raise ValueError(f"Unsupported dtype: {input.dtype}")
71
+ else:
72
+ audio_content = await self._tts_response_to_buffer(input)
73
+
74
+ loop = asyncio.get_event_loop()
75
+ event = asyncio.Event()
76
+ idx = 0
77
+
78
+ def callback(
79
+ outdata: npt.NDArray[np.float32],
80
+ frame_count: int,
81
+ _time_info: Any,
82
+ _status: Any,
83
+ ):
84
+ nonlocal idx
85
+
86
+ remainder = len(audio_content) - idx
87
+ if remainder == 0 or (callable(self.should_stop) and self.should_stop()):
88
+ loop.call_soon_threadsafe(event.set)
89
+ raise sd.CallbackStop
90
+ valid_frames = frame_count if remainder >= frame_count else remainder
91
+ outdata[:valid_frames] = audio_content[idx : idx + valid_frames]
92
+ outdata[valid_frames:] = 0
93
+ idx += valid_frames
94
+
95
+ stream = sd.OutputStream(
96
+ samplerate=SAMPLE_RATE,
97
+ callback=callback,
98
+ dtype=audio_content.dtype,
99
+ channels=audio_content.shape[1],
100
+ )
101
+ with stream:
102
+ await event.wait()
103
+
104
+ async def play_stream(
105
+ self,
106
+ buffer_stream: AsyncGenerator[Union[npt.NDArray[np.float32], npt.NDArray[np.int16], None], None],
107
+ ) -> None:
108
+ loop = asyncio.get_event_loop()
109
+ event = asyncio.Event()
110
+ buffer_queue: queue.Queue[Union[npt.NDArray[np.float32], npt.NDArray[np.int16], None]] = queue.Queue(maxsize=50)
111
+
112
+ async def buffer_producer():
113
+ async for buffer in buffer_stream:
114
+ if buffer is None:
115
+ break
116
+ await loop.run_in_executor(None, buffer_queue.put, buffer)
117
+ await loop.run_in_executor(None, buffer_queue.put, None) # Signal completion
118
+
119
+ def callback(
120
+ outdata: npt.NDArray[np.float32],
121
+ frame_count: int,
122
+ _time_info: Any,
123
+ _status: Any,
124
+ ):
125
+ nonlocal current_buffer, buffer_pos
126
+
127
+ frames_written = 0
128
+ while frames_written < frame_count:
129
+ if current_buffer is None or buffer_pos >= len(current_buffer):
130
+ try:
131
+ current_buffer = buffer_queue.get(timeout=0.1)
132
+ if current_buffer is None:
133
+ loop.call_soon_threadsafe(event.set)
134
+ raise sd.CallbackStop
135
+ buffer_pos = 0
136
+
137
+ if current_buffer.dtype == np.int16 and self.dtype == np.float32:
138
+ current_buffer = (current_buffer.astype(np.float32) / 32767.0).reshape(-1, self.channels)
139
+
140
+ except queue.Empty:
141
+ outdata[frames_written:] = 0
142
+ return
143
+
144
+ remaining_frames = len(current_buffer) - buffer_pos
145
+ frames_to_write = min(frame_count - frames_written, remaining_frames)
146
+ outdata[frames_written : frames_written + frames_to_write] = current_buffer[
147
+ buffer_pos : buffer_pos + frames_to_write
148
+ ]
149
+ buffer_pos += frames_to_write
150
+ frames_written += frames_to_write
151
+
152
+ current_buffer = None
153
+ buffer_pos = 0
154
+
155
+ producer_task = asyncio.create_task(buffer_producer())
156
+
157
+ with sd.OutputStream(
158
+ samplerate=SAMPLE_RATE,
159
+ channels=self.channels,
160
+ dtype=self.dtype,
161
+ callback=callback,
162
+ ):
163
+ await event.wait()
164
+
165
+ await producer_task
python_embeded/Lib/site-packages/openai/helpers/microphone.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+ from __future__ import annotations
3
+
4
+ import io
5
+ import time
6
+ import wave
7
+ import asyncio
8
+ from typing import Any, Type, Union, Generic, TypeVar, Callable, overload
9
+ from typing_extensions import TYPE_CHECKING, Literal
10
+
11
+ from .._types import FileTypes, FileContent
12
+ from .._extras import numpy as np, sounddevice as sd
13
+
14
+ if TYPE_CHECKING:
15
+ import numpy.typing as npt
16
+
17
+ SAMPLE_RATE = 24000
18
+
19
+ DType = TypeVar("DType", bound=np.generic)
20
+
21
+
22
+ class Microphone(Generic[DType]):
23
+ def __init__(
24
+ self,
25
+ channels: int = 1,
26
+ dtype: Type[DType] = np.int16,
27
+ should_record: Union[Callable[[], bool], None] = None,
28
+ timeout: Union[float, None] = None,
29
+ ):
30
+ self.channels = channels
31
+ self.dtype = dtype
32
+ self.should_record = should_record
33
+ self.buffer_chunks = []
34
+ self.timeout = timeout
35
+ self.has_record_function = callable(should_record)
36
+
37
+ def _ndarray_to_wav(self, audio_data: npt.NDArray[DType]) -> FileTypes:
38
+ buffer: FileContent = io.BytesIO()
39
+ with wave.open(buffer, "w") as wav_file:
40
+ wav_file.setnchannels(self.channels)
41
+ wav_file.setsampwidth(np.dtype(self.dtype).itemsize)
42
+ wav_file.setframerate(SAMPLE_RATE)
43
+ wav_file.writeframes(audio_data.tobytes())
44
+ buffer.seek(0)
45
+ return ("audio.wav", buffer, "audio/wav")
46
+
47
+ @overload
48
+ async def record(self, return_ndarray: Literal[True]) -> npt.NDArray[DType]: ...
49
+
50
+ @overload
51
+ async def record(self, return_ndarray: Literal[False]) -> FileTypes: ...
52
+
53
+ @overload
54
+ async def record(self, return_ndarray: None = ...) -> FileTypes: ...
55
+
56
+ async def record(self, return_ndarray: Union[bool, None] = False) -> Union[npt.NDArray[DType], FileTypes]:
57
+ loop = asyncio.get_event_loop()
58
+ event = asyncio.Event()
59
+ self.buffer_chunks: list[npt.NDArray[DType]] = []
60
+ start_time = time.perf_counter()
61
+
62
+ def callback(
63
+ indata: npt.NDArray[DType],
64
+ _frame_count: int,
65
+ _time_info: Any,
66
+ _status: Any,
67
+ ):
68
+ execution_time = time.perf_counter() - start_time
69
+ reached_recording_timeout = execution_time > self.timeout if self.timeout is not None else False
70
+ if reached_recording_timeout:
71
+ loop.call_soon_threadsafe(event.set)
72
+ raise sd.CallbackStop
73
+
74
+ should_be_recording = self.should_record() if callable(self.should_record) else True
75
+ if not should_be_recording:
76
+ loop.call_soon_threadsafe(event.set)
77
+ raise sd.CallbackStop
78
+
79
+ self.buffer_chunks.append(indata.copy())
80
+
81
+ stream = sd.InputStream(
82
+ callback=callback,
83
+ dtype=self.dtype,
84
+ samplerate=SAMPLE_RATE,
85
+ channels=self.channels,
86
+ )
87
+ with stream:
88
+ await event.wait()
89
+
90
+ # Concatenate all chunks into a single buffer, handle empty case
91
+ concatenated_chunks: npt.NDArray[DType] = (
92
+ np.concatenate(self.buffer_chunks, axis=0)
93
+ if len(self.buffer_chunks) > 0
94
+ else np.array([], dtype=self.dtype)
95
+ )
96
+
97
+ if return_ndarray:
98
+ return concatenated_chunks
99
+ else:
100
+ return self._ndarray_to_wav(concatenated_chunks)
python_embeded/Lib/site-packages/openai/lib/.keep ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ File generated from our OpenAPI spec by Stainless.
2
+
3
+ This directory can be used to store custom files to expand the SDK.
4
+ It is ignored by Stainless code generation and its content (other than this keep file) won't be touched.
python_embeded/Lib/site-packages/openai/lib/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from ._tools import pydantic_function_tool as pydantic_function_tool
2
+ from ._parsing import ResponseFormatT as ResponseFormatT
python_embeded/Lib/site-packages/openai/lib/_old_api.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, Any
4
+ from typing_extensions import override
5
+
6
+ from .._utils import LazyProxy
7
+ from .._exceptions import OpenAIError
8
+
9
+ INSTRUCTIONS = """
10
+
11
+ You tried to access openai.{symbol}, but this is no longer supported in openai>=1.0.0 - see the README at https://github.com/openai/openai-python for the API.
12
+
13
+ You can run `openai migrate` to automatically upgrade your codebase to use the 1.0.0 interface.
14
+
15
+ Alternatively, you can pin your installation to the old version, e.g. `pip install openai==0.28`
16
+
17
+ A detailed migration guide is available here: https://github.com/openai/openai-python/discussions/742
18
+ """
19
+
20
+
21
+ class APIRemovedInV1(OpenAIError):
22
+ def __init__(self, *, symbol: str) -> None:
23
+ super().__init__(INSTRUCTIONS.format(symbol=symbol))
24
+
25
+
26
+ class APIRemovedInV1Proxy(LazyProxy[Any]):
27
+ def __init__(self, *, symbol: str) -> None:
28
+ super().__init__()
29
+ self._symbol = symbol
30
+
31
+ @override
32
+ def __load__(self) -> Any:
33
+ # return the proxy until it is eventually called so that
34
+ # we don't break people that are just checking the attributes
35
+ # of a module
36
+ return self
37
+
38
+ def __call__(self, *_args: Any, **_kwargs: Any) -> Any:
39
+ raise APIRemovedInV1(symbol=self._symbol)
40
+
41
+
42
+ SYMBOLS = [
43
+ "Edit",
44
+ "File",
45
+ "Audio",
46
+ "Image",
47
+ "Model",
48
+ "Engine",
49
+ "Customer",
50
+ "FineTune",
51
+ "Embedding",
52
+ "Completion",
53
+ "Deployment",
54
+ "Moderation",
55
+ "ErrorObject",
56
+ "FineTuningJob",
57
+ "ChatCompletion",
58
+ ]
59
+
60
+ # we explicitly tell type checkers that nothing is exported
61
+ # from this file so that when we re-export the old symbols
62
+ # in `openai/__init__.py` they aren't added to the auto-complete
63
+ # suggestions given by editors
64
+ if TYPE_CHECKING:
65
+ __all__: list[str] = []
66
+ else:
67
+ __all__ = SYMBOLS
68
+
69
+
70
+ __locals = locals()
71
+ for symbol in SYMBOLS:
72
+ __locals[symbol] = APIRemovedInV1Proxy(symbol=symbol)
python_embeded/Lib/site-packages/openai/lib/_pydantic.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ from typing import Any, TypeVar
5
+ from typing_extensions import TypeGuard
6
+
7
+ import pydantic
8
+
9
+ from .._types import NOT_GIVEN
10
+ from .._utils import is_dict as _is_dict, is_list
11
+ from .._compat import PYDANTIC_V2, model_json_schema
12
+
13
+ _T = TypeVar("_T")
14
+
15
+
16
+ def to_strict_json_schema(model: type[pydantic.BaseModel] | pydantic.TypeAdapter[Any]) -> dict[str, Any]:
17
+ if inspect.isclass(model) and is_basemodel_type(model):
18
+ schema = model_json_schema(model)
19
+ elif PYDANTIC_V2 and isinstance(model, pydantic.TypeAdapter):
20
+ schema = model.json_schema()
21
+ else:
22
+ raise TypeError(f"Non BaseModel types are only supported with Pydantic v2 - {model}")
23
+
24
+ return _ensure_strict_json_schema(schema, path=(), root=schema)
25
+
26
+
27
+ def _ensure_strict_json_schema(
28
+ json_schema: object,
29
+ *,
30
+ path: tuple[str, ...],
31
+ root: dict[str, object],
32
+ ) -> dict[str, Any]:
33
+ """Mutates the given JSON schema to ensure it conforms to the `strict` standard
34
+ that the API expects.
35
+ """
36
+ if not is_dict(json_schema):
37
+ raise TypeError(f"Expected {json_schema} to be a dictionary; path={path}")
38
+
39
+ defs = json_schema.get("$defs")
40
+ if is_dict(defs):
41
+ for def_name, def_schema in defs.items():
42
+ _ensure_strict_json_schema(def_schema, path=(*path, "$defs", def_name), root=root)
43
+
44
+ definitions = json_schema.get("definitions")
45
+ if is_dict(definitions):
46
+ for definition_name, definition_schema in definitions.items():
47
+ _ensure_strict_json_schema(definition_schema, path=(*path, "definitions", definition_name), root=root)
48
+
49
+ typ = json_schema.get("type")
50
+ if typ == "object" and "additionalProperties" not in json_schema:
51
+ json_schema["additionalProperties"] = False
52
+
53
+ # object types
54
+ # { 'type': 'object', 'properties': { 'a': {...} } }
55
+ properties = json_schema.get("properties")
56
+ if is_dict(properties):
57
+ json_schema["required"] = [prop for prop in properties.keys()]
58
+ json_schema["properties"] = {
59
+ key: _ensure_strict_json_schema(prop_schema, path=(*path, "properties", key), root=root)
60
+ for key, prop_schema in properties.items()
61
+ }
62
+
63
+ # arrays
64
+ # { 'type': 'array', 'items': {...} }
65
+ items = json_schema.get("items")
66
+ if is_dict(items):
67
+ json_schema["items"] = _ensure_strict_json_schema(items, path=(*path, "items"), root=root)
68
+
69
+ # unions
70
+ any_of = json_schema.get("anyOf")
71
+ if is_list(any_of):
72
+ json_schema["anyOf"] = [
73
+ _ensure_strict_json_schema(variant, path=(*path, "anyOf", str(i)), root=root)
74
+ for i, variant in enumerate(any_of)
75
+ ]
76
+
77
+ # intersections
78
+ all_of = json_schema.get("allOf")
79
+ if is_list(all_of):
80
+ if len(all_of) == 1:
81
+ json_schema.update(_ensure_strict_json_schema(all_of[0], path=(*path, "allOf", "0"), root=root))
82
+ json_schema.pop("allOf")
83
+ else:
84
+ json_schema["allOf"] = [
85
+ _ensure_strict_json_schema(entry, path=(*path, "allOf", str(i)), root=root)
86
+ for i, entry in enumerate(all_of)
87
+ ]
88
+
89
+ # strip `None` defaults as there's no meaningful distinction here
90
+ # the schema will still be `nullable` and the model will default
91
+ # to using `None` anyway
92
+ if json_schema.get("default", NOT_GIVEN) is None:
93
+ json_schema.pop("default")
94
+
95
+ # we can't use `$ref`s if there are also other properties defined, e.g.
96
+ # `{"$ref": "...", "description": "my description"}`
97
+ #
98
+ # so we unravel the ref
99
+ # `{"type": "string", "description": "my description"}`
100
+ ref = json_schema.get("$ref")
101
+ if ref and has_more_than_n_keys(json_schema, 1):
102
+ assert isinstance(ref, str), f"Received non-string $ref - {ref}"
103
+
104
+ resolved = resolve_ref(root=root, ref=ref)
105
+ if not is_dict(resolved):
106
+ raise ValueError(f"Expected `$ref: {ref}` to resolved to a dictionary but got {resolved}")
107
+
108
+ # properties from the json schema take priority over the ones on the `$ref`
109
+ json_schema.update({**resolved, **json_schema})
110
+ json_schema.pop("$ref")
111
+ # Since the schema expanded from `$ref` might not have `additionalProperties: false` applied,
112
+ # we call `_ensure_strict_json_schema` again to fix the inlined schema and ensure it's valid.
113
+ return _ensure_strict_json_schema(json_schema, path=path, root=root)
114
+
115
+ return json_schema
116
+
117
+
118
+ def resolve_ref(*, root: dict[str, object], ref: str) -> object:
119
+ if not ref.startswith("#/"):
120
+ raise ValueError(f"Unexpected $ref format {ref!r}; Does not start with #/")
121
+
122
+ path = ref[2:].split("/")
123
+ resolved = root
124
+ for key in path:
125
+ value = resolved[key]
126
+ assert is_dict(value), f"encountered non-dictionary entry while resolving {ref} - {resolved}"
127
+ resolved = value
128
+
129
+ return resolved
130
+
131
+
132
+ def is_basemodel_type(typ: type) -> TypeGuard[type[pydantic.BaseModel]]:
133
+ if not inspect.isclass(typ):
134
+ return False
135
+ return issubclass(typ, pydantic.BaseModel)
136
+
137
+
138
+ def is_dataclass_like_type(typ: type) -> bool:
139
+ """Returns True if the given type likely used `@pydantic.dataclass`"""
140
+ return hasattr(typ, "__pydantic_config__")
141
+
142
+
143
+ def is_dict(obj: object) -> TypeGuard[dict[str, object]]:
144
+ # just pretend that we know there are only `str` keys
145
+ # as that check is not worth the performance cost
146
+ return _is_dict(obj)
147
+
148
+
149
+ def has_more_than_n_keys(obj: dict[str, object], n: int) -> bool:
150
+ i = 0
151
+ for _ in obj.keys():
152
+ i += 1
153
+ if i > n:
154
+ return True
155
+ return False
python_embeded/Lib/site-packages/openai/lib/_tools.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, Dict, cast
4
+
5
+ import pydantic
6
+
7
+ from ._pydantic import to_strict_json_schema
8
+ from ..types.chat import ChatCompletionToolParam
9
+ from ..types.shared_params import FunctionDefinition
10
+ from ..types.responses.function_tool_param import FunctionToolParam as ResponsesFunctionToolParam
11
+
12
+
13
+ class PydanticFunctionTool(Dict[str, Any]):
14
+ """Dictionary wrapper so we can pass the given base model
15
+ throughout the entire request stack without having to special
16
+ case it.
17
+ """
18
+
19
+ model: type[pydantic.BaseModel]
20
+
21
+ def __init__(self, defn: FunctionDefinition, model: type[pydantic.BaseModel]) -> None:
22
+ super().__init__(defn)
23
+ self.model = model
24
+
25
+ def cast(self) -> FunctionDefinition:
26
+ return cast(FunctionDefinition, self)
27
+
28
+
29
+ class ResponsesPydanticFunctionTool(Dict[str, Any]):
30
+ model: type[pydantic.BaseModel]
31
+
32
+ def __init__(self, tool: ResponsesFunctionToolParam, model: type[pydantic.BaseModel]) -> None:
33
+ super().__init__(tool)
34
+ self.model = model
35
+
36
+ def cast(self) -> ResponsesFunctionToolParam:
37
+ return cast(ResponsesFunctionToolParam, self)
38
+
39
+
40
+ def pydantic_function_tool(
41
+ model: type[pydantic.BaseModel],
42
+ *,
43
+ name: str | None = None, # inferred from class name by default
44
+ description: str | None = None, # inferred from class docstring by default
45
+ ) -> ChatCompletionToolParam:
46
+ if description is None:
47
+ # note: we intentionally don't use `.getdoc()` to avoid
48
+ # including pydantic's docstrings
49
+ description = model.__doc__
50
+
51
+ function = PydanticFunctionTool(
52
+ {
53
+ "name": name or model.__name__,
54
+ "strict": True,
55
+ "parameters": to_strict_json_schema(model),
56
+ },
57
+ model,
58
+ ).cast()
59
+
60
+ if description is not None:
61
+ function["description"] = description
62
+
63
+ return {
64
+ "type": "function",
65
+ "function": function,
66
+ }
python_embeded/Lib/site-packages/openai/lib/_validators.py ADDED
@@ -0,0 +1,809 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # pyright: basic
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import sys
6
+ from typing import Any, TypeVar, Callable, Optional, NamedTuple
7
+ from typing_extensions import TypeAlias
8
+
9
+ from .._extras import pandas as pd
10
+
11
+
12
+ class Remediation(NamedTuple):
13
+ name: str
14
+ immediate_msg: Optional[str] = None
15
+ necessary_msg: Optional[str] = None
16
+ necessary_fn: Optional[Callable[[Any], Any]] = None
17
+ optional_msg: Optional[str] = None
18
+ optional_fn: Optional[Callable[[Any], Any]] = None
19
+ error_msg: Optional[str] = None
20
+
21
+
22
+ OptionalDataFrameT = TypeVar("OptionalDataFrameT", bound="Optional[pd.DataFrame]")
23
+
24
+
25
+ def num_examples_validator(df: pd.DataFrame) -> Remediation:
26
+ """
27
+ This validator will only print out the number of examples and recommend to the user to increase the number of examples if less than 100.
28
+ """
29
+ MIN_EXAMPLES = 100
30
+ optional_suggestion = (
31
+ ""
32
+ if len(df) >= MIN_EXAMPLES
33
+ else ". In general, we recommend having at least a few hundred examples. We've found that performance tends to linearly increase for every doubling of the number of examples"
34
+ )
35
+ immediate_msg = f"\n- Your file contains {len(df)} prompt-completion pairs{optional_suggestion}"
36
+ return Remediation(name="num_examples", immediate_msg=immediate_msg)
37
+
38
+
39
+ def necessary_column_validator(df: pd.DataFrame, necessary_column: str) -> Remediation:
40
+ """
41
+ This validator will ensure that the necessary column is present in the dataframe.
42
+ """
43
+
44
+ def lower_case_column(df: pd.DataFrame, column: Any) -> pd.DataFrame:
45
+ cols = [c for c in df.columns if str(c).lower() == column]
46
+ df.rename(columns={cols[0]: column.lower()}, inplace=True)
47
+ return df
48
+
49
+ immediate_msg = None
50
+ necessary_fn = None
51
+ necessary_msg = None
52
+ error_msg = None
53
+
54
+ if necessary_column not in df.columns:
55
+ if necessary_column in [str(c).lower() for c in df.columns]:
56
+
57
+ def lower_case_column_creator(df: pd.DataFrame) -> pd.DataFrame:
58
+ return lower_case_column(df, necessary_column)
59
+
60
+ necessary_fn = lower_case_column_creator
61
+ immediate_msg = f"\n- The `{necessary_column}` column/key should be lowercase"
62
+ necessary_msg = f"Lower case column name to `{necessary_column}`"
63
+ else:
64
+ error_msg = f"`{necessary_column}` column/key is missing. Please make sure you name your columns/keys appropriately, then retry"
65
+
66
+ return Remediation(
67
+ name="necessary_column",
68
+ immediate_msg=immediate_msg,
69
+ necessary_msg=necessary_msg,
70
+ necessary_fn=necessary_fn,
71
+ error_msg=error_msg,
72
+ )
73
+
74
+
75
+ def additional_column_validator(df: pd.DataFrame, fields: list[str] = ["prompt", "completion"]) -> Remediation:
76
+ """
77
+ This validator will remove additional columns from the dataframe.
78
+ """
79
+ additional_columns = []
80
+ necessary_msg = None
81
+ immediate_msg = None
82
+ necessary_fn = None # type: ignore
83
+
84
+ if len(df.columns) > 2:
85
+ additional_columns = [c for c in df.columns if c not in fields]
86
+ warn_message = ""
87
+ for ac in additional_columns:
88
+ dups = [c for c in additional_columns if ac in c]
89
+ if len(dups) > 0:
90
+ warn_message += f"\n WARNING: Some of the additional columns/keys contain `{ac}` in their name. These will be ignored, and the column/key `{ac}` will be used instead. This could also result from a duplicate column/key in the provided file."
91
+ immediate_msg = f"\n- The input file should contain exactly two columns/keys per row. Additional columns/keys present are: {additional_columns}{warn_message}"
92
+ necessary_msg = f"Remove additional columns/keys: {additional_columns}"
93
+
94
+ def necessary_fn(x: Any) -> Any:
95
+ return x[fields]
96
+
97
+ return Remediation(
98
+ name="additional_column",
99
+ immediate_msg=immediate_msg,
100
+ necessary_msg=necessary_msg,
101
+ necessary_fn=necessary_fn,
102
+ )
103
+
104
+
105
+ def non_empty_field_validator(df: pd.DataFrame, field: str = "completion") -> Remediation:
106
+ """
107
+ This validator will ensure that no completion is empty.
108
+ """
109
+ necessary_msg = None
110
+ necessary_fn = None # type: ignore
111
+ immediate_msg = None
112
+
113
+ if df[field].apply(lambda x: x == "").any() or df[field].isnull().any():
114
+ empty_rows = (df[field] == "") | (df[field].isnull())
115
+ empty_indexes = df.reset_index().index[empty_rows].tolist()
116
+ immediate_msg = f"\n- `{field}` column/key should not contain empty strings. These are rows: {empty_indexes}"
117
+
118
+ def necessary_fn(x: Any) -> Any:
119
+ return x[x[field] != ""].dropna(subset=[field])
120
+
121
+ necessary_msg = f"Remove {len(empty_indexes)} rows with empty {field}s"
122
+
123
+ return Remediation(
124
+ name=f"empty_{field}",
125
+ immediate_msg=immediate_msg,
126
+ necessary_msg=necessary_msg,
127
+ necessary_fn=necessary_fn,
128
+ )
129
+
130
+
131
+ def duplicated_rows_validator(df: pd.DataFrame, fields: list[str] = ["prompt", "completion"]) -> Remediation:
132
+ """
133
+ This validator will suggest to the user to remove duplicate rows if they exist.
134
+ """
135
+ duplicated_rows = df.duplicated(subset=fields)
136
+ duplicated_indexes = df.reset_index().index[duplicated_rows].tolist()
137
+ immediate_msg = None
138
+ optional_msg = None
139
+ optional_fn = None # type: ignore
140
+
141
+ if len(duplicated_indexes) > 0:
142
+ immediate_msg = f"\n- There are {len(duplicated_indexes)} duplicated {'-'.join(fields)} sets. These are rows: {duplicated_indexes}"
143
+ optional_msg = f"Remove {len(duplicated_indexes)} duplicate rows"
144
+
145
+ def optional_fn(x: Any) -> Any:
146
+ return x.drop_duplicates(subset=fields)
147
+
148
+ return Remediation(
149
+ name="duplicated_rows",
150
+ immediate_msg=immediate_msg,
151
+ optional_msg=optional_msg,
152
+ optional_fn=optional_fn,
153
+ )
154
+
155
+
156
+ def long_examples_validator(df: pd.DataFrame) -> Remediation:
157
+ """
158
+ This validator will suggest to the user to remove examples that are too long.
159
+ """
160
+ immediate_msg = None
161
+ optional_msg = None
162
+ optional_fn = None # type: ignore
163
+
164
+ ft_type = infer_task_type(df)
165
+ if ft_type != "open-ended generation":
166
+
167
+ def get_long_indexes(d: pd.DataFrame) -> Any:
168
+ long_examples = d.apply(lambda x: len(x.prompt) + len(x.completion) > 10000, axis=1)
169
+ return d.reset_index().index[long_examples].tolist()
170
+
171
+ long_indexes = get_long_indexes(df)
172
+
173
+ if len(long_indexes) > 0:
174
+ immediate_msg = f"\n- There are {len(long_indexes)} examples that are very long. These are rows: {long_indexes}\nFor conditional generation, and for classification the examples shouldn't be longer than 2048 tokens."
175
+ optional_msg = f"Remove {len(long_indexes)} long examples"
176
+
177
+ def optional_fn(x: Any) -> Any:
178
+ long_indexes_to_drop = get_long_indexes(x)
179
+ if long_indexes != long_indexes_to_drop:
180
+ sys.stdout.write(
181
+ f"The indices of the long examples has changed as a result of a previously applied recommendation.\nThe {len(long_indexes_to_drop)} long examples to be dropped are now at the following indices: {long_indexes_to_drop}\n"
182
+ )
183
+ return x.drop(long_indexes_to_drop)
184
+
185
+ return Remediation(
186
+ name="long_examples",
187
+ immediate_msg=immediate_msg,
188
+ optional_msg=optional_msg,
189
+ optional_fn=optional_fn,
190
+ )
191
+
192
+
193
+ def common_prompt_suffix_validator(df: pd.DataFrame) -> Remediation:
194
+ """
195
+ This validator will suggest to add a common suffix to the prompt if one doesn't already exist in case of classification or conditional generation.
196
+ """
197
+ error_msg = None
198
+ immediate_msg = None
199
+ optional_msg = None
200
+ optional_fn = None # type: ignore
201
+
202
+ # Find a suffix which is not contained within the prompt otherwise
203
+ suggested_suffix = "\n\n### =>\n\n"
204
+ suffix_options = [
205
+ " ->",
206
+ "\n\n###\n\n",
207
+ "\n\n===\n\n",
208
+ "\n\n---\n\n",
209
+ "\n\n===>\n\n",
210
+ "\n\n--->\n\n",
211
+ ]
212
+ for suffix_option in suffix_options:
213
+ if suffix_option == " ->":
214
+ if df.prompt.str.contains("\n").any():
215
+ continue
216
+ if df.prompt.str.contains(suffix_option, regex=False).any():
217
+ continue
218
+ suggested_suffix = suffix_option
219
+ break
220
+ display_suggested_suffix = suggested_suffix.replace("\n", "\\n")
221
+
222
+ ft_type = infer_task_type(df)
223
+ if ft_type == "open-ended generation":
224
+ return Remediation(name="common_suffix")
225
+
226
+ def add_suffix(x: Any, suffix: Any) -> Any:
227
+ x["prompt"] += suffix
228
+ return x
229
+
230
+ common_suffix = get_common_xfix(df.prompt, xfix="suffix")
231
+ if (df.prompt == common_suffix).all():
232
+ error_msg = f"All prompts are identical: `{common_suffix}`\nConsider leaving the prompts blank if you want to do open-ended generation, otherwise ensure prompts are different"
233
+ return Remediation(name="common_suffix", error_msg=error_msg)
234
+
235
+ if common_suffix != "":
236
+ common_suffix_new_line_handled = common_suffix.replace("\n", "\\n")
237
+ immediate_msg = f"\n- All prompts end with suffix `{common_suffix_new_line_handled}`"
238
+ if len(common_suffix) > 10:
239
+ immediate_msg += f". This suffix seems very long. Consider replacing with a shorter suffix, such as `{display_suggested_suffix}`"
240
+ if df.prompt.str[: -len(common_suffix)].str.contains(common_suffix, regex=False).any():
241
+ immediate_msg += f"\n WARNING: Some of your prompts contain the suffix `{common_suffix}` more than once. We strongly suggest that you review your prompts and add a unique suffix"
242
+
243
+ else:
244
+ immediate_msg = "\n- Your data does not contain a common separator at the end of your prompts. Having a separator string appended to the end of the prompt makes it clearer to the fine-tuned model where the completion should begin. See https://platform.openai.com/docs/guides/fine-tuning/preparing-your-dataset for more detail and examples. If you intend to do open-ended generation, then you should leave the prompts empty"
245
+
246
+ if common_suffix == "":
247
+ optional_msg = f"Add a suffix separator `{display_suggested_suffix}` to all prompts"
248
+
249
+ def optional_fn(x: Any) -> Any:
250
+ return add_suffix(x, suggested_suffix)
251
+
252
+ return Remediation(
253
+ name="common_completion_suffix",
254
+ immediate_msg=immediate_msg,
255
+ optional_msg=optional_msg,
256
+ optional_fn=optional_fn,
257
+ error_msg=error_msg,
258
+ )
259
+
260
+
261
+ def common_prompt_prefix_validator(df: pd.DataFrame) -> Remediation:
262
+ """
263
+ This validator will suggest to remove a common prefix from the prompt if a long one exist.
264
+ """
265
+ MAX_PREFIX_LEN = 12
266
+
267
+ immediate_msg = None
268
+ optional_msg = None
269
+ optional_fn = None # type: ignore
270
+
271
+ common_prefix = get_common_xfix(df.prompt, xfix="prefix")
272
+ if common_prefix == "":
273
+ return Remediation(name="common_prefix")
274
+
275
+ def remove_common_prefix(x: Any, prefix: Any) -> Any:
276
+ x["prompt"] = x["prompt"].str[len(prefix) :]
277
+ return x
278
+
279
+ if (df.prompt == common_prefix).all():
280
+ # already handled by common_suffix_validator
281
+ return Remediation(name="common_prefix")
282
+
283
+ if common_prefix != "":
284
+ immediate_msg = f"\n- All prompts start with prefix `{common_prefix}`"
285
+ if MAX_PREFIX_LEN < len(common_prefix):
286
+ immediate_msg += ". Fine-tuning doesn't require the instruction specifying the task, or a few-shot example scenario. Most of the time you should only add the input data into the prompt, and the desired output into the completion"
287
+ optional_msg = f"Remove prefix `{common_prefix}` from all prompts"
288
+
289
+ def optional_fn(x: Any) -> Any:
290
+ return remove_common_prefix(x, common_prefix)
291
+
292
+ return Remediation(
293
+ name="common_prompt_prefix",
294
+ immediate_msg=immediate_msg,
295
+ optional_msg=optional_msg,
296
+ optional_fn=optional_fn,
297
+ )
298
+
299
+
300
+ def common_completion_prefix_validator(df: pd.DataFrame) -> Remediation:
301
+ """
302
+ This validator will suggest to remove a common prefix from the completion if a long one exist.
303
+ """
304
+ MAX_PREFIX_LEN = 5
305
+
306
+ common_prefix = get_common_xfix(df.completion, xfix="prefix")
307
+ ws_prefix = len(common_prefix) > 0 and common_prefix[0] == " "
308
+ if len(common_prefix) < MAX_PREFIX_LEN:
309
+ return Remediation(name="common_prefix")
310
+
311
+ def remove_common_prefix(x: Any, prefix: Any, ws_prefix: Any) -> Any:
312
+ x["completion"] = x["completion"].str[len(prefix) :]
313
+ if ws_prefix:
314
+ # keep the single whitespace as prefix
315
+ x["completion"] = f" {x['completion']}"
316
+ return x
317
+
318
+ if (df.completion == common_prefix).all():
319
+ # already handled by common_suffix_validator
320
+ return Remediation(name="common_prefix")
321
+
322
+ immediate_msg = f"\n- All completions start with prefix `{common_prefix}`. Most of the time you should only add the output data into the completion, without any prefix"
323
+ optional_msg = f"Remove prefix `{common_prefix}` from all completions"
324
+
325
+ def optional_fn(x: Any) -> Any:
326
+ return remove_common_prefix(x, common_prefix, ws_prefix)
327
+
328
+ return Remediation(
329
+ name="common_completion_prefix",
330
+ immediate_msg=immediate_msg,
331
+ optional_msg=optional_msg,
332
+ optional_fn=optional_fn,
333
+ )
334
+
335
+
336
+ def common_completion_suffix_validator(df: pd.DataFrame) -> Remediation:
337
+ """
338
+ This validator will suggest to add a common suffix to the completion if one doesn't already exist in case of classification or conditional generation.
339
+ """
340
+ error_msg = None
341
+ immediate_msg = None
342
+ optional_msg = None
343
+ optional_fn = None # type: ignore
344
+
345
+ ft_type = infer_task_type(df)
346
+ if ft_type == "open-ended generation" or ft_type == "classification":
347
+ return Remediation(name="common_suffix")
348
+
349
+ common_suffix = get_common_xfix(df.completion, xfix="suffix")
350
+ if (df.completion == common_suffix).all():
351
+ error_msg = f"All completions are identical: `{common_suffix}`\nEnsure completions are different, otherwise the model will just repeat `{common_suffix}`"
352
+ return Remediation(name="common_suffix", error_msg=error_msg)
353
+
354
+ # Find a suffix which is not contained within the completion otherwise
355
+ suggested_suffix = " [END]"
356
+ suffix_options = [
357
+ "\n",
358
+ ".",
359
+ " END",
360
+ "***",
361
+ "+++",
362
+ "&&&",
363
+ "$$$",
364
+ "@@@",
365
+ "%%%",
366
+ ]
367
+ for suffix_option in suffix_options:
368
+ if df.completion.str.contains(suffix_option, regex=False).any():
369
+ continue
370
+ suggested_suffix = suffix_option
371
+ break
372
+ display_suggested_suffix = suggested_suffix.replace("\n", "\\n")
373
+
374
+ def add_suffix(x: Any, suffix: Any) -> Any:
375
+ x["completion"] += suffix
376
+ return x
377
+
378
+ if common_suffix != "":
379
+ common_suffix_new_line_handled = common_suffix.replace("\n", "\\n")
380
+ immediate_msg = f"\n- All completions end with suffix `{common_suffix_new_line_handled}`"
381
+ if len(common_suffix) > 10:
382
+ immediate_msg += f". This suffix seems very long. Consider replacing with a shorter suffix, such as `{display_suggested_suffix}`"
383
+ if df.completion.str[: -len(common_suffix)].str.contains(common_suffix, regex=False).any():
384
+ immediate_msg += f"\n WARNING: Some of your completions contain the suffix `{common_suffix}` more than once. We suggest that you review your completions and add a unique ending"
385
+
386
+ else:
387
+ immediate_msg = "\n- Your data does not contain a common ending at the end of your completions. Having a common ending string appended to the end of the completion makes it clearer to the fine-tuned model where the completion should end. See https://platform.openai.com/docs/guides/fine-tuning/preparing-your-dataset for more detail and examples."
388
+
389
+ if common_suffix == "":
390
+ optional_msg = f"Add a suffix ending `{display_suggested_suffix}` to all completions"
391
+
392
+ def optional_fn(x: Any) -> Any:
393
+ return add_suffix(x, suggested_suffix)
394
+
395
+ return Remediation(
396
+ name="common_completion_suffix",
397
+ immediate_msg=immediate_msg,
398
+ optional_msg=optional_msg,
399
+ optional_fn=optional_fn,
400
+ error_msg=error_msg,
401
+ )
402
+
403
+
404
+ def completions_space_start_validator(df: pd.DataFrame) -> Remediation:
405
+ """
406
+ This validator will suggest to add a space at the start of the completion if it doesn't already exist. This helps with tokenization.
407
+ """
408
+
409
+ def add_space_start(x: Any) -> Any:
410
+ x["completion"] = x["completion"].apply(lambda s: ("" if s.startswith(" ") else " ") + s)
411
+ return x
412
+
413
+ optional_msg = None
414
+ optional_fn = None
415
+ immediate_msg = None
416
+
417
+ if df.completion.str[:1].nunique() != 1 or df.completion.values[0][0] != " ":
418
+ immediate_msg = "\n- The completion should start with a whitespace character (` `). This tends to produce better results due to the tokenization we use. See https://platform.openai.com/docs/guides/fine-tuning/preparing-your-dataset for more details"
419
+ optional_msg = "Add a whitespace character to the beginning of the completion"
420
+ optional_fn = add_space_start
421
+ return Remediation(
422
+ name="completion_space_start",
423
+ immediate_msg=immediate_msg,
424
+ optional_msg=optional_msg,
425
+ optional_fn=optional_fn,
426
+ )
427
+
428
+
429
+ def lower_case_validator(df: pd.DataFrame, column: Any) -> Remediation | None:
430
+ """
431
+ This validator will suggest to lowercase the column values, if more than a third of letters are uppercase.
432
+ """
433
+
434
+ def lower_case(x: Any) -> Any:
435
+ x[column] = x[column].str.lower()
436
+ return x
437
+
438
+ count_upper = df[column].apply(lambda x: sum(1 for c in x if c.isalpha() and c.isupper())).sum()
439
+ count_lower = df[column].apply(lambda x: sum(1 for c in x if c.isalpha() and c.islower())).sum()
440
+
441
+ if count_upper * 2 > count_lower:
442
+ return Remediation(
443
+ name="lower_case",
444
+ immediate_msg=f"\n- More than a third of your `{column}` column/key is uppercase. Uppercase {column}s tends to perform worse than a mixture of case encountered in normal language. We recommend to lower case the data if that makes sense in your domain. See https://platform.openai.com/docs/guides/fine-tuning/preparing-your-dataset for more details",
445
+ optional_msg=f"Lowercase all your data in column/key `{column}`",
446
+ optional_fn=lower_case,
447
+ )
448
+ return None
449
+
450
+
451
+ def read_any_format(
452
+ fname: str, fields: list[str] = ["prompt", "completion"]
453
+ ) -> tuple[pd.DataFrame | None, Remediation]:
454
+ """
455
+ This function will read a file saved in .csv, .json, .txt, .xlsx or .tsv format using pandas.
456
+ - for .xlsx it will read the first sheet
457
+ - for .txt it will assume completions and split on newline
458
+ """
459
+ remediation = None
460
+ necessary_msg = None
461
+ immediate_msg = None
462
+ error_msg = None
463
+ df = None
464
+
465
+ if os.path.isfile(fname):
466
+ try:
467
+ if fname.lower().endswith(".csv") or fname.lower().endswith(".tsv"):
468
+ file_extension_str, separator = ("CSV", ",") if fname.lower().endswith(".csv") else ("TSV", "\t")
469
+ immediate_msg = (
470
+ f"\n- Based on your file extension, your file is formatted as a {file_extension_str} file"
471
+ )
472
+ necessary_msg = f"Your format `{file_extension_str}` will be converted to `JSONL`"
473
+ df = pd.read_csv(fname, sep=separator, dtype=str).fillna("")
474
+ elif fname.lower().endswith(".xlsx"):
475
+ immediate_msg = "\n- Based on your file extension, your file is formatted as an Excel file"
476
+ necessary_msg = "Your format `XLSX` will be converted to `JSONL`"
477
+ xls = pd.ExcelFile(fname)
478
+ sheets = xls.sheet_names
479
+ if len(sheets) > 1:
480
+ immediate_msg += "\n- Your Excel file contains more than one sheet. Please either save as csv or ensure all data is present in the first sheet. WARNING: Reading only the first sheet..."
481
+ df = pd.read_excel(fname, dtype=str).fillna("")
482
+ elif fname.lower().endswith(".txt"):
483
+ immediate_msg = "\n- Based on your file extension, you provided a text file"
484
+ necessary_msg = "Your format `TXT` will be converted to `JSONL`"
485
+ with open(fname, "r") as f:
486
+ content = f.read()
487
+ df = pd.DataFrame(
488
+ [["", line] for line in content.split("\n")],
489
+ columns=fields,
490
+ dtype=str,
491
+ ).fillna("")
492
+ elif fname.lower().endswith(".jsonl"):
493
+ df = pd.read_json(fname, lines=True, dtype=str).fillna("") # type: ignore
494
+ if len(df) == 1: # type: ignore
495
+ # this is NOT what we expect for a .jsonl file
496
+ immediate_msg = "\n- Your JSONL file appears to be in a JSON format. Your file will be converted to JSONL format"
497
+ necessary_msg = "Your format `JSON` will be converted to `JSONL`"
498
+ df = pd.read_json(fname, dtype=str).fillna("") # type: ignore
499
+ else:
500
+ pass # this is what we expect for a .jsonl file
501
+ elif fname.lower().endswith(".json"):
502
+ try:
503
+ # to handle case where .json file is actually a .jsonl file
504
+ df = pd.read_json(fname, lines=True, dtype=str).fillna("") # type: ignore
505
+ if len(df) == 1: # type: ignore
506
+ # this code path corresponds to a .json file that has one line
507
+ df = pd.read_json(fname, dtype=str).fillna("") # type: ignore
508
+ else:
509
+ # this is NOT what we expect for a .json file
510
+ immediate_msg = "\n- Your JSON file appears to be in a JSONL format. Your file will be converted to JSONL format"
511
+ necessary_msg = "Your format `JSON` will be converted to `JSONL`"
512
+ except ValueError:
513
+ # this code path corresponds to a .json file that has multiple lines (i.e. it is indented)
514
+ df = pd.read_json(fname, dtype=str).fillna("") # type: ignore
515
+ else:
516
+ error_msg = (
517
+ "Your file must have one of the following extensions: .CSV, .TSV, .XLSX, .TXT, .JSON or .JSONL"
518
+ )
519
+ if "." in fname:
520
+ error_msg += f" Your file `{fname}` ends with the extension `.{fname.split('.')[-1]}` which is not supported."
521
+ else:
522
+ error_msg += f" Your file `{fname}` is missing a file extension."
523
+
524
+ except (ValueError, TypeError):
525
+ file_extension_str = fname.split(".")[-1].upper()
526
+ error_msg = f"Your file `{fname}` does not appear to be in valid {file_extension_str} format. Please ensure your file is formatted as a valid {file_extension_str} file."
527
+
528
+ else:
529
+ error_msg = f"File {fname} does not exist."
530
+
531
+ remediation = Remediation(
532
+ name="read_any_format",
533
+ necessary_msg=necessary_msg,
534
+ immediate_msg=immediate_msg,
535
+ error_msg=error_msg,
536
+ )
537
+ return df, remediation
538
+
539
+
540
+ def format_inferrer_validator(df: pd.DataFrame) -> Remediation:
541
+ """
542
+ This validator will infer the likely fine-tuning format of the data, and display it to the user if it is classification.
543
+ It will also suggest to use ada and explain train/validation split benefits.
544
+ """
545
+ ft_type = infer_task_type(df)
546
+ immediate_msg = None
547
+ if ft_type == "classification":
548
+ immediate_msg = f"\n- Based on your data it seems like you're trying to fine-tune a model for {ft_type}\n- For classification, we recommend you try one of the faster and cheaper models, such as `ada`\n- For classification, you can estimate the expected model performance by keeping a held out dataset, which is not used for training"
549
+ return Remediation(name="num_examples", immediate_msg=immediate_msg)
550
+
551
+
552
+ def apply_necessary_remediation(df: OptionalDataFrameT, remediation: Remediation) -> OptionalDataFrameT:
553
+ """
554
+ This function will apply a necessary remediation to a dataframe, or print an error message if one exists.
555
+ """
556
+ if remediation.error_msg is not None:
557
+ sys.stderr.write(f"\n\nERROR in {remediation.name} validator: {remediation.error_msg}\n\nAborting...")
558
+ sys.exit(1)
559
+ if remediation.immediate_msg is not None:
560
+ sys.stdout.write(remediation.immediate_msg)
561
+ if remediation.necessary_fn is not None:
562
+ df = remediation.necessary_fn(df)
563
+ return df
564
+
565
+
566
+ def accept_suggestion(input_text: str, auto_accept: bool) -> bool:
567
+ sys.stdout.write(input_text)
568
+ if auto_accept:
569
+ sys.stdout.write("Y\n")
570
+ return True
571
+ return input().lower() != "n"
572
+
573
+
574
+ def apply_optional_remediation(
575
+ df: pd.DataFrame, remediation: Remediation, auto_accept: bool
576
+ ) -> tuple[pd.DataFrame, bool]:
577
+ """
578
+ This function will apply an optional remediation to a dataframe, based on the user input.
579
+ """
580
+ optional_applied = False
581
+ input_text = f"- [Recommended] {remediation.optional_msg} [Y/n]: "
582
+ if remediation.optional_msg is not None:
583
+ if accept_suggestion(input_text, auto_accept):
584
+ assert remediation.optional_fn is not None
585
+ df = remediation.optional_fn(df)
586
+ optional_applied = True
587
+ if remediation.necessary_msg is not None:
588
+ sys.stdout.write(f"- [Necessary] {remediation.necessary_msg}\n")
589
+ return df, optional_applied
590
+
591
+
592
+ def estimate_fine_tuning_time(df: pd.DataFrame) -> None:
593
+ """
594
+ Estimate the time it'll take to fine-tune the dataset
595
+ """
596
+ ft_format = infer_task_type(df)
597
+ expected_time = 1.0
598
+ if ft_format == "classification":
599
+ num_examples = len(df)
600
+ expected_time = num_examples * 1.44
601
+ else:
602
+ size = df.memory_usage(index=True).sum()
603
+ expected_time = size * 0.0515
604
+
605
+ def format_time(time: float) -> str:
606
+ if time < 60:
607
+ return f"{round(time, 2)} seconds"
608
+ elif time < 3600:
609
+ return f"{round(time / 60, 2)} minutes"
610
+ elif time < 86400:
611
+ return f"{round(time / 3600, 2)} hours"
612
+ else:
613
+ return f"{round(time / 86400, 2)} days"
614
+
615
+ time_string = format_time(expected_time + 140)
616
+ sys.stdout.write(
617
+ f"Once your model starts training, it'll approximately take {time_string} to train a `curie` model, and less for `ada` and `babbage`. Queue will approximately take half an hour per job ahead of you.\n"
618
+ )
619
+
620
+
621
+ def get_outfnames(fname: str, split: bool) -> list[str]:
622
+ suffixes = ["_train", "_valid"] if split else [""]
623
+ i = 0
624
+ while True:
625
+ index_suffix = f" ({i})" if i > 0 else ""
626
+ candidate_fnames = [f"{os.path.splitext(fname)[0]}_prepared{suffix}{index_suffix}.jsonl" for suffix in suffixes]
627
+ if not any(os.path.isfile(f) for f in candidate_fnames):
628
+ return candidate_fnames
629
+ i += 1
630
+
631
+
632
+ def get_classification_hyperparams(df: pd.DataFrame) -> tuple[int, object]:
633
+ n_classes = df.completion.nunique()
634
+ pos_class = None
635
+ if n_classes == 2:
636
+ pos_class = df.completion.value_counts().index[0]
637
+ return n_classes, pos_class
638
+
639
+
640
+ def write_out_file(df: pd.DataFrame, fname: str, any_remediations: bool, auto_accept: bool) -> None:
641
+ """
642
+ This function will write out a dataframe to a file, if the user would like to proceed, and also offer a fine-tuning command with the newly created file.
643
+ For classification it will optionally ask the user if they would like to split the data into train/valid files, and modify the suggested command to include the valid set.
644
+ """
645
+ ft_format = infer_task_type(df)
646
+ common_prompt_suffix = get_common_xfix(df.prompt, xfix="suffix")
647
+ common_completion_suffix = get_common_xfix(df.completion, xfix="suffix")
648
+
649
+ split = False
650
+ input_text = "- [Recommended] Would you like to split into training and validation set? [Y/n]: "
651
+ if ft_format == "classification":
652
+ if accept_suggestion(input_text, auto_accept):
653
+ split = True
654
+
655
+ additional_params = ""
656
+ common_prompt_suffix_new_line_handled = common_prompt_suffix.replace("\n", "\\n")
657
+ common_completion_suffix_new_line_handled = common_completion_suffix.replace("\n", "\\n")
658
+ optional_ending_string = (
659
+ f' Make sure to include `stop=["{common_completion_suffix_new_line_handled}"]` so that the generated texts ends at the expected place.'
660
+ if len(common_completion_suffix_new_line_handled) > 0
661
+ else ""
662
+ )
663
+
664
+ input_text = "\n\nYour data will be written to a new JSONL file. Proceed [Y/n]: "
665
+
666
+ if not any_remediations and not split:
667
+ sys.stdout.write(
668
+ f'\nYou can use your file for fine-tuning:\n> openai api fine_tunes.create -t "{fname}"{additional_params}\n\nAfter you’ve fine-tuned a model, remember that your prompt has to end with the indicator string `{common_prompt_suffix_new_line_handled}` for the model to start generating completions, rather than continuing with the prompt.{optional_ending_string}\n'
669
+ )
670
+ estimate_fine_tuning_time(df)
671
+
672
+ elif accept_suggestion(input_text, auto_accept):
673
+ fnames = get_outfnames(fname, split)
674
+ if split:
675
+ assert len(fnames) == 2 and "train" in fnames[0] and "valid" in fnames[1]
676
+ MAX_VALID_EXAMPLES = 1000
677
+ n_train = max(len(df) - MAX_VALID_EXAMPLES, int(len(df) * 0.8))
678
+ df_train = df.sample(n=n_train, random_state=42)
679
+ df_valid = df.drop(df_train.index)
680
+ df_train[["prompt", "completion"]].to_json( # type: ignore
681
+ fnames[0], lines=True, orient="records", force_ascii=False, indent=None
682
+ )
683
+ df_valid[["prompt", "completion"]].to_json(
684
+ fnames[1], lines=True, orient="records", force_ascii=False, indent=None
685
+ )
686
+
687
+ n_classes, pos_class = get_classification_hyperparams(df)
688
+ additional_params += " --compute_classification_metrics"
689
+ if n_classes == 2:
690
+ additional_params += f' --classification_positive_class "{pos_class}"'
691
+ else:
692
+ additional_params += f" --classification_n_classes {n_classes}"
693
+ else:
694
+ assert len(fnames) == 1
695
+ df[["prompt", "completion"]].to_json(
696
+ fnames[0], lines=True, orient="records", force_ascii=False, indent=None
697
+ )
698
+
699
+ # Add -v VALID_FILE if we split the file into train / valid
700
+ files_string = ("s" if split else "") + " to `" + ("` and `".join(fnames))
701
+ valid_string = f' -v "{fnames[1]}"' if split else ""
702
+ separator_reminder = (
703
+ ""
704
+ if len(common_prompt_suffix_new_line_handled) == 0
705
+ else f"After you’ve fine-tuned a model, remember that your prompt has to end with the indicator string `{common_prompt_suffix_new_line_handled}` for the model to start generating completions, rather than continuing with the prompt."
706
+ )
707
+ sys.stdout.write(
708
+ f'\nWrote modified file{files_string}`\nFeel free to take a look!\n\nNow use that file when fine-tuning:\n> openai api fine_tunes.create -t "{fnames[0]}"{valid_string}{additional_params}\n\n{separator_reminder}{optional_ending_string}\n'
709
+ )
710
+ estimate_fine_tuning_time(df)
711
+ else:
712
+ sys.stdout.write("Aborting... did not write the file\n")
713
+
714
+
715
+ def infer_task_type(df: pd.DataFrame) -> str:
716
+ """
717
+ Infer the likely fine-tuning task type from the data
718
+ """
719
+ CLASSIFICATION_THRESHOLD = 3 # min_average instances of each class
720
+ if sum(df.prompt.str.len()) == 0:
721
+ return "open-ended generation"
722
+
723
+ if len(df.completion.unique()) < len(df) / CLASSIFICATION_THRESHOLD:
724
+ return "classification"
725
+
726
+ return "conditional generation"
727
+
728
+
729
+ def get_common_xfix(series: Any, xfix: str = "suffix") -> str:
730
+ """
731
+ Finds the longest common suffix or prefix of all the values in a series
732
+ """
733
+ common_xfix = ""
734
+ while True:
735
+ common_xfixes = (
736
+ series.str[-(len(common_xfix) + 1) :] if xfix == "suffix" else series.str[: len(common_xfix) + 1]
737
+ ) # first few or last few characters
738
+ if common_xfixes.nunique() != 1: # we found the character at which we don't have a unique xfix anymore
739
+ break
740
+ elif common_xfix == common_xfixes.values[0]: # the entire first row is a prefix of every other row
741
+ break
742
+ else: # the first or last few characters are still common across all rows - let's try to add one more
743
+ common_xfix = common_xfixes.values[0]
744
+ return common_xfix
745
+
746
+
747
+ Validator: TypeAlias = "Callable[[pd.DataFrame], Remediation | None]"
748
+
749
+
750
+ def get_validators() -> list[Validator]:
751
+ return [
752
+ num_examples_validator,
753
+ lambda x: necessary_column_validator(x, "prompt"),
754
+ lambda x: necessary_column_validator(x, "completion"),
755
+ additional_column_validator,
756
+ non_empty_field_validator,
757
+ format_inferrer_validator,
758
+ duplicated_rows_validator,
759
+ long_examples_validator,
760
+ lambda x: lower_case_validator(x, "prompt"),
761
+ lambda x: lower_case_validator(x, "completion"),
762
+ common_prompt_suffix_validator,
763
+ common_prompt_prefix_validator,
764
+ common_completion_prefix_validator,
765
+ common_completion_suffix_validator,
766
+ completions_space_start_validator,
767
+ ]
768
+
769
+
770
+ def apply_validators(
771
+ df: pd.DataFrame,
772
+ fname: str,
773
+ remediation: Remediation | None,
774
+ validators: list[Validator],
775
+ auto_accept: bool,
776
+ write_out_file_func: Callable[..., Any],
777
+ ) -> None:
778
+ optional_remediations: list[Remediation] = []
779
+ if remediation is not None:
780
+ optional_remediations.append(remediation)
781
+ for validator in validators:
782
+ remediation = validator(df)
783
+ if remediation is not None:
784
+ optional_remediations.append(remediation)
785
+ df = apply_necessary_remediation(df, remediation)
786
+
787
+ any_optional_or_necessary_remediations = any(
788
+ [
789
+ remediation
790
+ for remediation in optional_remediations
791
+ if remediation.optional_msg is not None or remediation.necessary_msg is not None
792
+ ]
793
+ )
794
+ any_necessary_applied = any(
795
+ [remediation for remediation in optional_remediations if remediation.necessary_msg is not None]
796
+ )
797
+ any_optional_applied = False
798
+
799
+ if any_optional_or_necessary_remediations:
800
+ sys.stdout.write("\n\nBased on the analysis we will perform the following actions:\n")
801
+ for remediation in optional_remediations:
802
+ df, optional_applied = apply_optional_remediation(df, remediation, auto_accept)
803
+ any_optional_applied = any_optional_applied or optional_applied
804
+ else:
805
+ sys.stdout.write("\n\nNo remediations found.\n")
806
+
807
+ any_optional_or_necessary_applied = any_optional_applied or any_necessary_applied
808
+
809
+ write_out_file_func(df, fname, any_optional_or_necessary_applied, auto_accept)
python_embeded/Lib/site-packages/openai/lib/azure.py ADDED
@@ -0,0 +1,647 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import inspect
5
+ from typing import Any, Union, Mapping, TypeVar, Callable, Awaitable, cast, overload
6
+ from typing_extensions import Self, override
7
+
8
+ import httpx
9
+
10
+ from .._types import NOT_GIVEN, Omit, Query, Timeout, NotGiven
11
+ from .._utils import is_given, is_mapping
12
+ from .._client import OpenAI, AsyncOpenAI
13
+ from .._compat import model_copy
14
+ from .._models import FinalRequestOptions
15
+ from .._streaming import Stream, AsyncStream
16
+ from .._exceptions import OpenAIError
17
+ from .._base_client import DEFAULT_MAX_RETRIES, BaseClient
18
+
19
+ _deployments_endpoints = set(
20
+ [
21
+ "/completions",
22
+ "/chat/completions",
23
+ "/embeddings",
24
+ "/audio/transcriptions",
25
+ "/audio/translations",
26
+ "/audio/speech",
27
+ "/images/generations",
28
+ "/images/edits",
29
+ ]
30
+ )
31
+
32
+
33
+ AzureADTokenProvider = Callable[[], str]
34
+ AsyncAzureADTokenProvider = Callable[[], "str | Awaitable[str]"]
35
+ _HttpxClientT = TypeVar("_HttpxClientT", bound=Union[httpx.Client, httpx.AsyncClient])
36
+ _DefaultStreamT = TypeVar("_DefaultStreamT", bound=Union[Stream[Any], AsyncStream[Any]])
37
+
38
+
39
+ # we need to use a sentinel API key value for Azure AD
40
+ # as we don't want to make the `api_key` in the main client Optional
41
+ # and Azure AD tokens may be retrieved on a per-request basis
42
+ API_KEY_SENTINEL = "".join(["<", "missing API key", ">"])
43
+
44
+
45
+ class MutuallyExclusiveAuthError(OpenAIError):
46
+ def __init__(self) -> None:
47
+ super().__init__(
48
+ "The `api_key`, `azure_ad_token` and `azure_ad_token_provider` arguments are mutually exclusive; Only one can be passed at a time"
49
+ )
50
+
51
+
52
+ class BaseAzureClient(BaseClient[_HttpxClientT, _DefaultStreamT]):
53
+ _azure_endpoint: httpx.URL | None
54
+ _azure_deployment: str | None
55
+
56
+ @override
57
+ def _build_request(
58
+ self,
59
+ options: FinalRequestOptions,
60
+ *,
61
+ retries_taken: int = 0,
62
+ ) -> httpx.Request:
63
+ if options.url in _deployments_endpoints and is_mapping(options.json_data):
64
+ model = options.json_data.get("model")
65
+ if model is not None and "/deployments" not in str(self.base_url.path):
66
+ options.url = f"/deployments/{model}{options.url}"
67
+
68
+ return super()._build_request(options, retries_taken=retries_taken)
69
+
70
+ @override
71
+ def _prepare_url(self, url: str) -> httpx.URL:
72
+ """Adjust the URL if the client was configured with an Azure endpoint + deployment
73
+ and the API feature being called is **not** a deployments-based endpoint
74
+ (i.e. requires /deployments/deployment-name in the URL path).
75
+ """
76
+ if self._azure_deployment and self._azure_endpoint and url not in _deployments_endpoints:
77
+ merge_url = httpx.URL(url)
78
+ if merge_url.is_relative_url:
79
+ merge_raw_path = (
80
+ self._azure_endpoint.raw_path.rstrip(b"/") + b"/openai/" + merge_url.raw_path.lstrip(b"/")
81
+ )
82
+ return self._azure_endpoint.copy_with(raw_path=merge_raw_path)
83
+
84
+ return merge_url
85
+
86
+ return super()._prepare_url(url)
87
+
88
+
89
+ class AzureOpenAI(BaseAzureClient[httpx.Client, Stream[Any]], OpenAI):
90
+ @overload
91
+ def __init__(
92
+ self,
93
+ *,
94
+ azure_endpoint: str,
95
+ azure_deployment: str | None = None,
96
+ api_version: str | None = None,
97
+ api_key: str | None = None,
98
+ azure_ad_token: str | None = None,
99
+ azure_ad_token_provider: AzureADTokenProvider | None = None,
100
+ organization: str | None = None,
101
+ webhook_secret: str | None = None,
102
+ websocket_base_url: str | httpx.URL | None = None,
103
+ timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
104
+ max_retries: int = DEFAULT_MAX_RETRIES,
105
+ default_headers: Mapping[str, str] | None = None,
106
+ default_query: Mapping[str, object] | None = None,
107
+ http_client: httpx.Client | None = None,
108
+ _strict_response_validation: bool = False,
109
+ ) -> None: ...
110
+
111
+ @overload
112
+ def __init__(
113
+ self,
114
+ *,
115
+ azure_deployment: str | None = None,
116
+ api_version: str | None = None,
117
+ api_key: str | None = None,
118
+ azure_ad_token: str | None = None,
119
+ azure_ad_token_provider: AzureADTokenProvider | None = None,
120
+ organization: str | None = None,
121
+ webhook_secret: str | None = None,
122
+ websocket_base_url: str | httpx.URL | None = None,
123
+ timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
124
+ max_retries: int = DEFAULT_MAX_RETRIES,
125
+ default_headers: Mapping[str, str] | None = None,
126
+ default_query: Mapping[str, object] | None = None,
127
+ http_client: httpx.Client | None = None,
128
+ _strict_response_validation: bool = False,
129
+ ) -> None: ...
130
+
131
+ @overload
132
+ def __init__(
133
+ self,
134
+ *,
135
+ base_url: str,
136
+ api_version: str | None = None,
137
+ api_key: str | None = None,
138
+ azure_ad_token: str | None = None,
139
+ azure_ad_token_provider: AzureADTokenProvider | None = None,
140
+ organization: str | None = None,
141
+ webhook_secret: str | None = None,
142
+ websocket_base_url: str | httpx.URL | None = None,
143
+ timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
144
+ max_retries: int = DEFAULT_MAX_RETRIES,
145
+ default_headers: Mapping[str, str] | None = None,
146
+ default_query: Mapping[str, object] | None = None,
147
+ http_client: httpx.Client | None = None,
148
+ _strict_response_validation: bool = False,
149
+ ) -> None: ...
150
+
151
+ def __init__(
152
+ self,
153
+ *,
154
+ api_version: str | None = None,
155
+ azure_endpoint: str | None = None,
156
+ azure_deployment: str | None = None,
157
+ api_key: str | None = None,
158
+ azure_ad_token: str | None = None,
159
+ azure_ad_token_provider: AzureADTokenProvider | None = None,
160
+ organization: str | None = None,
161
+ project: str | None = None,
162
+ webhook_secret: str | None = None,
163
+ websocket_base_url: str | httpx.URL | None = None,
164
+ base_url: str | None = None,
165
+ timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
166
+ max_retries: int = DEFAULT_MAX_RETRIES,
167
+ default_headers: Mapping[str, str] | None = None,
168
+ default_query: Mapping[str, object] | None = None,
169
+ http_client: httpx.Client | None = None,
170
+ _strict_response_validation: bool = False,
171
+ ) -> None:
172
+ """Construct a new synchronous azure openai client instance.
173
+
174
+ This automatically infers the following arguments from their corresponding environment variables if they are not provided:
175
+ - `api_key` from `AZURE_OPENAI_API_KEY`
176
+ - `organization` from `OPENAI_ORG_ID`
177
+ - `project` from `OPENAI_PROJECT_ID`
178
+ - `azure_ad_token` from `AZURE_OPENAI_AD_TOKEN`
179
+ - `api_version` from `OPENAI_API_VERSION`
180
+ - `azure_endpoint` from `AZURE_OPENAI_ENDPOINT`
181
+
182
+ Args:
183
+ azure_endpoint: Your Azure endpoint, including the resource, e.g. `https://example-resource.azure.openai.com/`
184
+
185
+ azure_ad_token: Your Azure Active Directory token, https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id
186
+
187
+ azure_ad_token_provider: A function that returns an Azure Active Directory token, will be invoked on every request.
188
+
189
+ azure_deployment: A model deployment, if given with `azure_endpoint`, sets the base client URL to include `/deployments/{azure_deployment}`.
190
+ Not supported with Assistants APIs.
191
+ """
192
+ if api_key is None:
193
+ api_key = os.environ.get("AZURE_OPENAI_API_KEY")
194
+
195
+ if azure_ad_token is None:
196
+ azure_ad_token = os.environ.get("AZURE_OPENAI_AD_TOKEN")
197
+
198
+ if api_key is None and azure_ad_token is None and azure_ad_token_provider is None:
199
+ raise OpenAIError(
200
+ "Missing credentials. Please pass one of `api_key`, `azure_ad_token`, `azure_ad_token_provider`, or the `AZURE_OPENAI_API_KEY` or `AZURE_OPENAI_AD_TOKEN` environment variables."
201
+ )
202
+
203
+ if api_version is None:
204
+ api_version = os.environ.get("OPENAI_API_VERSION")
205
+
206
+ if api_version is None:
207
+ raise ValueError(
208
+ "Must provide either the `api_version` argument or the `OPENAI_API_VERSION` environment variable"
209
+ )
210
+
211
+ if default_query is None:
212
+ default_query = {"api-version": api_version}
213
+ else:
214
+ default_query = {**default_query, "api-version": api_version}
215
+
216
+ if base_url is None:
217
+ if azure_endpoint is None:
218
+ azure_endpoint = os.environ.get("AZURE_OPENAI_ENDPOINT")
219
+
220
+ if azure_endpoint is None:
221
+ raise ValueError(
222
+ "Must provide one of the `base_url` or `azure_endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable"
223
+ )
224
+
225
+ if azure_deployment is not None:
226
+ base_url = f"{azure_endpoint.rstrip('/')}/openai/deployments/{azure_deployment}"
227
+ else:
228
+ base_url = f"{azure_endpoint.rstrip('/')}/openai"
229
+ else:
230
+ if azure_endpoint is not None:
231
+ raise ValueError("base_url and azure_endpoint are mutually exclusive")
232
+
233
+ if api_key is None:
234
+ # define a sentinel value to avoid any typing issues
235
+ api_key = API_KEY_SENTINEL
236
+
237
+ super().__init__(
238
+ api_key=api_key,
239
+ organization=organization,
240
+ project=project,
241
+ webhook_secret=webhook_secret,
242
+ base_url=base_url,
243
+ timeout=timeout,
244
+ max_retries=max_retries,
245
+ default_headers=default_headers,
246
+ default_query=default_query,
247
+ http_client=http_client,
248
+ websocket_base_url=websocket_base_url,
249
+ _strict_response_validation=_strict_response_validation,
250
+ )
251
+ self._api_version = api_version
252
+ self._azure_ad_token = azure_ad_token
253
+ self._azure_ad_token_provider = azure_ad_token_provider
254
+ self._azure_deployment = azure_deployment if azure_endpoint else None
255
+ self._azure_endpoint = httpx.URL(azure_endpoint) if azure_endpoint else None
256
+
257
+ @override
258
+ def copy(
259
+ self,
260
+ *,
261
+ api_key: str | None = None,
262
+ organization: str | None = None,
263
+ project: str | None = None,
264
+ webhook_secret: str | None = None,
265
+ websocket_base_url: str | httpx.URL | None = None,
266
+ api_version: str | None = None,
267
+ azure_ad_token: str | None = None,
268
+ azure_ad_token_provider: AzureADTokenProvider | None = None,
269
+ base_url: str | httpx.URL | None = None,
270
+ timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
271
+ http_client: httpx.Client | None = None,
272
+ max_retries: int | NotGiven = NOT_GIVEN,
273
+ default_headers: Mapping[str, str] | None = None,
274
+ set_default_headers: Mapping[str, str] | None = None,
275
+ default_query: Mapping[str, object] | None = None,
276
+ set_default_query: Mapping[str, object] | None = None,
277
+ _extra_kwargs: Mapping[str, Any] = {},
278
+ ) -> Self:
279
+ """
280
+ Create a new client instance re-using the same options given to the current client with optional overriding.
281
+ """
282
+ return super().copy(
283
+ api_key=api_key,
284
+ organization=organization,
285
+ project=project,
286
+ webhook_secret=webhook_secret,
287
+ websocket_base_url=websocket_base_url,
288
+ base_url=base_url,
289
+ timeout=timeout,
290
+ http_client=http_client,
291
+ max_retries=max_retries,
292
+ default_headers=default_headers,
293
+ set_default_headers=set_default_headers,
294
+ default_query=default_query,
295
+ set_default_query=set_default_query,
296
+ _extra_kwargs={
297
+ "api_version": api_version or self._api_version,
298
+ "azure_ad_token": azure_ad_token or self._azure_ad_token,
299
+ "azure_ad_token_provider": azure_ad_token_provider or self._azure_ad_token_provider,
300
+ **_extra_kwargs,
301
+ },
302
+ )
303
+
304
+ with_options = copy
305
+
306
+ def _get_azure_ad_token(self) -> str | None:
307
+ if self._azure_ad_token is not None:
308
+ return self._azure_ad_token
309
+
310
+ provider = self._azure_ad_token_provider
311
+ if provider is not None:
312
+ token = provider()
313
+ if not token or not isinstance(token, str): # pyright: ignore[reportUnnecessaryIsInstance]
314
+ raise ValueError(
315
+ f"Expected `azure_ad_token_provider` argument to return a string but it returned {token}",
316
+ )
317
+ return token
318
+
319
+ return None
320
+
321
+ @override
322
+ def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions:
323
+ headers: dict[str, str | Omit] = {**options.headers} if is_given(options.headers) else {}
324
+
325
+ options = model_copy(options)
326
+ options.headers = headers
327
+
328
+ azure_ad_token = self._get_azure_ad_token()
329
+ if azure_ad_token is not None:
330
+ if headers.get("Authorization") is None:
331
+ headers["Authorization"] = f"Bearer {azure_ad_token}"
332
+ elif self.api_key is not API_KEY_SENTINEL:
333
+ if headers.get("api-key") is None:
334
+ headers["api-key"] = self.api_key
335
+ else:
336
+ # should never be hit
337
+ raise ValueError("Unable to handle auth")
338
+
339
+ return options
340
+
341
+ def _configure_realtime(self, model: str, extra_query: Query) -> tuple[httpx.URL, dict[str, str]]:
342
+ auth_headers = {}
343
+ query = {
344
+ **extra_query,
345
+ "api-version": self._api_version,
346
+ "deployment": self._azure_deployment or model,
347
+ }
348
+ if self.api_key != "<missing API key>":
349
+ auth_headers = {"api-key": self.api_key}
350
+ else:
351
+ token = self._get_azure_ad_token()
352
+ if token:
353
+ auth_headers = {"Authorization": f"Bearer {token}"}
354
+
355
+ if self.websocket_base_url is not None:
356
+ base_url = httpx.URL(self.websocket_base_url)
357
+ merge_raw_path = base_url.raw_path.rstrip(b"/") + b"/realtime"
358
+ realtime_url = base_url.copy_with(raw_path=merge_raw_path)
359
+ else:
360
+ base_url = self._prepare_url("/realtime")
361
+ realtime_url = base_url.copy_with(scheme="wss")
362
+
363
+ url = realtime_url.copy_with(params={**query})
364
+ return url, auth_headers
365
+
366
+
367
+ class AsyncAzureOpenAI(BaseAzureClient[httpx.AsyncClient, AsyncStream[Any]], AsyncOpenAI):
368
+ @overload
369
+ def __init__(
370
+ self,
371
+ *,
372
+ azure_endpoint: str,
373
+ azure_deployment: str | None = None,
374
+ api_version: str | None = None,
375
+ api_key: str | None = None,
376
+ azure_ad_token: str | None = None,
377
+ azure_ad_token_provider: AsyncAzureADTokenProvider | None = None,
378
+ organization: str | None = None,
379
+ project: str | None = None,
380
+ webhook_secret: str | None = None,
381
+ websocket_base_url: str | httpx.URL | None = None,
382
+ timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
383
+ max_retries: int = DEFAULT_MAX_RETRIES,
384
+ default_headers: Mapping[str, str] | None = None,
385
+ default_query: Mapping[str, object] | None = None,
386
+ http_client: httpx.AsyncClient | None = None,
387
+ _strict_response_validation: bool = False,
388
+ ) -> None: ...
389
+
390
+ @overload
391
+ def __init__(
392
+ self,
393
+ *,
394
+ azure_deployment: str | None = None,
395
+ api_version: str | None = None,
396
+ api_key: str | None = None,
397
+ azure_ad_token: str | None = None,
398
+ azure_ad_token_provider: AsyncAzureADTokenProvider | None = None,
399
+ organization: str | None = None,
400
+ project: str | None = None,
401
+ webhook_secret: str | None = None,
402
+ websocket_base_url: str | httpx.URL | None = None,
403
+ timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
404
+ max_retries: int = DEFAULT_MAX_RETRIES,
405
+ default_headers: Mapping[str, str] | None = None,
406
+ default_query: Mapping[str, object] | None = None,
407
+ http_client: httpx.AsyncClient | None = None,
408
+ _strict_response_validation: bool = False,
409
+ ) -> None: ...
410
+
411
+ @overload
412
+ def __init__(
413
+ self,
414
+ *,
415
+ base_url: str,
416
+ api_version: str | None = None,
417
+ api_key: str | None = None,
418
+ azure_ad_token: str | None = None,
419
+ azure_ad_token_provider: AsyncAzureADTokenProvider | None = None,
420
+ organization: str | None = None,
421
+ project: str | None = None,
422
+ webhook_secret: str | None = None,
423
+ websocket_base_url: str | httpx.URL | None = None,
424
+ timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
425
+ max_retries: int = DEFAULT_MAX_RETRIES,
426
+ default_headers: Mapping[str, str] | None = None,
427
+ default_query: Mapping[str, object] | None = None,
428
+ http_client: httpx.AsyncClient | None = None,
429
+ _strict_response_validation: bool = False,
430
+ ) -> None: ...
431
+
432
+ def __init__(
433
+ self,
434
+ *,
435
+ azure_endpoint: str | None = None,
436
+ azure_deployment: str | None = None,
437
+ api_version: str | None = None,
438
+ api_key: str | None = None,
439
+ azure_ad_token: str | None = None,
440
+ azure_ad_token_provider: AsyncAzureADTokenProvider | None = None,
441
+ organization: str | None = None,
442
+ project: str | None = None,
443
+ webhook_secret: str | None = None,
444
+ base_url: str | None = None,
445
+ websocket_base_url: str | httpx.URL | None = None,
446
+ timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
447
+ max_retries: int = DEFAULT_MAX_RETRIES,
448
+ default_headers: Mapping[str, str] | None = None,
449
+ default_query: Mapping[str, object] | None = None,
450
+ http_client: httpx.AsyncClient | None = None,
451
+ _strict_response_validation: bool = False,
452
+ ) -> None:
453
+ """Construct a new asynchronous azure openai client instance.
454
+
455
+ This automatically infers the following arguments from their corresponding environment variables if they are not provided:
456
+ - `api_key` from `AZURE_OPENAI_API_KEY`
457
+ - `organization` from `OPENAI_ORG_ID`
458
+ - `project` from `OPENAI_PROJECT_ID`
459
+ - `azure_ad_token` from `AZURE_OPENAI_AD_TOKEN`
460
+ - `api_version` from `OPENAI_API_VERSION`
461
+ - `azure_endpoint` from `AZURE_OPENAI_ENDPOINT`
462
+
463
+ Args:
464
+ azure_endpoint: Your Azure endpoint, including the resource, e.g. `https://example-resource.azure.openai.com/`
465
+
466
+ azure_ad_token: Your Azure Active Directory token, https://www.microsoft.com/en-us/security/business/identity-access/microsoft-entra-id
467
+
468
+ azure_ad_token_provider: A function that returns an Azure Active Directory token, will be invoked on every request.
469
+
470
+ azure_deployment: A model deployment, if given with `azure_endpoint`, sets the base client URL to include `/deployments/{azure_deployment}`.
471
+ Not supported with Assistants APIs.
472
+ """
473
+ if api_key is None:
474
+ api_key = os.environ.get("AZURE_OPENAI_API_KEY")
475
+
476
+ if azure_ad_token is None:
477
+ azure_ad_token = os.environ.get("AZURE_OPENAI_AD_TOKEN")
478
+
479
+ if api_key is None and azure_ad_token is None and azure_ad_token_provider is None:
480
+ raise OpenAIError(
481
+ "Missing credentials. Please pass one of `api_key`, `azure_ad_token`, `azure_ad_token_provider`, or the `AZURE_OPENAI_API_KEY` or `AZURE_OPENAI_AD_TOKEN` environment variables."
482
+ )
483
+
484
+ if api_version is None:
485
+ api_version = os.environ.get("OPENAI_API_VERSION")
486
+
487
+ if api_version is None:
488
+ raise ValueError(
489
+ "Must provide either the `api_version` argument or the `OPENAI_API_VERSION` environment variable"
490
+ )
491
+
492
+ if default_query is None:
493
+ default_query = {"api-version": api_version}
494
+ else:
495
+ default_query = {**default_query, "api-version": api_version}
496
+
497
+ if base_url is None:
498
+ if azure_endpoint is None:
499
+ azure_endpoint = os.environ.get("AZURE_OPENAI_ENDPOINT")
500
+
501
+ if azure_endpoint is None:
502
+ raise ValueError(
503
+ "Must provide one of the `base_url` or `azure_endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable"
504
+ )
505
+
506
+ if azure_deployment is not None:
507
+ base_url = f"{azure_endpoint.rstrip('/')}/openai/deployments/{azure_deployment}"
508
+ else:
509
+ base_url = f"{azure_endpoint.rstrip('/')}/openai"
510
+ else:
511
+ if azure_endpoint is not None:
512
+ raise ValueError("base_url and azure_endpoint are mutually exclusive")
513
+
514
+ if api_key is None:
515
+ # define a sentinel value to avoid any typing issues
516
+ api_key = API_KEY_SENTINEL
517
+
518
+ super().__init__(
519
+ api_key=api_key,
520
+ organization=organization,
521
+ project=project,
522
+ webhook_secret=webhook_secret,
523
+ base_url=base_url,
524
+ timeout=timeout,
525
+ max_retries=max_retries,
526
+ default_headers=default_headers,
527
+ default_query=default_query,
528
+ http_client=http_client,
529
+ websocket_base_url=websocket_base_url,
530
+ _strict_response_validation=_strict_response_validation,
531
+ )
532
+ self._api_version = api_version
533
+ self._azure_ad_token = azure_ad_token
534
+ self._azure_ad_token_provider = azure_ad_token_provider
535
+ self._azure_deployment = azure_deployment if azure_endpoint else None
536
+ self._azure_endpoint = httpx.URL(azure_endpoint) if azure_endpoint else None
537
+
538
+ @override
539
+ def copy(
540
+ self,
541
+ *,
542
+ api_key: str | None = None,
543
+ organization: str | None = None,
544
+ project: str | None = None,
545
+ webhook_secret: str | None = None,
546
+ websocket_base_url: str | httpx.URL | None = None,
547
+ api_version: str | None = None,
548
+ azure_ad_token: str | None = None,
549
+ azure_ad_token_provider: AsyncAzureADTokenProvider | None = None,
550
+ base_url: str | httpx.URL | None = None,
551
+ timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
552
+ http_client: httpx.AsyncClient | None = None,
553
+ max_retries: int | NotGiven = NOT_GIVEN,
554
+ default_headers: Mapping[str, str] | None = None,
555
+ set_default_headers: Mapping[str, str] | None = None,
556
+ default_query: Mapping[str, object] | None = None,
557
+ set_default_query: Mapping[str, object] | None = None,
558
+ _extra_kwargs: Mapping[str, Any] = {},
559
+ ) -> Self:
560
+ """
561
+ Create a new client instance re-using the same options given to the current client with optional overriding.
562
+ """
563
+ return super().copy(
564
+ api_key=api_key,
565
+ organization=organization,
566
+ project=project,
567
+ webhook_secret=webhook_secret,
568
+ websocket_base_url=websocket_base_url,
569
+ base_url=base_url,
570
+ timeout=timeout,
571
+ http_client=http_client,
572
+ max_retries=max_retries,
573
+ default_headers=default_headers,
574
+ set_default_headers=set_default_headers,
575
+ default_query=default_query,
576
+ set_default_query=set_default_query,
577
+ _extra_kwargs={
578
+ "api_version": api_version or self._api_version,
579
+ "azure_ad_token": azure_ad_token or self._azure_ad_token,
580
+ "azure_ad_token_provider": azure_ad_token_provider or self._azure_ad_token_provider,
581
+ **_extra_kwargs,
582
+ },
583
+ )
584
+
585
+ with_options = copy
586
+
587
+ async def _get_azure_ad_token(self) -> str | None:
588
+ if self._azure_ad_token is not None:
589
+ return self._azure_ad_token
590
+
591
+ provider = self._azure_ad_token_provider
592
+ if provider is not None:
593
+ token = provider()
594
+ if inspect.isawaitable(token):
595
+ token = await token
596
+ if not token or not isinstance(cast(Any, token), str):
597
+ raise ValueError(
598
+ f"Expected `azure_ad_token_provider` argument to return a string but it returned {token}",
599
+ )
600
+ return str(token)
601
+
602
+ return None
603
+
604
+ @override
605
+ async def _prepare_options(self, options: FinalRequestOptions) -> FinalRequestOptions:
606
+ headers: dict[str, str | Omit] = {**options.headers} if is_given(options.headers) else {}
607
+
608
+ options = model_copy(options)
609
+ options.headers = headers
610
+
611
+ azure_ad_token = await self._get_azure_ad_token()
612
+ if azure_ad_token is not None:
613
+ if headers.get("Authorization") is None:
614
+ headers["Authorization"] = f"Bearer {azure_ad_token}"
615
+ elif self.api_key is not API_KEY_SENTINEL:
616
+ if headers.get("api-key") is None:
617
+ headers["api-key"] = self.api_key
618
+ else:
619
+ # should never be hit
620
+ raise ValueError("Unable to handle auth")
621
+
622
+ return options
623
+
624
+ async def _configure_realtime(self, model: str, extra_query: Query) -> tuple[httpx.URL, dict[str, str]]:
625
+ auth_headers = {}
626
+ query = {
627
+ **extra_query,
628
+ "api-version": self._api_version,
629
+ "deployment": self._azure_deployment or model,
630
+ }
631
+ if self.api_key != "<missing API key>":
632
+ auth_headers = {"api-key": self.api_key}
633
+ else:
634
+ token = await self._get_azure_ad_token()
635
+ if token:
636
+ auth_headers = {"Authorization": f"Bearer {token}"}
637
+
638
+ if self.websocket_base_url is not None:
639
+ base_url = httpx.URL(self.websocket_base_url)
640
+ merge_raw_path = base_url.raw_path.rstrip(b"/") + b"/realtime"
641
+ realtime_url = base_url.copy_with(raw_path=merge_raw_path)
642
+ else:
643
+ base_url = self._prepare_url("/realtime")
644
+ realtime_url = base_url.copy_with(scheme="wss")
645
+
646
+ url = realtime_url.copy_with(params={**query})
647
+ return url, auth_headers
python_embeded/Lib/site-packages/openai/resources/__init__.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from .beta import (
4
+ Beta,
5
+ AsyncBeta,
6
+ BetaWithRawResponse,
7
+ AsyncBetaWithRawResponse,
8
+ BetaWithStreamingResponse,
9
+ AsyncBetaWithStreamingResponse,
10
+ )
11
+ from .chat import (
12
+ Chat,
13
+ AsyncChat,
14
+ ChatWithRawResponse,
15
+ AsyncChatWithRawResponse,
16
+ ChatWithStreamingResponse,
17
+ AsyncChatWithStreamingResponse,
18
+ )
19
+ from .audio import (
20
+ Audio,
21
+ AsyncAudio,
22
+ AudioWithRawResponse,
23
+ AsyncAudioWithRawResponse,
24
+ AudioWithStreamingResponse,
25
+ AsyncAudioWithStreamingResponse,
26
+ )
27
+ from .evals import (
28
+ Evals,
29
+ AsyncEvals,
30
+ EvalsWithRawResponse,
31
+ AsyncEvalsWithRawResponse,
32
+ EvalsWithStreamingResponse,
33
+ AsyncEvalsWithStreamingResponse,
34
+ )
35
+ from .files import (
36
+ Files,
37
+ AsyncFiles,
38
+ FilesWithRawResponse,
39
+ AsyncFilesWithRawResponse,
40
+ FilesWithStreamingResponse,
41
+ AsyncFilesWithStreamingResponse,
42
+ )
43
+ from .images import (
44
+ Images,
45
+ AsyncImages,
46
+ ImagesWithRawResponse,
47
+ AsyncImagesWithRawResponse,
48
+ ImagesWithStreamingResponse,
49
+ AsyncImagesWithStreamingResponse,
50
+ )
51
+ from .models import (
52
+ Models,
53
+ AsyncModels,
54
+ ModelsWithRawResponse,
55
+ AsyncModelsWithRawResponse,
56
+ ModelsWithStreamingResponse,
57
+ AsyncModelsWithStreamingResponse,
58
+ )
59
+ from .batches import (
60
+ Batches,
61
+ AsyncBatches,
62
+ BatchesWithRawResponse,
63
+ AsyncBatchesWithRawResponse,
64
+ BatchesWithStreamingResponse,
65
+ AsyncBatchesWithStreamingResponse,
66
+ )
67
+ from .uploads import (
68
+ Uploads,
69
+ AsyncUploads,
70
+ UploadsWithRawResponse,
71
+ AsyncUploadsWithRawResponse,
72
+ UploadsWithStreamingResponse,
73
+ AsyncUploadsWithStreamingResponse,
74
+ )
75
+ from .containers import (
76
+ Containers,
77
+ AsyncContainers,
78
+ ContainersWithRawResponse,
79
+ AsyncContainersWithRawResponse,
80
+ ContainersWithStreamingResponse,
81
+ AsyncContainersWithStreamingResponse,
82
+ )
83
+ from .embeddings import (
84
+ Embeddings,
85
+ AsyncEmbeddings,
86
+ EmbeddingsWithRawResponse,
87
+ AsyncEmbeddingsWithRawResponse,
88
+ EmbeddingsWithStreamingResponse,
89
+ AsyncEmbeddingsWithStreamingResponse,
90
+ )
91
+ from .completions import (
92
+ Completions,
93
+ AsyncCompletions,
94
+ CompletionsWithRawResponse,
95
+ AsyncCompletionsWithRawResponse,
96
+ CompletionsWithStreamingResponse,
97
+ AsyncCompletionsWithStreamingResponse,
98
+ )
99
+ from .fine_tuning import (
100
+ FineTuning,
101
+ AsyncFineTuning,
102
+ FineTuningWithRawResponse,
103
+ AsyncFineTuningWithRawResponse,
104
+ FineTuningWithStreamingResponse,
105
+ AsyncFineTuningWithStreamingResponse,
106
+ )
107
+ from .moderations import (
108
+ Moderations,
109
+ AsyncModerations,
110
+ ModerationsWithRawResponse,
111
+ AsyncModerationsWithRawResponse,
112
+ ModerationsWithStreamingResponse,
113
+ AsyncModerationsWithStreamingResponse,
114
+ )
115
+ from .vector_stores import (
116
+ VectorStores,
117
+ AsyncVectorStores,
118
+ VectorStoresWithRawResponse,
119
+ AsyncVectorStoresWithRawResponse,
120
+ VectorStoresWithStreamingResponse,
121
+ AsyncVectorStoresWithStreamingResponse,
122
+ )
123
+
124
+ __all__ = [
125
+ "Completions",
126
+ "AsyncCompletions",
127
+ "CompletionsWithRawResponse",
128
+ "AsyncCompletionsWithRawResponse",
129
+ "CompletionsWithStreamingResponse",
130
+ "AsyncCompletionsWithStreamingResponse",
131
+ "Chat",
132
+ "AsyncChat",
133
+ "ChatWithRawResponse",
134
+ "AsyncChatWithRawResponse",
135
+ "ChatWithStreamingResponse",
136
+ "AsyncChatWithStreamingResponse",
137
+ "Embeddings",
138
+ "AsyncEmbeddings",
139
+ "EmbeddingsWithRawResponse",
140
+ "AsyncEmbeddingsWithRawResponse",
141
+ "EmbeddingsWithStreamingResponse",
142
+ "AsyncEmbeddingsWithStreamingResponse",
143
+ "Files",
144
+ "AsyncFiles",
145
+ "FilesWithRawResponse",
146
+ "AsyncFilesWithRawResponse",
147
+ "FilesWithStreamingResponse",
148
+ "AsyncFilesWithStreamingResponse",
149
+ "Images",
150
+ "AsyncImages",
151
+ "ImagesWithRawResponse",
152
+ "AsyncImagesWithRawResponse",
153
+ "ImagesWithStreamingResponse",
154
+ "AsyncImagesWithStreamingResponse",
155
+ "Audio",
156
+ "AsyncAudio",
157
+ "AudioWithRawResponse",
158
+ "AsyncAudioWithRawResponse",
159
+ "AudioWithStreamingResponse",
160
+ "AsyncAudioWithStreamingResponse",
161
+ "Moderations",
162
+ "AsyncModerations",
163
+ "ModerationsWithRawResponse",
164
+ "AsyncModerationsWithRawResponse",
165
+ "ModerationsWithStreamingResponse",
166
+ "AsyncModerationsWithStreamingResponse",
167
+ "Models",
168
+ "AsyncModels",
169
+ "ModelsWithRawResponse",
170
+ "AsyncModelsWithRawResponse",
171
+ "ModelsWithStreamingResponse",
172
+ "AsyncModelsWithStreamingResponse",
173
+ "FineTuning",
174
+ "AsyncFineTuning",
175
+ "FineTuningWithRawResponse",
176
+ "AsyncFineTuningWithRawResponse",
177
+ "FineTuningWithStreamingResponse",
178
+ "AsyncFineTuningWithStreamingResponse",
179
+ "VectorStores",
180
+ "AsyncVectorStores",
181
+ "VectorStoresWithRawResponse",
182
+ "AsyncVectorStoresWithRawResponse",
183
+ "VectorStoresWithStreamingResponse",
184
+ "AsyncVectorStoresWithStreamingResponse",
185
+ "Beta",
186
+ "AsyncBeta",
187
+ "BetaWithRawResponse",
188
+ "AsyncBetaWithRawResponse",
189
+ "BetaWithStreamingResponse",
190
+ "AsyncBetaWithStreamingResponse",
191
+ "Batches",
192
+ "AsyncBatches",
193
+ "BatchesWithRawResponse",
194
+ "AsyncBatchesWithRawResponse",
195
+ "BatchesWithStreamingResponse",
196
+ "AsyncBatchesWithStreamingResponse",
197
+ "Uploads",
198
+ "AsyncUploads",
199
+ "UploadsWithRawResponse",
200
+ "AsyncUploadsWithRawResponse",
201
+ "UploadsWithStreamingResponse",
202
+ "AsyncUploadsWithStreamingResponse",
203
+ "Evals",
204
+ "AsyncEvals",
205
+ "EvalsWithRawResponse",
206
+ "AsyncEvalsWithRawResponse",
207
+ "EvalsWithStreamingResponse",
208
+ "AsyncEvalsWithStreamingResponse",
209
+ "Containers",
210
+ "AsyncContainers",
211
+ "ContainersWithRawResponse",
212
+ "AsyncContainersWithRawResponse",
213
+ "ContainersWithStreamingResponse",
214
+ "AsyncContainersWithStreamingResponse",
215
+ ]
python_embeded/Lib/site-packages/openai/resources/batches.py ADDED
@@ -0,0 +1,514 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Optional
6
+ from typing_extensions import Literal
7
+
8
+ import httpx
9
+
10
+ from .. import _legacy_response
11
+ from ..types import batch_list_params, batch_create_params
12
+ from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven
13
+ from .._utils import maybe_transform, async_maybe_transform
14
+ from .._compat import cached_property
15
+ from .._resource import SyncAPIResource, AsyncAPIResource
16
+ from .._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper
17
+ from ..pagination import SyncCursorPage, AsyncCursorPage
18
+ from ..types.batch import Batch
19
+ from .._base_client import AsyncPaginator, make_request_options
20
+ from ..types.shared_params.metadata import Metadata
21
+
22
+ __all__ = ["Batches", "AsyncBatches"]
23
+
24
+
25
+ class Batches(SyncAPIResource):
26
+ @cached_property
27
+ def with_raw_response(self) -> BatchesWithRawResponse:
28
+ """
29
+ This property can be used as a prefix for any HTTP method call to return
30
+ the raw response object instead of the parsed content.
31
+
32
+ For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
33
+ """
34
+ return BatchesWithRawResponse(self)
35
+
36
+ @cached_property
37
+ def with_streaming_response(self) -> BatchesWithStreamingResponse:
38
+ """
39
+ An alternative to `.with_raw_response` that doesn't eagerly read the response body.
40
+
41
+ For more information, see https://www.github.com/openai/openai-python#with_streaming_response
42
+ """
43
+ return BatchesWithStreamingResponse(self)
44
+
45
+ def create(
46
+ self,
47
+ *,
48
+ completion_window: Literal["24h"],
49
+ endpoint: Literal["/v1/responses", "/v1/chat/completions", "/v1/embeddings", "/v1/completions"],
50
+ input_file_id: str,
51
+ metadata: Optional[Metadata] | NotGiven = NOT_GIVEN,
52
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
53
+ # The extra values given here take precedence over values defined on the client or passed to this method.
54
+ extra_headers: Headers | None = None,
55
+ extra_query: Query | None = None,
56
+ extra_body: Body | None = None,
57
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
58
+ ) -> Batch:
59
+ """
60
+ Creates and executes a batch from an uploaded file of requests
61
+
62
+ Args:
63
+ completion_window: The time frame within which the batch should be processed. Currently only `24h`
64
+ is supported.
65
+
66
+ endpoint: The endpoint to be used for all requests in the batch. Currently
67
+ `/v1/responses`, `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions`
68
+ are supported. Note that `/v1/embeddings` batches are also restricted to a
69
+ maximum of 50,000 embedding inputs across all requests in the batch.
70
+
71
+ input_file_id: The ID of an uploaded file that contains requests for the new batch.
72
+
73
+ See [upload file](https://platform.openai.com/docs/api-reference/files/create)
74
+ for how to upload a file.
75
+
76
+ Your input file must be formatted as a
77
+ [JSONL file](https://platform.openai.com/docs/api-reference/batch/request-input),
78
+ and must be uploaded with the purpose `batch`. The file can contain up to 50,000
79
+ requests, and can be up to 200 MB in size.
80
+
81
+ metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful
82
+ for storing additional information about the object in a structured format, and
83
+ querying for objects via API or the dashboard.
84
+
85
+ Keys are strings with a maximum length of 64 characters. Values are strings with
86
+ a maximum length of 512 characters.
87
+
88
+ extra_headers: Send extra headers
89
+
90
+ extra_query: Add additional query parameters to the request
91
+
92
+ extra_body: Add additional JSON properties to the request
93
+
94
+ timeout: Override the client-level default timeout for this request, in seconds
95
+ """
96
+ return self._post(
97
+ "/batches",
98
+ body=maybe_transform(
99
+ {
100
+ "completion_window": completion_window,
101
+ "endpoint": endpoint,
102
+ "input_file_id": input_file_id,
103
+ "metadata": metadata,
104
+ },
105
+ batch_create_params.BatchCreateParams,
106
+ ),
107
+ options=make_request_options(
108
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
109
+ ),
110
+ cast_to=Batch,
111
+ )
112
+
113
+ def retrieve(
114
+ self,
115
+ batch_id: str,
116
+ *,
117
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
118
+ # The extra values given here take precedence over values defined on the client or passed to this method.
119
+ extra_headers: Headers | None = None,
120
+ extra_query: Query | None = None,
121
+ extra_body: Body | None = None,
122
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
123
+ ) -> Batch:
124
+ """
125
+ Retrieves a batch.
126
+
127
+ Args:
128
+ extra_headers: Send extra headers
129
+
130
+ extra_query: Add additional query parameters to the request
131
+
132
+ extra_body: Add additional JSON properties to the request
133
+
134
+ timeout: Override the client-level default timeout for this request, in seconds
135
+ """
136
+ if not batch_id:
137
+ raise ValueError(f"Expected a non-empty value for `batch_id` but received {batch_id!r}")
138
+ return self._get(
139
+ f"/batches/{batch_id}",
140
+ options=make_request_options(
141
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
142
+ ),
143
+ cast_to=Batch,
144
+ )
145
+
146
+ def list(
147
+ self,
148
+ *,
149
+ after: str | NotGiven = NOT_GIVEN,
150
+ limit: int | NotGiven = NOT_GIVEN,
151
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
152
+ # The extra values given here take precedence over values defined on the client or passed to this method.
153
+ extra_headers: Headers | None = None,
154
+ extra_query: Query | None = None,
155
+ extra_body: Body | None = None,
156
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
157
+ ) -> SyncCursorPage[Batch]:
158
+ """List your organization's batches.
159
+
160
+ Args:
161
+ after: A cursor for use in pagination.
162
+
163
+ `after` is an object ID that defines your place
164
+ in the list. For instance, if you make a list request and receive 100 objects,
165
+ ending with obj_foo, your subsequent call can include after=obj_foo in order to
166
+ fetch the next page of the list.
167
+
168
+ limit: A limit on the number of objects to be returned. Limit can range between 1 and
169
+ 100, and the default is 20.
170
+
171
+ extra_headers: Send extra headers
172
+
173
+ extra_query: Add additional query parameters to the request
174
+
175
+ extra_body: Add additional JSON properties to the request
176
+
177
+ timeout: Override the client-level default timeout for this request, in seconds
178
+ """
179
+ return self._get_api_list(
180
+ "/batches",
181
+ page=SyncCursorPage[Batch],
182
+ options=make_request_options(
183
+ extra_headers=extra_headers,
184
+ extra_query=extra_query,
185
+ extra_body=extra_body,
186
+ timeout=timeout,
187
+ query=maybe_transform(
188
+ {
189
+ "after": after,
190
+ "limit": limit,
191
+ },
192
+ batch_list_params.BatchListParams,
193
+ ),
194
+ ),
195
+ model=Batch,
196
+ )
197
+
198
+ def cancel(
199
+ self,
200
+ batch_id: str,
201
+ *,
202
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
203
+ # The extra values given here take precedence over values defined on the client or passed to this method.
204
+ extra_headers: Headers | None = None,
205
+ extra_query: Query | None = None,
206
+ extra_body: Body | None = None,
207
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
208
+ ) -> Batch:
209
+ """Cancels an in-progress batch.
210
+
211
+ The batch will be in status `cancelling` for up to
212
+ 10 minutes, before changing to `cancelled`, where it will have partial results
213
+ (if any) available in the output file.
214
+
215
+ Args:
216
+ extra_headers: Send extra headers
217
+
218
+ extra_query: Add additional query parameters to the request
219
+
220
+ extra_body: Add additional JSON properties to the request
221
+
222
+ timeout: Override the client-level default timeout for this request, in seconds
223
+ """
224
+ if not batch_id:
225
+ raise ValueError(f"Expected a non-empty value for `batch_id` but received {batch_id!r}")
226
+ return self._post(
227
+ f"/batches/{batch_id}/cancel",
228
+ options=make_request_options(
229
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
230
+ ),
231
+ cast_to=Batch,
232
+ )
233
+
234
+
235
+ class AsyncBatches(AsyncAPIResource):
236
+ @cached_property
237
+ def with_raw_response(self) -> AsyncBatchesWithRawResponse:
238
+ """
239
+ This property can be used as a prefix for any HTTP method call to return
240
+ the raw response object instead of the parsed content.
241
+
242
+ For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
243
+ """
244
+ return AsyncBatchesWithRawResponse(self)
245
+
246
+ @cached_property
247
+ def with_streaming_response(self) -> AsyncBatchesWithStreamingResponse:
248
+ """
249
+ An alternative to `.with_raw_response` that doesn't eagerly read the response body.
250
+
251
+ For more information, see https://www.github.com/openai/openai-python#with_streaming_response
252
+ """
253
+ return AsyncBatchesWithStreamingResponse(self)
254
+
255
+ async def create(
256
+ self,
257
+ *,
258
+ completion_window: Literal["24h"],
259
+ endpoint: Literal["/v1/responses", "/v1/chat/completions", "/v1/embeddings", "/v1/completions"],
260
+ input_file_id: str,
261
+ metadata: Optional[Metadata] | NotGiven = NOT_GIVEN,
262
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
263
+ # The extra values given here take precedence over values defined on the client or passed to this method.
264
+ extra_headers: Headers | None = None,
265
+ extra_query: Query | None = None,
266
+ extra_body: Body | None = None,
267
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
268
+ ) -> Batch:
269
+ """
270
+ Creates and executes a batch from an uploaded file of requests
271
+
272
+ Args:
273
+ completion_window: The time frame within which the batch should be processed. Currently only `24h`
274
+ is supported.
275
+
276
+ endpoint: The endpoint to be used for all requests in the batch. Currently
277
+ `/v1/responses`, `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions`
278
+ are supported. Note that `/v1/embeddings` batches are also restricted to a
279
+ maximum of 50,000 embedding inputs across all requests in the batch.
280
+
281
+ input_file_id: The ID of an uploaded file that contains requests for the new batch.
282
+
283
+ See [upload file](https://platform.openai.com/docs/api-reference/files/create)
284
+ for how to upload a file.
285
+
286
+ Your input file must be formatted as a
287
+ [JSONL file](https://platform.openai.com/docs/api-reference/batch/request-input),
288
+ and must be uploaded with the purpose `batch`. The file can contain up to 50,000
289
+ requests, and can be up to 200 MB in size.
290
+
291
+ metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful
292
+ for storing additional information about the object in a structured format, and
293
+ querying for objects via API or the dashboard.
294
+
295
+ Keys are strings with a maximum length of 64 characters. Values are strings with
296
+ a maximum length of 512 characters.
297
+
298
+ extra_headers: Send extra headers
299
+
300
+ extra_query: Add additional query parameters to the request
301
+
302
+ extra_body: Add additional JSON properties to the request
303
+
304
+ timeout: Override the client-level default timeout for this request, in seconds
305
+ """
306
+ return await self._post(
307
+ "/batches",
308
+ body=await async_maybe_transform(
309
+ {
310
+ "completion_window": completion_window,
311
+ "endpoint": endpoint,
312
+ "input_file_id": input_file_id,
313
+ "metadata": metadata,
314
+ },
315
+ batch_create_params.BatchCreateParams,
316
+ ),
317
+ options=make_request_options(
318
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
319
+ ),
320
+ cast_to=Batch,
321
+ )
322
+
323
+ async def retrieve(
324
+ self,
325
+ batch_id: str,
326
+ *,
327
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
328
+ # The extra values given here take precedence over values defined on the client or passed to this method.
329
+ extra_headers: Headers | None = None,
330
+ extra_query: Query | None = None,
331
+ extra_body: Body | None = None,
332
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
333
+ ) -> Batch:
334
+ """
335
+ Retrieves a batch.
336
+
337
+ Args:
338
+ extra_headers: Send extra headers
339
+
340
+ extra_query: Add additional query parameters to the request
341
+
342
+ extra_body: Add additional JSON properties to the request
343
+
344
+ timeout: Override the client-level default timeout for this request, in seconds
345
+ """
346
+ if not batch_id:
347
+ raise ValueError(f"Expected a non-empty value for `batch_id` but received {batch_id!r}")
348
+ return await self._get(
349
+ f"/batches/{batch_id}",
350
+ options=make_request_options(
351
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
352
+ ),
353
+ cast_to=Batch,
354
+ )
355
+
356
+ def list(
357
+ self,
358
+ *,
359
+ after: str | NotGiven = NOT_GIVEN,
360
+ limit: int | NotGiven = NOT_GIVEN,
361
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
362
+ # The extra values given here take precedence over values defined on the client or passed to this method.
363
+ extra_headers: Headers | None = None,
364
+ extra_query: Query | None = None,
365
+ extra_body: Body | None = None,
366
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
367
+ ) -> AsyncPaginator[Batch, AsyncCursorPage[Batch]]:
368
+ """List your organization's batches.
369
+
370
+ Args:
371
+ after: A cursor for use in pagination.
372
+
373
+ `after` is an object ID that defines your place
374
+ in the list. For instance, if you make a list request and receive 100 objects,
375
+ ending with obj_foo, your subsequent call can include after=obj_foo in order to
376
+ fetch the next page of the list.
377
+
378
+ limit: A limit on the number of objects to be returned. Limit can range between 1 and
379
+ 100, and the default is 20.
380
+
381
+ extra_headers: Send extra headers
382
+
383
+ extra_query: Add additional query parameters to the request
384
+
385
+ extra_body: Add additional JSON properties to the request
386
+
387
+ timeout: Override the client-level default timeout for this request, in seconds
388
+ """
389
+ return self._get_api_list(
390
+ "/batches",
391
+ page=AsyncCursorPage[Batch],
392
+ options=make_request_options(
393
+ extra_headers=extra_headers,
394
+ extra_query=extra_query,
395
+ extra_body=extra_body,
396
+ timeout=timeout,
397
+ query=maybe_transform(
398
+ {
399
+ "after": after,
400
+ "limit": limit,
401
+ },
402
+ batch_list_params.BatchListParams,
403
+ ),
404
+ ),
405
+ model=Batch,
406
+ )
407
+
408
+ async def cancel(
409
+ self,
410
+ batch_id: str,
411
+ *,
412
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
413
+ # The extra values given here take precedence over values defined on the client or passed to this method.
414
+ extra_headers: Headers | None = None,
415
+ extra_query: Query | None = None,
416
+ extra_body: Body | None = None,
417
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
418
+ ) -> Batch:
419
+ """Cancels an in-progress batch.
420
+
421
+ The batch will be in status `cancelling` for up to
422
+ 10 minutes, before changing to `cancelled`, where it will have partial results
423
+ (if any) available in the output file.
424
+
425
+ Args:
426
+ extra_headers: Send extra headers
427
+
428
+ extra_query: Add additional query parameters to the request
429
+
430
+ extra_body: Add additional JSON properties to the request
431
+
432
+ timeout: Override the client-level default timeout for this request, in seconds
433
+ """
434
+ if not batch_id:
435
+ raise ValueError(f"Expected a non-empty value for `batch_id` but received {batch_id!r}")
436
+ return await self._post(
437
+ f"/batches/{batch_id}/cancel",
438
+ options=make_request_options(
439
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
440
+ ),
441
+ cast_to=Batch,
442
+ )
443
+
444
+
445
+ class BatchesWithRawResponse:
446
+ def __init__(self, batches: Batches) -> None:
447
+ self._batches = batches
448
+
449
+ self.create = _legacy_response.to_raw_response_wrapper(
450
+ batches.create,
451
+ )
452
+ self.retrieve = _legacy_response.to_raw_response_wrapper(
453
+ batches.retrieve,
454
+ )
455
+ self.list = _legacy_response.to_raw_response_wrapper(
456
+ batches.list,
457
+ )
458
+ self.cancel = _legacy_response.to_raw_response_wrapper(
459
+ batches.cancel,
460
+ )
461
+
462
+
463
+ class AsyncBatchesWithRawResponse:
464
+ def __init__(self, batches: AsyncBatches) -> None:
465
+ self._batches = batches
466
+
467
+ self.create = _legacy_response.async_to_raw_response_wrapper(
468
+ batches.create,
469
+ )
470
+ self.retrieve = _legacy_response.async_to_raw_response_wrapper(
471
+ batches.retrieve,
472
+ )
473
+ self.list = _legacy_response.async_to_raw_response_wrapper(
474
+ batches.list,
475
+ )
476
+ self.cancel = _legacy_response.async_to_raw_response_wrapper(
477
+ batches.cancel,
478
+ )
479
+
480
+
481
+ class BatchesWithStreamingResponse:
482
+ def __init__(self, batches: Batches) -> None:
483
+ self._batches = batches
484
+
485
+ self.create = to_streamed_response_wrapper(
486
+ batches.create,
487
+ )
488
+ self.retrieve = to_streamed_response_wrapper(
489
+ batches.retrieve,
490
+ )
491
+ self.list = to_streamed_response_wrapper(
492
+ batches.list,
493
+ )
494
+ self.cancel = to_streamed_response_wrapper(
495
+ batches.cancel,
496
+ )
497
+
498
+
499
+ class AsyncBatchesWithStreamingResponse:
500
+ def __init__(self, batches: AsyncBatches) -> None:
501
+ self._batches = batches
502
+
503
+ self.create = async_to_streamed_response_wrapper(
504
+ batches.create,
505
+ )
506
+ self.retrieve = async_to_streamed_response_wrapper(
507
+ batches.retrieve,
508
+ )
509
+ self.list = async_to_streamed_response_wrapper(
510
+ batches.list,
511
+ )
512
+ self.cancel = async_to_streamed_response_wrapper(
513
+ batches.cancel,
514
+ )
python_embeded/Lib/site-packages/openai/resources/completions.py ADDED
@@ -0,0 +1,1160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Dict, List, Union, Iterable, Optional
6
+ from typing_extensions import Literal, overload
7
+
8
+ import httpx
9
+
10
+ from .. import _legacy_response
11
+ from ..types import completion_create_params
12
+ from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven
13
+ from .._utils import required_args, maybe_transform, async_maybe_transform
14
+ from .._compat import cached_property
15
+ from .._resource import SyncAPIResource, AsyncAPIResource
16
+ from .._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper
17
+ from .._streaming import Stream, AsyncStream
18
+ from .._base_client import (
19
+ make_request_options,
20
+ )
21
+ from ..types.completion import Completion
22
+ from ..types.chat.chat_completion_stream_options_param import ChatCompletionStreamOptionsParam
23
+
24
+ __all__ = ["Completions", "AsyncCompletions"]
25
+
26
+
27
+ class Completions(SyncAPIResource):
28
+ @cached_property
29
+ def with_raw_response(self) -> CompletionsWithRawResponse:
30
+ """
31
+ This property can be used as a prefix for any HTTP method call to return
32
+ the raw response object instead of the parsed content.
33
+
34
+ For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
35
+ """
36
+ return CompletionsWithRawResponse(self)
37
+
38
+ @cached_property
39
+ def with_streaming_response(self) -> CompletionsWithStreamingResponse:
40
+ """
41
+ An alternative to `.with_raw_response` that doesn't eagerly read the response body.
42
+
43
+ For more information, see https://www.github.com/openai/openai-python#with_streaming_response
44
+ """
45
+ return CompletionsWithStreamingResponse(self)
46
+
47
+ @overload
48
+ def create(
49
+ self,
50
+ *,
51
+ model: Union[str, Literal["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"]],
52
+ prompt: Union[str, List[str], Iterable[int], Iterable[Iterable[int]], None],
53
+ best_of: Optional[int] | NotGiven = NOT_GIVEN,
54
+ echo: Optional[bool] | NotGiven = NOT_GIVEN,
55
+ frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN,
56
+ logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN,
57
+ logprobs: Optional[int] | NotGiven = NOT_GIVEN,
58
+ max_tokens: Optional[int] | NotGiven = NOT_GIVEN,
59
+ n: Optional[int] | NotGiven = NOT_GIVEN,
60
+ presence_penalty: Optional[float] | NotGiven = NOT_GIVEN,
61
+ seed: Optional[int] | NotGiven = NOT_GIVEN,
62
+ stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN,
63
+ stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN,
64
+ stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN,
65
+ suffix: Optional[str] | NotGiven = NOT_GIVEN,
66
+ temperature: Optional[float] | NotGiven = NOT_GIVEN,
67
+ top_p: Optional[float] | NotGiven = NOT_GIVEN,
68
+ user: str | NotGiven = NOT_GIVEN,
69
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
70
+ # The extra values given here take precedence over values defined on the client or passed to this method.
71
+ extra_headers: Headers | None = None,
72
+ extra_query: Query | None = None,
73
+ extra_body: Body | None = None,
74
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
75
+ ) -> Completion:
76
+ """
77
+ Creates a completion for the provided prompt and parameters.
78
+
79
+ Args:
80
+ model: ID of the model to use. You can use the
81
+ [List models](https://platform.openai.com/docs/api-reference/models/list) API to
82
+ see all of your available models, or see our
83
+ [Model overview](https://platform.openai.com/docs/models) for descriptions of
84
+ them.
85
+
86
+ prompt: The prompt(s) to generate completions for, encoded as a string, array of
87
+ strings, array of tokens, or array of token arrays.
88
+
89
+ Note that <|endoftext|> is the document separator that the model sees during
90
+ training, so if a prompt is not specified the model will generate as if from the
91
+ beginning of a new document.
92
+
93
+ best_of: Generates `best_of` completions server-side and returns the "best" (the one with
94
+ the highest log probability per token). Results cannot be streamed.
95
+
96
+ When used with `n`, `best_of` controls the number of candidate completions and
97
+ `n` specifies how many to return – `best_of` must be greater than `n`.
98
+
99
+ **Note:** Because this parameter generates many completions, it can quickly
100
+ consume your token quota. Use carefully and ensure that you have reasonable
101
+ settings for `max_tokens` and `stop`.
102
+
103
+ echo: Echo back the prompt in addition to the completion
104
+
105
+ frequency_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on their
106
+ existing frequency in the text so far, decreasing the model's likelihood to
107
+ repeat the same line verbatim.
108
+
109
+ [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation)
110
+
111
+ logit_bias: Modify the likelihood of specified tokens appearing in the completion.
112
+
113
+ Accepts a JSON object that maps tokens (specified by their token ID in the GPT
114
+ tokenizer) to an associated bias value from -100 to 100. You can use this
115
+ [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs.
116
+ Mathematically, the bias is added to the logits generated by the model prior to
117
+ sampling. The exact effect will vary per model, but values between -1 and 1
118
+ should decrease or increase likelihood of selection; values like -100 or 100
119
+ should result in a ban or exclusive selection of the relevant token.
120
+
121
+ As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token
122
+ from being generated.
123
+
124
+ logprobs: Include the log probabilities on the `logprobs` most likely output tokens, as
125
+ well the chosen tokens. For example, if `logprobs` is 5, the API will return a
126
+ list of the 5 most likely tokens. The API will always return the `logprob` of
127
+ the sampled token, so there may be up to `logprobs+1` elements in the response.
128
+
129
+ The maximum value for `logprobs` is 5.
130
+
131
+ max_tokens: The maximum number of [tokens](/tokenizer) that can be generated in the
132
+ completion.
133
+
134
+ The token count of your prompt plus `max_tokens` cannot exceed the model's
135
+ context length.
136
+ [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken)
137
+ for counting tokens.
138
+
139
+ n: How many completions to generate for each prompt.
140
+
141
+ **Note:** Because this parameter generates many completions, it can quickly
142
+ consume your token quota. Use carefully and ensure that you have reasonable
143
+ settings for `max_tokens` and `stop`.
144
+
145
+ presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on
146
+ whether they appear in the text so far, increasing the model's likelihood to
147
+ talk about new topics.
148
+
149
+ [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation)
150
+
151
+ seed: If specified, our system will make a best effort to sample deterministically,
152
+ such that repeated requests with the same `seed` and parameters should return
153
+ the same result.
154
+
155
+ Determinism is not guaranteed, and you should refer to the `system_fingerprint`
156
+ response parameter to monitor changes in the backend.
157
+
158
+ stop: Not supported with latest reasoning models `o3` and `o4-mini`.
159
+
160
+ Up to 4 sequences where the API will stop generating further tokens. The
161
+ returned text will not contain the stop sequence.
162
+
163
+ stream: Whether to stream back partial progress. If set, tokens will be sent as
164
+ data-only
165
+ [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format)
166
+ as they become available, with the stream terminated by a `data: [DONE]`
167
+ message.
168
+ [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions).
169
+
170
+ stream_options: Options for streaming response. Only set this when you set `stream: true`.
171
+
172
+ suffix: The suffix that comes after a completion of inserted text.
173
+
174
+ This parameter is only supported for `gpt-3.5-turbo-instruct`.
175
+
176
+ temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will
177
+ make the output more random, while lower values like 0.2 will make it more
178
+ focused and deterministic.
179
+
180
+ We generally recommend altering this or `top_p` but not both.
181
+
182
+ top_p: An alternative to sampling with temperature, called nucleus sampling, where the
183
+ model considers the results of the tokens with top_p probability mass. So 0.1
184
+ means only the tokens comprising the top 10% probability mass are considered.
185
+
186
+ We generally recommend altering this or `temperature` but not both.
187
+
188
+ user: A unique identifier representing your end-user, which can help OpenAI to monitor
189
+ and detect abuse.
190
+ [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).
191
+
192
+ extra_headers: Send extra headers
193
+
194
+ extra_query: Add additional query parameters to the request
195
+
196
+ extra_body: Add additional JSON properties to the request
197
+
198
+ timeout: Override the client-level default timeout for this request, in seconds
199
+ """
200
+ ...
201
+
202
+ @overload
203
+ def create(
204
+ self,
205
+ *,
206
+ model: Union[str, Literal["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"]],
207
+ prompt: Union[str, List[str], Iterable[int], Iterable[Iterable[int]], None],
208
+ stream: Literal[True],
209
+ best_of: Optional[int] | NotGiven = NOT_GIVEN,
210
+ echo: Optional[bool] | NotGiven = NOT_GIVEN,
211
+ frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN,
212
+ logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN,
213
+ logprobs: Optional[int] | NotGiven = NOT_GIVEN,
214
+ max_tokens: Optional[int] | NotGiven = NOT_GIVEN,
215
+ n: Optional[int] | NotGiven = NOT_GIVEN,
216
+ presence_penalty: Optional[float] | NotGiven = NOT_GIVEN,
217
+ seed: Optional[int] | NotGiven = NOT_GIVEN,
218
+ stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN,
219
+ stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN,
220
+ suffix: Optional[str] | NotGiven = NOT_GIVEN,
221
+ temperature: Optional[float] | NotGiven = NOT_GIVEN,
222
+ top_p: Optional[float] | NotGiven = NOT_GIVEN,
223
+ user: str | NotGiven = NOT_GIVEN,
224
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
225
+ # The extra values given here take precedence over values defined on the client or passed to this method.
226
+ extra_headers: Headers | None = None,
227
+ extra_query: Query | None = None,
228
+ extra_body: Body | None = None,
229
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
230
+ ) -> Stream[Completion]:
231
+ """
232
+ Creates a completion for the provided prompt and parameters.
233
+
234
+ Args:
235
+ model: ID of the model to use. You can use the
236
+ [List models](https://platform.openai.com/docs/api-reference/models/list) API to
237
+ see all of your available models, or see our
238
+ [Model overview](https://platform.openai.com/docs/models) for descriptions of
239
+ them.
240
+
241
+ prompt: The prompt(s) to generate completions for, encoded as a string, array of
242
+ strings, array of tokens, or array of token arrays.
243
+
244
+ Note that <|endoftext|> is the document separator that the model sees during
245
+ training, so if a prompt is not specified the model will generate as if from the
246
+ beginning of a new document.
247
+
248
+ stream: Whether to stream back partial progress. If set, tokens will be sent as
249
+ data-only
250
+ [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format)
251
+ as they become available, with the stream terminated by a `data: [DONE]`
252
+ message.
253
+ [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions).
254
+
255
+ best_of: Generates `best_of` completions server-side and returns the "best" (the one with
256
+ the highest log probability per token). Results cannot be streamed.
257
+
258
+ When used with `n`, `best_of` controls the number of candidate completions and
259
+ `n` specifies how many to return – `best_of` must be greater than `n`.
260
+
261
+ **Note:** Because this parameter generates many completions, it can quickly
262
+ consume your token quota. Use carefully and ensure that you have reasonable
263
+ settings for `max_tokens` and `stop`.
264
+
265
+ echo: Echo back the prompt in addition to the completion
266
+
267
+ frequency_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on their
268
+ existing frequency in the text so far, decreasing the model's likelihood to
269
+ repeat the same line verbatim.
270
+
271
+ [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation)
272
+
273
+ logit_bias: Modify the likelihood of specified tokens appearing in the completion.
274
+
275
+ Accepts a JSON object that maps tokens (specified by their token ID in the GPT
276
+ tokenizer) to an associated bias value from -100 to 100. You can use this
277
+ [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs.
278
+ Mathematically, the bias is added to the logits generated by the model prior to
279
+ sampling. The exact effect will vary per model, but values between -1 and 1
280
+ should decrease or increase likelihood of selection; values like -100 or 100
281
+ should result in a ban or exclusive selection of the relevant token.
282
+
283
+ As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token
284
+ from being generated.
285
+
286
+ logprobs: Include the log probabilities on the `logprobs` most likely output tokens, as
287
+ well the chosen tokens. For example, if `logprobs` is 5, the API will return a
288
+ list of the 5 most likely tokens. The API will always return the `logprob` of
289
+ the sampled token, so there may be up to `logprobs+1` elements in the response.
290
+
291
+ The maximum value for `logprobs` is 5.
292
+
293
+ max_tokens: The maximum number of [tokens](/tokenizer) that can be generated in the
294
+ completion.
295
+
296
+ The token count of your prompt plus `max_tokens` cannot exceed the model's
297
+ context length.
298
+ [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken)
299
+ for counting tokens.
300
+
301
+ n: How many completions to generate for each prompt.
302
+
303
+ **Note:** Because this parameter generates many completions, it can quickly
304
+ consume your token quota. Use carefully and ensure that you have reasonable
305
+ settings for `max_tokens` and `stop`.
306
+
307
+ presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on
308
+ whether they appear in the text so far, increasing the model's likelihood to
309
+ talk about new topics.
310
+
311
+ [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation)
312
+
313
+ seed: If specified, our system will make a best effort to sample deterministically,
314
+ such that repeated requests with the same `seed` and parameters should return
315
+ the same result.
316
+
317
+ Determinism is not guaranteed, and you should refer to the `system_fingerprint`
318
+ response parameter to monitor changes in the backend.
319
+
320
+ stop: Not supported with latest reasoning models `o3` and `o4-mini`.
321
+
322
+ Up to 4 sequences where the API will stop generating further tokens. The
323
+ returned text will not contain the stop sequence.
324
+
325
+ stream_options: Options for streaming response. Only set this when you set `stream: true`.
326
+
327
+ suffix: The suffix that comes after a completion of inserted text.
328
+
329
+ This parameter is only supported for `gpt-3.5-turbo-instruct`.
330
+
331
+ temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will
332
+ make the output more random, while lower values like 0.2 will make it more
333
+ focused and deterministic.
334
+
335
+ We generally recommend altering this or `top_p` but not both.
336
+
337
+ top_p: An alternative to sampling with temperature, called nucleus sampling, where the
338
+ model considers the results of the tokens with top_p probability mass. So 0.1
339
+ means only the tokens comprising the top 10% probability mass are considered.
340
+
341
+ We generally recommend altering this or `temperature` but not both.
342
+
343
+ user: A unique identifier representing your end-user, which can help OpenAI to monitor
344
+ and detect abuse.
345
+ [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).
346
+
347
+ extra_headers: Send extra headers
348
+
349
+ extra_query: Add additional query parameters to the request
350
+
351
+ extra_body: Add additional JSON properties to the request
352
+
353
+ timeout: Override the client-level default timeout for this request, in seconds
354
+ """
355
+ ...
356
+
357
+ @overload
358
+ def create(
359
+ self,
360
+ *,
361
+ model: Union[str, Literal["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"]],
362
+ prompt: Union[str, List[str], Iterable[int], Iterable[Iterable[int]], None],
363
+ stream: bool,
364
+ best_of: Optional[int] | NotGiven = NOT_GIVEN,
365
+ echo: Optional[bool] | NotGiven = NOT_GIVEN,
366
+ frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN,
367
+ logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN,
368
+ logprobs: Optional[int] | NotGiven = NOT_GIVEN,
369
+ max_tokens: Optional[int] | NotGiven = NOT_GIVEN,
370
+ n: Optional[int] | NotGiven = NOT_GIVEN,
371
+ presence_penalty: Optional[float] | NotGiven = NOT_GIVEN,
372
+ seed: Optional[int] | NotGiven = NOT_GIVEN,
373
+ stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN,
374
+ stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN,
375
+ suffix: Optional[str] | NotGiven = NOT_GIVEN,
376
+ temperature: Optional[float] | NotGiven = NOT_GIVEN,
377
+ top_p: Optional[float] | NotGiven = NOT_GIVEN,
378
+ user: str | NotGiven = NOT_GIVEN,
379
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
380
+ # The extra values given here take precedence over values defined on the client or passed to this method.
381
+ extra_headers: Headers | None = None,
382
+ extra_query: Query | None = None,
383
+ extra_body: Body | None = None,
384
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
385
+ ) -> Completion | Stream[Completion]:
386
+ """
387
+ Creates a completion for the provided prompt and parameters.
388
+
389
+ Args:
390
+ model: ID of the model to use. You can use the
391
+ [List models](https://platform.openai.com/docs/api-reference/models/list) API to
392
+ see all of your available models, or see our
393
+ [Model overview](https://platform.openai.com/docs/models) for descriptions of
394
+ them.
395
+
396
+ prompt: The prompt(s) to generate completions for, encoded as a string, array of
397
+ strings, array of tokens, or array of token arrays.
398
+
399
+ Note that <|endoftext|> is the document separator that the model sees during
400
+ training, so if a prompt is not specified the model will generate as if from the
401
+ beginning of a new document.
402
+
403
+ stream: Whether to stream back partial progress. If set, tokens will be sent as
404
+ data-only
405
+ [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format)
406
+ as they become available, with the stream terminated by a `data: [DONE]`
407
+ message.
408
+ [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions).
409
+
410
+ best_of: Generates `best_of` completions server-side and returns the "best" (the one with
411
+ the highest log probability per token). Results cannot be streamed.
412
+
413
+ When used with `n`, `best_of` controls the number of candidate completions and
414
+ `n` specifies how many to return – `best_of` must be greater than `n`.
415
+
416
+ **Note:** Because this parameter generates many completions, it can quickly
417
+ consume your token quota. Use carefully and ensure that you have reasonable
418
+ settings for `max_tokens` and `stop`.
419
+
420
+ echo: Echo back the prompt in addition to the completion
421
+
422
+ frequency_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on their
423
+ existing frequency in the text so far, decreasing the model's likelihood to
424
+ repeat the same line verbatim.
425
+
426
+ [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation)
427
+
428
+ logit_bias: Modify the likelihood of specified tokens appearing in the completion.
429
+
430
+ Accepts a JSON object that maps tokens (specified by their token ID in the GPT
431
+ tokenizer) to an associated bias value from -100 to 100. You can use this
432
+ [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs.
433
+ Mathematically, the bias is added to the logits generated by the model prior to
434
+ sampling. The exact effect will vary per model, but values between -1 and 1
435
+ should decrease or increase likelihood of selection; values like -100 or 100
436
+ should result in a ban or exclusive selection of the relevant token.
437
+
438
+ As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token
439
+ from being generated.
440
+
441
+ logprobs: Include the log probabilities on the `logprobs` most likely output tokens, as
442
+ well the chosen tokens. For example, if `logprobs` is 5, the API will return a
443
+ list of the 5 most likely tokens. The API will always return the `logprob` of
444
+ the sampled token, so there may be up to `logprobs+1` elements in the response.
445
+
446
+ The maximum value for `logprobs` is 5.
447
+
448
+ max_tokens: The maximum number of [tokens](/tokenizer) that can be generated in the
449
+ completion.
450
+
451
+ The token count of your prompt plus `max_tokens` cannot exceed the model's
452
+ context length.
453
+ [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken)
454
+ for counting tokens.
455
+
456
+ n: How many completions to generate for each prompt.
457
+
458
+ **Note:** Because this parameter generates many completions, it can quickly
459
+ consume your token quota. Use carefully and ensure that you have reasonable
460
+ settings for `max_tokens` and `stop`.
461
+
462
+ presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on
463
+ whether they appear in the text so far, increasing the model's likelihood to
464
+ talk about new topics.
465
+
466
+ [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation)
467
+
468
+ seed: If specified, our system will make a best effort to sample deterministically,
469
+ such that repeated requests with the same `seed` and parameters should return
470
+ the same result.
471
+
472
+ Determinism is not guaranteed, and you should refer to the `system_fingerprint`
473
+ response parameter to monitor changes in the backend.
474
+
475
+ stop: Not supported with latest reasoning models `o3` and `o4-mini`.
476
+
477
+ Up to 4 sequences where the API will stop generating further tokens. The
478
+ returned text will not contain the stop sequence.
479
+
480
+ stream_options: Options for streaming response. Only set this when you set `stream: true`.
481
+
482
+ suffix: The suffix that comes after a completion of inserted text.
483
+
484
+ This parameter is only supported for `gpt-3.5-turbo-instruct`.
485
+
486
+ temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will
487
+ make the output more random, while lower values like 0.2 will make it more
488
+ focused and deterministic.
489
+
490
+ We generally recommend altering this or `top_p` but not both.
491
+
492
+ top_p: An alternative to sampling with temperature, called nucleus sampling, where the
493
+ model considers the results of the tokens with top_p probability mass. So 0.1
494
+ means only the tokens comprising the top 10% probability mass are considered.
495
+
496
+ We generally recommend altering this or `temperature` but not both.
497
+
498
+ user: A unique identifier representing your end-user, which can help OpenAI to monitor
499
+ and detect abuse.
500
+ [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).
501
+
502
+ extra_headers: Send extra headers
503
+
504
+ extra_query: Add additional query parameters to the request
505
+
506
+ extra_body: Add additional JSON properties to the request
507
+
508
+ timeout: Override the client-level default timeout for this request, in seconds
509
+ """
510
+ ...
511
+
512
+ @required_args(["model", "prompt"], ["model", "prompt", "stream"])
513
+ def create(
514
+ self,
515
+ *,
516
+ model: Union[str, Literal["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"]],
517
+ prompt: Union[str, List[str], Iterable[int], Iterable[Iterable[int]], None],
518
+ best_of: Optional[int] | NotGiven = NOT_GIVEN,
519
+ echo: Optional[bool] | NotGiven = NOT_GIVEN,
520
+ frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN,
521
+ logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN,
522
+ logprobs: Optional[int] | NotGiven = NOT_GIVEN,
523
+ max_tokens: Optional[int] | NotGiven = NOT_GIVEN,
524
+ n: Optional[int] | NotGiven = NOT_GIVEN,
525
+ presence_penalty: Optional[float] | NotGiven = NOT_GIVEN,
526
+ seed: Optional[int] | NotGiven = NOT_GIVEN,
527
+ stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN,
528
+ stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN,
529
+ stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN,
530
+ suffix: Optional[str] | NotGiven = NOT_GIVEN,
531
+ temperature: Optional[float] | NotGiven = NOT_GIVEN,
532
+ top_p: Optional[float] | NotGiven = NOT_GIVEN,
533
+ user: str | NotGiven = NOT_GIVEN,
534
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
535
+ # The extra values given here take precedence over values defined on the client or passed to this method.
536
+ extra_headers: Headers | None = None,
537
+ extra_query: Query | None = None,
538
+ extra_body: Body | None = None,
539
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
540
+ ) -> Completion | Stream[Completion]:
541
+ return self._post(
542
+ "/completions",
543
+ body=maybe_transform(
544
+ {
545
+ "model": model,
546
+ "prompt": prompt,
547
+ "best_of": best_of,
548
+ "echo": echo,
549
+ "frequency_penalty": frequency_penalty,
550
+ "logit_bias": logit_bias,
551
+ "logprobs": logprobs,
552
+ "max_tokens": max_tokens,
553
+ "n": n,
554
+ "presence_penalty": presence_penalty,
555
+ "seed": seed,
556
+ "stop": stop,
557
+ "stream": stream,
558
+ "stream_options": stream_options,
559
+ "suffix": suffix,
560
+ "temperature": temperature,
561
+ "top_p": top_p,
562
+ "user": user,
563
+ },
564
+ completion_create_params.CompletionCreateParamsStreaming
565
+ if stream
566
+ else completion_create_params.CompletionCreateParamsNonStreaming,
567
+ ),
568
+ options=make_request_options(
569
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
570
+ ),
571
+ cast_to=Completion,
572
+ stream=stream or False,
573
+ stream_cls=Stream[Completion],
574
+ )
575
+
576
+
577
+ class AsyncCompletions(AsyncAPIResource):
578
+ @cached_property
579
+ def with_raw_response(self) -> AsyncCompletionsWithRawResponse:
580
+ """
581
+ This property can be used as a prefix for any HTTP method call to return
582
+ the raw response object instead of the parsed content.
583
+
584
+ For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
585
+ """
586
+ return AsyncCompletionsWithRawResponse(self)
587
+
588
+ @cached_property
589
+ def with_streaming_response(self) -> AsyncCompletionsWithStreamingResponse:
590
+ """
591
+ An alternative to `.with_raw_response` that doesn't eagerly read the response body.
592
+
593
+ For more information, see https://www.github.com/openai/openai-python#with_streaming_response
594
+ """
595
+ return AsyncCompletionsWithStreamingResponse(self)
596
+
597
+ @overload
598
+ async def create(
599
+ self,
600
+ *,
601
+ model: Union[str, Literal["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"]],
602
+ prompt: Union[str, List[str], Iterable[int], Iterable[Iterable[int]], None],
603
+ best_of: Optional[int] | NotGiven = NOT_GIVEN,
604
+ echo: Optional[bool] | NotGiven = NOT_GIVEN,
605
+ frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN,
606
+ logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN,
607
+ logprobs: Optional[int] | NotGiven = NOT_GIVEN,
608
+ max_tokens: Optional[int] | NotGiven = NOT_GIVEN,
609
+ n: Optional[int] | NotGiven = NOT_GIVEN,
610
+ presence_penalty: Optional[float] | NotGiven = NOT_GIVEN,
611
+ seed: Optional[int] | NotGiven = NOT_GIVEN,
612
+ stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN,
613
+ stream: Optional[Literal[False]] | NotGiven = NOT_GIVEN,
614
+ stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN,
615
+ suffix: Optional[str] | NotGiven = NOT_GIVEN,
616
+ temperature: Optional[float] | NotGiven = NOT_GIVEN,
617
+ top_p: Optional[float] | NotGiven = NOT_GIVEN,
618
+ user: str | NotGiven = NOT_GIVEN,
619
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
620
+ # The extra values given here take precedence over values defined on the client or passed to this method.
621
+ extra_headers: Headers | None = None,
622
+ extra_query: Query | None = None,
623
+ extra_body: Body | None = None,
624
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
625
+ ) -> Completion:
626
+ """
627
+ Creates a completion for the provided prompt and parameters.
628
+
629
+ Args:
630
+ model: ID of the model to use. You can use the
631
+ [List models](https://platform.openai.com/docs/api-reference/models/list) API to
632
+ see all of your available models, or see our
633
+ [Model overview](https://platform.openai.com/docs/models) for descriptions of
634
+ them.
635
+
636
+ prompt: The prompt(s) to generate completions for, encoded as a string, array of
637
+ strings, array of tokens, or array of token arrays.
638
+
639
+ Note that <|endoftext|> is the document separator that the model sees during
640
+ training, so if a prompt is not specified the model will generate as if from the
641
+ beginning of a new document.
642
+
643
+ best_of: Generates `best_of` completions server-side and returns the "best" (the one with
644
+ the highest log probability per token). Results cannot be streamed.
645
+
646
+ When used with `n`, `best_of` controls the number of candidate completions and
647
+ `n` specifies how many to return – `best_of` must be greater than `n`.
648
+
649
+ **Note:** Because this parameter generates many completions, it can quickly
650
+ consume your token quota. Use carefully and ensure that you have reasonable
651
+ settings for `max_tokens` and `stop`.
652
+
653
+ echo: Echo back the prompt in addition to the completion
654
+
655
+ frequency_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on their
656
+ existing frequency in the text so far, decreasing the model's likelihood to
657
+ repeat the same line verbatim.
658
+
659
+ [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation)
660
+
661
+ logit_bias: Modify the likelihood of specified tokens appearing in the completion.
662
+
663
+ Accepts a JSON object that maps tokens (specified by their token ID in the GPT
664
+ tokenizer) to an associated bias value from -100 to 100. You can use this
665
+ [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs.
666
+ Mathematically, the bias is added to the logits generated by the model prior to
667
+ sampling. The exact effect will vary per model, but values between -1 and 1
668
+ should decrease or increase likelihood of selection; values like -100 or 100
669
+ should result in a ban or exclusive selection of the relevant token.
670
+
671
+ As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token
672
+ from being generated.
673
+
674
+ logprobs: Include the log probabilities on the `logprobs` most likely output tokens, as
675
+ well the chosen tokens. For example, if `logprobs` is 5, the API will return a
676
+ list of the 5 most likely tokens. The API will always return the `logprob` of
677
+ the sampled token, so there may be up to `logprobs+1` elements in the response.
678
+
679
+ The maximum value for `logprobs` is 5.
680
+
681
+ max_tokens: The maximum number of [tokens](/tokenizer) that can be generated in the
682
+ completion.
683
+
684
+ The token count of your prompt plus `max_tokens` cannot exceed the model's
685
+ context length.
686
+ [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken)
687
+ for counting tokens.
688
+
689
+ n: How many completions to generate for each prompt.
690
+
691
+ **Note:** Because this parameter generates many completions, it can quickly
692
+ consume your token quota. Use carefully and ensure that you have reasonable
693
+ settings for `max_tokens` and `stop`.
694
+
695
+ presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on
696
+ whether they appear in the text so far, increasing the model's likelihood to
697
+ talk about new topics.
698
+
699
+ [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation)
700
+
701
+ seed: If specified, our system will make a best effort to sample deterministically,
702
+ such that repeated requests with the same `seed` and parameters should return
703
+ the same result.
704
+
705
+ Determinism is not guaranteed, and you should refer to the `system_fingerprint`
706
+ response parameter to monitor changes in the backend.
707
+
708
+ stop: Not supported with latest reasoning models `o3` and `o4-mini`.
709
+
710
+ Up to 4 sequences where the API will stop generating further tokens. The
711
+ returned text will not contain the stop sequence.
712
+
713
+ stream: Whether to stream back partial progress. If set, tokens will be sent as
714
+ data-only
715
+ [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format)
716
+ as they become available, with the stream terminated by a `data: [DONE]`
717
+ message.
718
+ [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions).
719
+
720
+ stream_options: Options for streaming response. Only set this when you set `stream: true`.
721
+
722
+ suffix: The suffix that comes after a completion of inserted text.
723
+
724
+ This parameter is only supported for `gpt-3.5-turbo-instruct`.
725
+
726
+ temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will
727
+ make the output more random, while lower values like 0.2 will make it more
728
+ focused and deterministic.
729
+
730
+ We generally recommend altering this or `top_p` but not both.
731
+
732
+ top_p: An alternative to sampling with temperature, called nucleus sampling, where the
733
+ model considers the results of the tokens with top_p probability mass. So 0.1
734
+ means only the tokens comprising the top 10% probability mass are considered.
735
+
736
+ We generally recommend altering this or `temperature` but not both.
737
+
738
+ user: A unique identifier representing your end-user, which can help OpenAI to monitor
739
+ and detect abuse.
740
+ [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).
741
+
742
+ extra_headers: Send extra headers
743
+
744
+ extra_query: Add additional query parameters to the request
745
+
746
+ extra_body: Add additional JSON properties to the request
747
+
748
+ timeout: Override the client-level default timeout for this request, in seconds
749
+ """
750
+ ...
751
+
752
+ @overload
753
+ async def create(
754
+ self,
755
+ *,
756
+ model: Union[str, Literal["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"]],
757
+ prompt: Union[str, List[str], Iterable[int], Iterable[Iterable[int]], None],
758
+ stream: Literal[True],
759
+ best_of: Optional[int] | NotGiven = NOT_GIVEN,
760
+ echo: Optional[bool] | NotGiven = NOT_GIVEN,
761
+ frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN,
762
+ logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN,
763
+ logprobs: Optional[int] | NotGiven = NOT_GIVEN,
764
+ max_tokens: Optional[int] | NotGiven = NOT_GIVEN,
765
+ n: Optional[int] | NotGiven = NOT_GIVEN,
766
+ presence_penalty: Optional[float] | NotGiven = NOT_GIVEN,
767
+ seed: Optional[int] | NotGiven = NOT_GIVEN,
768
+ stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN,
769
+ stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN,
770
+ suffix: Optional[str] | NotGiven = NOT_GIVEN,
771
+ temperature: Optional[float] | NotGiven = NOT_GIVEN,
772
+ top_p: Optional[float] | NotGiven = NOT_GIVEN,
773
+ user: str | NotGiven = NOT_GIVEN,
774
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
775
+ # The extra values given here take precedence over values defined on the client or passed to this method.
776
+ extra_headers: Headers | None = None,
777
+ extra_query: Query | None = None,
778
+ extra_body: Body | None = None,
779
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
780
+ ) -> AsyncStream[Completion]:
781
+ """
782
+ Creates a completion for the provided prompt and parameters.
783
+
784
+ Args:
785
+ model: ID of the model to use. You can use the
786
+ [List models](https://platform.openai.com/docs/api-reference/models/list) API to
787
+ see all of your available models, or see our
788
+ [Model overview](https://platform.openai.com/docs/models) for descriptions of
789
+ them.
790
+
791
+ prompt: The prompt(s) to generate completions for, encoded as a string, array of
792
+ strings, array of tokens, or array of token arrays.
793
+
794
+ Note that <|endoftext|> is the document separator that the model sees during
795
+ training, so if a prompt is not specified the model will generate as if from the
796
+ beginning of a new document.
797
+
798
+ stream: Whether to stream back partial progress. If set, tokens will be sent as
799
+ data-only
800
+ [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format)
801
+ as they become available, with the stream terminated by a `data: [DONE]`
802
+ message.
803
+ [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions).
804
+
805
+ best_of: Generates `best_of` completions server-side and returns the "best" (the one with
806
+ the highest log probability per token). Results cannot be streamed.
807
+
808
+ When used with `n`, `best_of` controls the number of candidate completions and
809
+ `n` specifies how many to return – `best_of` must be greater than `n`.
810
+
811
+ **Note:** Because this parameter generates many completions, it can quickly
812
+ consume your token quota. Use carefully and ensure that you have reasonable
813
+ settings for `max_tokens` and `stop`.
814
+
815
+ echo: Echo back the prompt in addition to the completion
816
+
817
+ frequency_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on their
818
+ existing frequency in the text so far, decreasing the model's likelihood to
819
+ repeat the same line verbatim.
820
+
821
+ [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation)
822
+
823
+ logit_bias: Modify the likelihood of specified tokens appearing in the completion.
824
+
825
+ Accepts a JSON object that maps tokens (specified by their token ID in the GPT
826
+ tokenizer) to an associated bias value from -100 to 100. You can use this
827
+ [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs.
828
+ Mathematically, the bias is added to the logits generated by the model prior to
829
+ sampling. The exact effect will vary per model, but values between -1 and 1
830
+ should decrease or increase likelihood of selection; values like -100 or 100
831
+ should result in a ban or exclusive selection of the relevant token.
832
+
833
+ As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token
834
+ from being generated.
835
+
836
+ logprobs: Include the log probabilities on the `logprobs` most likely output tokens, as
837
+ well the chosen tokens. For example, if `logprobs` is 5, the API will return a
838
+ list of the 5 most likely tokens. The API will always return the `logprob` of
839
+ the sampled token, so there may be up to `logprobs+1` elements in the response.
840
+
841
+ The maximum value for `logprobs` is 5.
842
+
843
+ max_tokens: The maximum number of [tokens](/tokenizer) that can be generated in the
844
+ completion.
845
+
846
+ The token count of your prompt plus `max_tokens` cannot exceed the model's
847
+ context length.
848
+ [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken)
849
+ for counting tokens.
850
+
851
+ n: How many completions to generate for each prompt.
852
+
853
+ **Note:** Because this parameter generates many completions, it can quickly
854
+ consume your token quota. Use carefully and ensure that you have reasonable
855
+ settings for `max_tokens` and `stop`.
856
+
857
+ presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on
858
+ whether they appear in the text so far, increasing the model's likelihood to
859
+ talk about new topics.
860
+
861
+ [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation)
862
+
863
+ seed: If specified, our system will make a best effort to sample deterministically,
864
+ such that repeated requests with the same `seed` and parameters should return
865
+ the same result.
866
+
867
+ Determinism is not guaranteed, and you should refer to the `system_fingerprint`
868
+ response parameter to monitor changes in the backend.
869
+
870
+ stop: Not supported with latest reasoning models `o3` and `o4-mini`.
871
+
872
+ Up to 4 sequences where the API will stop generating further tokens. The
873
+ returned text will not contain the stop sequence.
874
+
875
+ stream_options: Options for streaming response. Only set this when you set `stream: true`.
876
+
877
+ suffix: The suffix that comes after a completion of inserted text.
878
+
879
+ This parameter is only supported for `gpt-3.5-turbo-instruct`.
880
+
881
+ temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will
882
+ make the output more random, while lower values like 0.2 will make it more
883
+ focused and deterministic.
884
+
885
+ We generally recommend altering this or `top_p` but not both.
886
+
887
+ top_p: An alternative to sampling with temperature, called nucleus sampling, where the
888
+ model considers the results of the tokens with top_p probability mass. So 0.1
889
+ means only the tokens comprising the top 10% probability mass are considered.
890
+
891
+ We generally recommend altering this or `temperature` but not both.
892
+
893
+ user: A unique identifier representing your end-user, which can help OpenAI to monitor
894
+ and detect abuse.
895
+ [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).
896
+
897
+ extra_headers: Send extra headers
898
+
899
+ extra_query: Add additional query parameters to the request
900
+
901
+ extra_body: Add additional JSON properties to the request
902
+
903
+ timeout: Override the client-level default timeout for this request, in seconds
904
+ """
905
+ ...
906
+
907
+ @overload
908
+ async def create(
909
+ self,
910
+ *,
911
+ model: Union[str, Literal["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"]],
912
+ prompt: Union[str, List[str], Iterable[int], Iterable[Iterable[int]], None],
913
+ stream: bool,
914
+ best_of: Optional[int] | NotGiven = NOT_GIVEN,
915
+ echo: Optional[bool] | NotGiven = NOT_GIVEN,
916
+ frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN,
917
+ logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN,
918
+ logprobs: Optional[int] | NotGiven = NOT_GIVEN,
919
+ max_tokens: Optional[int] | NotGiven = NOT_GIVEN,
920
+ n: Optional[int] | NotGiven = NOT_GIVEN,
921
+ presence_penalty: Optional[float] | NotGiven = NOT_GIVEN,
922
+ seed: Optional[int] | NotGiven = NOT_GIVEN,
923
+ stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN,
924
+ stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN,
925
+ suffix: Optional[str] | NotGiven = NOT_GIVEN,
926
+ temperature: Optional[float] | NotGiven = NOT_GIVEN,
927
+ top_p: Optional[float] | NotGiven = NOT_GIVEN,
928
+ user: str | NotGiven = NOT_GIVEN,
929
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
930
+ # The extra values given here take precedence over values defined on the client or passed to this method.
931
+ extra_headers: Headers | None = None,
932
+ extra_query: Query | None = None,
933
+ extra_body: Body | None = None,
934
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
935
+ ) -> Completion | AsyncStream[Completion]:
936
+ """
937
+ Creates a completion for the provided prompt and parameters.
938
+
939
+ Args:
940
+ model: ID of the model to use. You can use the
941
+ [List models](https://platform.openai.com/docs/api-reference/models/list) API to
942
+ see all of your available models, or see our
943
+ [Model overview](https://platform.openai.com/docs/models) for descriptions of
944
+ them.
945
+
946
+ prompt: The prompt(s) to generate completions for, encoded as a string, array of
947
+ strings, array of tokens, or array of token arrays.
948
+
949
+ Note that <|endoftext|> is the document separator that the model sees during
950
+ training, so if a prompt is not specified the model will generate as if from the
951
+ beginning of a new document.
952
+
953
+ stream: Whether to stream back partial progress. If set, tokens will be sent as
954
+ data-only
955
+ [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format)
956
+ as they become available, with the stream terminated by a `data: [DONE]`
957
+ message.
958
+ [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions).
959
+
960
+ best_of: Generates `best_of` completions server-side and returns the "best" (the one with
961
+ the highest log probability per token). Results cannot be streamed.
962
+
963
+ When used with `n`, `best_of` controls the number of candidate completions and
964
+ `n` specifies how many to return – `best_of` must be greater than `n`.
965
+
966
+ **Note:** Because this parameter generates many completions, it can quickly
967
+ consume your token quota. Use carefully and ensure that you have reasonable
968
+ settings for `max_tokens` and `stop`.
969
+
970
+ echo: Echo back the prompt in addition to the completion
971
+
972
+ frequency_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on their
973
+ existing frequency in the text so far, decreasing the model's likelihood to
974
+ repeat the same line verbatim.
975
+
976
+ [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation)
977
+
978
+ logit_bias: Modify the likelihood of specified tokens appearing in the completion.
979
+
980
+ Accepts a JSON object that maps tokens (specified by their token ID in the GPT
981
+ tokenizer) to an associated bias value from -100 to 100. You can use this
982
+ [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs.
983
+ Mathematically, the bias is added to the logits generated by the model prior to
984
+ sampling. The exact effect will vary per model, but values between -1 and 1
985
+ should decrease or increase likelihood of selection; values like -100 or 100
986
+ should result in a ban or exclusive selection of the relevant token.
987
+
988
+ As an example, you can pass `{"50256": -100}` to prevent the <|endoftext|> token
989
+ from being generated.
990
+
991
+ logprobs: Include the log probabilities on the `logprobs` most likely output tokens, as
992
+ well the chosen tokens. For example, if `logprobs` is 5, the API will return a
993
+ list of the 5 most likely tokens. The API will always return the `logprob` of
994
+ the sampled token, so there may be up to `logprobs+1` elements in the response.
995
+
996
+ The maximum value for `logprobs` is 5.
997
+
998
+ max_tokens: The maximum number of [tokens](/tokenizer) that can be generated in the
999
+ completion.
1000
+
1001
+ The token count of your prompt plus `max_tokens` cannot exceed the model's
1002
+ context length.
1003
+ [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken)
1004
+ for counting tokens.
1005
+
1006
+ n: How many completions to generate for each prompt.
1007
+
1008
+ **Note:** Because this parameter generates many completions, it can quickly
1009
+ consume your token quota. Use carefully and ensure that you have reasonable
1010
+ settings for `max_tokens` and `stop`.
1011
+
1012
+ presence_penalty: Number between -2.0 and 2.0. Positive values penalize new tokens based on
1013
+ whether they appear in the text so far, increasing the model's likelihood to
1014
+ talk about new topics.
1015
+
1016
+ [See more information about frequency and presence penalties.](https://platform.openai.com/docs/guides/text-generation)
1017
+
1018
+ seed: If specified, our system will make a best effort to sample deterministically,
1019
+ such that repeated requests with the same `seed` and parameters should return
1020
+ the same result.
1021
+
1022
+ Determinism is not guaranteed, and you should refer to the `system_fingerprint`
1023
+ response parameter to monitor changes in the backend.
1024
+
1025
+ stop: Not supported with latest reasoning models `o3` and `o4-mini`.
1026
+
1027
+ Up to 4 sequences where the API will stop generating further tokens. The
1028
+ returned text will not contain the stop sequence.
1029
+
1030
+ stream_options: Options for streaming response. Only set this when you set `stream: true`.
1031
+
1032
+ suffix: The suffix that comes after a completion of inserted text.
1033
+
1034
+ This parameter is only supported for `gpt-3.5-turbo-instruct`.
1035
+
1036
+ temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will
1037
+ make the output more random, while lower values like 0.2 will make it more
1038
+ focused and deterministic.
1039
+
1040
+ We generally recommend altering this or `top_p` but not both.
1041
+
1042
+ top_p: An alternative to sampling with temperature, called nucleus sampling, where the
1043
+ model considers the results of the tokens with top_p probability mass. So 0.1
1044
+ means only the tokens comprising the top 10% probability mass are considered.
1045
+
1046
+ We generally recommend altering this or `temperature` but not both.
1047
+
1048
+ user: A unique identifier representing your end-user, which can help OpenAI to monitor
1049
+ and detect abuse.
1050
+ [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).
1051
+
1052
+ extra_headers: Send extra headers
1053
+
1054
+ extra_query: Add additional query parameters to the request
1055
+
1056
+ extra_body: Add additional JSON properties to the request
1057
+
1058
+ timeout: Override the client-level default timeout for this request, in seconds
1059
+ """
1060
+ ...
1061
+
1062
+ @required_args(["model", "prompt"], ["model", "prompt", "stream"])
1063
+ async def create(
1064
+ self,
1065
+ *,
1066
+ model: Union[str, Literal["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"]],
1067
+ prompt: Union[str, List[str], Iterable[int], Iterable[Iterable[int]], None],
1068
+ best_of: Optional[int] | NotGiven = NOT_GIVEN,
1069
+ echo: Optional[bool] | NotGiven = NOT_GIVEN,
1070
+ frequency_penalty: Optional[float] | NotGiven = NOT_GIVEN,
1071
+ logit_bias: Optional[Dict[str, int]] | NotGiven = NOT_GIVEN,
1072
+ logprobs: Optional[int] | NotGiven = NOT_GIVEN,
1073
+ max_tokens: Optional[int] | NotGiven = NOT_GIVEN,
1074
+ n: Optional[int] | NotGiven = NOT_GIVEN,
1075
+ presence_penalty: Optional[float] | NotGiven = NOT_GIVEN,
1076
+ seed: Optional[int] | NotGiven = NOT_GIVEN,
1077
+ stop: Union[Optional[str], List[str], None] | NotGiven = NOT_GIVEN,
1078
+ stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN,
1079
+ stream_options: Optional[ChatCompletionStreamOptionsParam] | NotGiven = NOT_GIVEN,
1080
+ suffix: Optional[str] | NotGiven = NOT_GIVEN,
1081
+ temperature: Optional[float] | NotGiven = NOT_GIVEN,
1082
+ top_p: Optional[float] | NotGiven = NOT_GIVEN,
1083
+ user: str | NotGiven = NOT_GIVEN,
1084
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
1085
+ # The extra values given here take precedence over values defined on the client or passed to this method.
1086
+ extra_headers: Headers | None = None,
1087
+ extra_query: Query | None = None,
1088
+ extra_body: Body | None = None,
1089
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
1090
+ ) -> Completion | AsyncStream[Completion]:
1091
+ return await self._post(
1092
+ "/completions",
1093
+ body=await async_maybe_transform(
1094
+ {
1095
+ "model": model,
1096
+ "prompt": prompt,
1097
+ "best_of": best_of,
1098
+ "echo": echo,
1099
+ "frequency_penalty": frequency_penalty,
1100
+ "logit_bias": logit_bias,
1101
+ "logprobs": logprobs,
1102
+ "max_tokens": max_tokens,
1103
+ "n": n,
1104
+ "presence_penalty": presence_penalty,
1105
+ "seed": seed,
1106
+ "stop": stop,
1107
+ "stream": stream,
1108
+ "stream_options": stream_options,
1109
+ "suffix": suffix,
1110
+ "temperature": temperature,
1111
+ "top_p": top_p,
1112
+ "user": user,
1113
+ },
1114
+ completion_create_params.CompletionCreateParamsStreaming
1115
+ if stream
1116
+ else completion_create_params.CompletionCreateParamsNonStreaming,
1117
+ ),
1118
+ options=make_request_options(
1119
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
1120
+ ),
1121
+ cast_to=Completion,
1122
+ stream=stream or False,
1123
+ stream_cls=AsyncStream[Completion],
1124
+ )
1125
+
1126
+
1127
+ class CompletionsWithRawResponse:
1128
+ def __init__(self, completions: Completions) -> None:
1129
+ self._completions = completions
1130
+
1131
+ self.create = _legacy_response.to_raw_response_wrapper(
1132
+ completions.create,
1133
+ )
1134
+
1135
+
1136
+ class AsyncCompletionsWithRawResponse:
1137
+ def __init__(self, completions: AsyncCompletions) -> None:
1138
+ self._completions = completions
1139
+
1140
+ self.create = _legacy_response.async_to_raw_response_wrapper(
1141
+ completions.create,
1142
+ )
1143
+
1144
+
1145
+ class CompletionsWithStreamingResponse:
1146
+ def __init__(self, completions: Completions) -> None:
1147
+ self._completions = completions
1148
+
1149
+ self.create = to_streamed_response_wrapper(
1150
+ completions.create,
1151
+ )
1152
+
1153
+
1154
+ class AsyncCompletionsWithStreamingResponse:
1155
+ def __init__(self, completions: AsyncCompletions) -> None:
1156
+ self._completions = completions
1157
+
1158
+ self.create = async_to_streamed_response_wrapper(
1159
+ completions.create,
1160
+ )
python_embeded/Lib/site-packages/openai/resources/embeddings.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from __future__ import annotations
4
+
5
+ import array
6
+ import base64
7
+ from typing import List, Union, Iterable, cast
8
+ from typing_extensions import Literal
9
+
10
+ import httpx
11
+
12
+ from .. import _legacy_response
13
+ from ..types import embedding_create_params
14
+ from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven
15
+ from .._utils import is_given, maybe_transform
16
+ from .._compat import cached_property
17
+ from .._extras import numpy as np, has_numpy
18
+ from .._resource import SyncAPIResource, AsyncAPIResource
19
+ from .._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper
20
+ from .._base_client import make_request_options
21
+ from ..types.embedding_model import EmbeddingModel
22
+ from ..types.create_embedding_response import CreateEmbeddingResponse
23
+
24
+ __all__ = ["Embeddings", "AsyncEmbeddings"]
25
+
26
+
27
+ class Embeddings(SyncAPIResource):
28
+ @cached_property
29
+ def with_raw_response(self) -> EmbeddingsWithRawResponse:
30
+ """
31
+ This property can be used as a prefix for any HTTP method call to return
32
+ the raw response object instead of the parsed content.
33
+
34
+ For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
35
+ """
36
+ return EmbeddingsWithRawResponse(self)
37
+
38
+ @cached_property
39
+ def with_streaming_response(self) -> EmbeddingsWithStreamingResponse:
40
+ """
41
+ An alternative to `.with_raw_response` that doesn't eagerly read the response body.
42
+
43
+ For more information, see https://www.github.com/openai/openai-python#with_streaming_response
44
+ """
45
+ return EmbeddingsWithStreamingResponse(self)
46
+
47
+ def create(
48
+ self,
49
+ *,
50
+ input: Union[str, List[str], Iterable[int], Iterable[Iterable[int]]],
51
+ model: Union[str, EmbeddingModel],
52
+ dimensions: int | NotGiven = NOT_GIVEN,
53
+ encoding_format: Literal["float", "base64"] | NotGiven = NOT_GIVEN,
54
+ user: str | NotGiven = NOT_GIVEN,
55
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
56
+ # The extra values given here take precedence over values defined on the client or passed to this method.
57
+ extra_headers: Headers | None = None,
58
+ extra_query: Query | None = None,
59
+ extra_body: Body | None = None,
60
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
61
+ ) -> CreateEmbeddingResponse:
62
+ """
63
+ Creates an embedding vector representing the input text.
64
+
65
+ Args:
66
+ input: Input text to embed, encoded as a string or array of tokens. To embed multiple
67
+ inputs in a single request, pass an array of strings or array of token arrays.
68
+ The input must not exceed the max input tokens for the model (8192 tokens for
69
+ all embedding models), cannot be an empty string, and any array must be 2048
70
+ dimensions or less.
71
+ [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken)
72
+ for counting tokens. In addition to the per-input token limit, all embedding
73
+ models enforce a maximum of 300,000 tokens summed across all inputs in a single
74
+ request.
75
+
76
+ model: ID of the model to use. You can use the
77
+ [List models](https://platform.openai.com/docs/api-reference/models/list) API to
78
+ see all of your available models, or see our
79
+ [Model overview](https://platform.openai.com/docs/models) for descriptions of
80
+ them.
81
+
82
+ dimensions: The number of dimensions the resulting output embeddings should have. Only
83
+ supported in `text-embedding-3` and later models.
84
+
85
+ encoding_format: The format to return the embeddings in. Can be either `float` or
86
+ [`base64`](https://pypi.org/project/pybase64/).
87
+
88
+ user: A unique identifier representing your end-user, which can help OpenAI to monitor
89
+ and detect abuse.
90
+ [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).
91
+
92
+ extra_headers: Send extra headers
93
+
94
+ extra_query: Add additional query parameters to the request
95
+
96
+ extra_body: Add additional JSON properties to the request
97
+
98
+ timeout: Override the client-level default timeout for this request, in seconds
99
+ """
100
+ params = {
101
+ "input": input,
102
+ "model": model,
103
+ "user": user,
104
+ "dimensions": dimensions,
105
+ "encoding_format": encoding_format,
106
+ }
107
+ if not is_given(encoding_format):
108
+ params["encoding_format"] = "base64"
109
+
110
+ def parser(obj: CreateEmbeddingResponse) -> CreateEmbeddingResponse:
111
+ if is_given(encoding_format):
112
+ # don't modify the response object if a user explicitly asked for a format
113
+ return obj
114
+
115
+ for embedding in obj.data:
116
+ data = cast(object, embedding.embedding)
117
+ if not isinstance(data, str):
118
+ continue
119
+ if not has_numpy():
120
+ # use array for base64 optimisation
121
+ embedding.embedding = array.array("f", base64.b64decode(data)).tolist()
122
+ else:
123
+ embedding.embedding = np.frombuffer( # type: ignore[no-untyped-call]
124
+ base64.b64decode(data), dtype="float32"
125
+ ).tolist()
126
+
127
+ return obj
128
+
129
+ return self._post(
130
+ "/embeddings",
131
+ body=maybe_transform(params, embedding_create_params.EmbeddingCreateParams),
132
+ options=make_request_options(
133
+ extra_headers=extra_headers,
134
+ extra_query=extra_query,
135
+ extra_body=extra_body,
136
+ timeout=timeout,
137
+ post_parser=parser,
138
+ ),
139
+ cast_to=CreateEmbeddingResponse,
140
+ )
141
+
142
+
143
+ class AsyncEmbeddings(AsyncAPIResource):
144
+ @cached_property
145
+ def with_raw_response(self) -> AsyncEmbeddingsWithRawResponse:
146
+ """
147
+ This property can be used as a prefix for any HTTP method call to return
148
+ the raw response object instead of the parsed content.
149
+
150
+ For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
151
+ """
152
+ return AsyncEmbeddingsWithRawResponse(self)
153
+
154
+ @cached_property
155
+ def with_streaming_response(self) -> AsyncEmbeddingsWithStreamingResponse:
156
+ """
157
+ An alternative to `.with_raw_response` that doesn't eagerly read the response body.
158
+
159
+ For more information, see https://www.github.com/openai/openai-python#with_streaming_response
160
+ """
161
+ return AsyncEmbeddingsWithStreamingResponse(self)
162
+
163
+ async def create(
164
+ self,
165
+ *,
166
+ input: Union[str, List[str], Iterable[int], Iterable[Iterable[int]]],
167
+ model: Union[str, EmbeddingModel],
168
+ dimensions: int | NotGiven = NOT_GIVEN,
169
+ encoding_format: Literal["float", "base64"] | NotGiven = NOT_GIVEN,
170
+ user: str | NotGiven = NOT_GIVEN,
171
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
172
+ # The extra values given here take precedence over values defined on the client or passed to this method.
173
+ extra_headers: Headers | None = None,
174
+ extra_query: Query | None = None,
175
+ extra_body: Body | None = None,
176
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
177
+ ) -> CreateEmbeddingResponse:
178
+ """
179
+ Creates an embedding vector representing the input text.
180
+
181
+ Args:
182
+ input: Input text to embed, encoded as a string or array of tokens. To embed multiple
183
+ inputs in a single request, pass an array of strings or array of token arrays.
184
+ The input must not exceed the max input tokens for the model (8192 tokens for
185
+ all embedding models), cannot be an empty string, and any array must be 2048
186
+ dimensions or less.
187
+ [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken)
188
+ for counting tokens. In addition to the per-input token limit, all embedding
189
+ models enforce a maximum of 300,000 tokens summed across all inputs in a single
190
+ request.
191
+
192
+ model: ID of the model to use. You can use the
193
+ [List models](https://platform.openai.com/docs/api-reference/models/list) API to
194
+ see all of your available models, or see our
195
+ [Model overview](https://platform.openai.com/docs/models) for descriptions of
196
+ them.
197
+
198
+ dimensions: The number of dimensions the resulting output embeddings should have. Only
199
+ supported in `text-embedding-3` and later models.
200
+
201
+ encoding_format: The format to return the embeddings in. Can be either `float` or
202
+ [`base64`](https://pypi.org/project/pybase64/).
203
+
204
+ user: A unique identifier representing your end-user, which can help OpenAI to monitor
205
+ and detect abuse.
206
+ [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).
207
+
208
+ extra_headers: Send extra headers
209
+
210
+ extra_query: Add additional query parameters to the request
211
+
212
+ extra_body: Add additional JSON properties to the request
213
+
214
+ timeout: Override the client-level default timeout for this request, in seconds
215
+ """
216
+ params = {
217
+ "input": input,
218
+ "model": model,
219
+ "user": user,
220
+ "dimensions": dimensions,
221
+ "encoding_format": encoding_format,
222
+ }
223
+ if not is_given(encoding_format):
224
+ params["encoding_format"] = "base64"
225
+
226
+ def parser(obj: CreateEmbeddingResponse) -> CreateEmbeddingResponse:
227
+ if is_given(encoding_format):
228
+ # don't modify the response object if a user explicitly asked for a format
229
+ return obj
230
+
231
+ for embedding in obj.data:
232
+ data = cast(object, embedding.embedding)
233
+ if not isinstance(data, str):
234
+ continue
235
+ if not has_numpy():
236
+ # use array for base64 optimisation
237
+ embedding.embedding = array.array("f", base64.b64decode(data)).tolist()
238
+ else:
239
+ embedding.embedding = np.frombuffer( # type: ignore[no-untyped-call]
240
+ base64.b64decode(data), dtype="float32"
241
+ ).tolist()
242
+
243
+ return obj
244
+
245
+ return await self._post(
246
+ "/embeddings",
247
+ body=maybe_transform(params, embedding_create_params.EmbeddingCreateParams),
248
+ options=make_request_options(
249
+ extra_headers=extra_headers,
250
+ extra_query=extra_query,
251
+ extra_body=extra_body,
252
+ timeout=timeout,
253
+ post_parser=parser,
254
+ ),
255
+ cast_to=CreateEmbeddingResponse,
256
+ )
257
+
258
+
259
+ class EmbeddingsWithRawResponse:
260
+ def __init__(self, embeddings: Embeddings) -> None:
261
+ self._embeddings = embeddings
262
+
263
+ self.create = _legacy_response.to_raw_response_wrapper(
264
+ embeddings.create,
265
+ )
266
+
267
+
268
+ class AsyncEmbeddingsWithRawResponse:
269
+ def __init__(self, embeddings: AsyncEmbeddings) -> None:
270
+ self._embeddings = embeddings
271
+
272
+ self.create = _legacy_response.async_to_raw_response_wrapper(
273
+ embeddings.create,
274
+ )
275
+
276
+
277
+ class EmbeddingsWithStreamingResponse:
278
+ def __init__(self, embeddings: Embeddings) -> None:
279
+ self._embeddings = embeddings
280
+
281
+ self.create = to_streamed_response_wrapper(
282
+ embeddings.create,
283
+ )
284
+
285
+
286
+ class AsyncEmbeddingsWithStreamingResponse:
287
+ def __init__(self, embeddings: AsyncEmbeddings) -> None:
288
+ self._embeddings = embeddings
289
+
290
+ self.create = async_to_streamed_response_wrapper(
291
+ embeddings.create,
292
+ )
python_embeded/Lib/site-packages/openai/resources/files.py ADDED
@@ -0,0 +1,762 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ import typing_extensions
7
+ from typing import Mapping, cast
8
+ from typing_extensions import Literal
9
+
10
+ import httpx
11
+
12
+ from .. import _legacy_response
13
+ from ..types import FilePurpose, file_list_params, file_create_params
14
+ from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes
15
+ from .._utils import extract_files, maybe_transform, deepcopy_minimal, async_maybe_transform
16
+ from .._compat import cached_property
17
+ from .._resource import SyncAPIResource, AsyncAPIResource
18
+ from .._response import (
19
+ StreamedBinaryAPIResponse,
20
+ AsyncStreamedBinaryAPIResponse,
21
+ to_streamed_response_wrapper,
22
+ async_to_streamed_response_wrapper,
23
+ to_custom_streamed_response_wrapper,
24
+ async_to_custom_streamed_response_wrapper,
25
+ )
26
+ from ..pagination import SyncCursorPage, AsyncCursorPage
27
+ from .._base_client import AsyncPaginator, make_request_options
28
+ from ..types.file_object import FileObject
29
+ from ..types.file_deleted import FileDeleted
30
+ from ..types.file_purpose import FilePurpose
31
+
32
+ __all__ = ["Files", "AsyncFiles"]
33
+
34
+
35
+ class Files(SyncAPIResource):
36
+ @cached_property
37
+ def with_raw_response(self) -> FilesWithRawResponse:
38
+ """
39
+ This property can be used as a prefix for any HTTP method call to return
40
+ the raw response object instead of the parsed content.
41
+
42
+ For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
43
+ """
44
+ return FilesWithRawResponse(self)
45
+
46
+ @cached_property
47
+ def with_streaming_response(self) -> FilesWithStreamingResponse:
48
+ """
49
+ An alternative to `.with_raw_response` that doesn't eagerly read the response body.
50
+
51
+ For more information, see https://www.github.com/openai/openai-python#with_streaming_response
52
+ """
53
+ return FilesWithStreamingResponse(self)
54
+
55
+ def create(
56
+ self,
57
+ *,
58
+ file: FileTypes,
59
+ purpose: FilePurpose,
60
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
61
+ # The extra values given here take precedence over values defined on the client or passed to this method.
62
+ extra_headers: Headers | None = None,
63
+ extra_query: Query | None = None,
64
+ extra_body: Body | None = None,
65
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
66
+ ) -> FileObject:
67
+ """Upload a file that can be used across various endpoints.
68
+
69
+ Individual files can be
70
+ up to 512 MB, and the size of all files uploaded by one organization can be up
71
+ to 100 GB.
72
+
73
+ The Assistants API supports files up to 2 million tokens and of specific file
74
+ types. See the
75
+ [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for
76
+ details.
77
+
78
+ The Fine-tuning API only supports `.jsonl` files. The input also has certain
79
+ required formats for fine-tuning
80
+ [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or
81
+ [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input)
82
+ models.
83
+
84
+ The Batch API only supports `.jsonl` files up to 200 MB in size. The input also
85
+ has a specific required
86
+ [format](https://platform.openai.com/docs/api-reference/batch/request-input).
87
+
88
+ Please [contact us](https://help.openai.com/) if you need to increase these
89
+ storage limits.
90
+
91
+ Args:
92
+ file: The File object (not file name) to be uploaded.
93
+
94
+ purpose: The intended purpose of the uploaded file. One of: - `assistants`: Used in the
95
+ Assistants API - `batch`: Used in the Batch API - `fine-tune`: Used for
96
+ fine-tuning - `vision`: Images used for vision fine-tuning - `user_data`:
97
+ Flexible file type for any purpose - `evals`: Used for eval data sets
98
+
99
+ extra_headers: Send extra headers
100
+
101
+ extra_query: Add additional query parameters to the request
102
+
103
+ extra_body: Add additional JSON properties to the request
104
+
105
+ timeout: Override the client-level default timeout for this request, in seconds
106
+ """
107
+ body = deepcopy_minimal(
108
+ {
109
+ "file": file,
110
+ "purpose": purpose,
111
+ }
112
+ )
113
+ files = extract_files(cast(Mapping[str, object], body), paths=[["file"]])
114
+ # It should be noted that the actual Content-Type header that will be
115
+ # sent to the server will contain a `boundary` parameter, e.g.
116
+ # multipart/form-data; boundary=---abc--
117
+ extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})}
118
+ return self._post(
119
+ "/files",
120
+ body=maybe_transform(body, file_create_params.FileCreateParams),
121
+ files=files,
122
+ options=make_request_options(
123
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
124
+ ),
125
+ cast_to=FileObject,
126
+ )
127
+
128
+ def retrieve(
129
+ self,
130
+ file_id: str,
131
+ *,
132
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
133
+ # The extra values given here take precedence over values defined on the client or passed to this method.
134
+ extra_headers: Headers | None = None,
135
+ extra_query: Query | None = None,
136
+ extra_body: Body | None = None,
137
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
138
+ ) -> FileObject:
139
+ """
140
+ Returns information about a specific file.
141
+
142
+ Args:
143
+ extra_headers: Send extra headers
144
+
145
+ extra_query: Add additional query parameters to the request
146
+
147
+ extra_body: Add additional JSON properties to the request
148
+
149
+ timeout: Override the client-level default timeout for this request, in seconds
150
+ """
151
+ if not file_id:
152
+ raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}")
153
+ return self._get(
154
+ f"/files/{file_id}",
155
+ options=make_request_options(
156
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
157
+ ),
158
+ cast_to=FileObject,
159
+ )
160
+
161
+ def list(
162
+ self,
163
+ *,
164
+ after: str | NotGiven = NOT_GIVEN,
165
+ limit: int | NotGiven = NOT_GIVEN,
166
+ order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN,
167
+ purpose: str | NotGiven = NOT_GIVEN,
168
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
169
+ # The extra values given here take precedence over values defined on the client or passed to this method.
170
+ extra_headers: Headers | None = None,
171
+ extra_query: Query | None = None,
172
+ extra_body: Body | None = None,
173
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
174
+ ) -> SyncCursorPage[FileObject]:
175
+ """Returns a list of files.
176
+
177
+ Args:
178
+ after: A cursor for use in pagination.
179
+
180
+ `after` is an object ID that defines your place
181
+ in the list. For instance, if you make a list request and receive 100 objects,
182
+ ending with obj_foo, your subsequent call can include after=obj_foo in order to
183
+ fetch the next page of the list.
184
+
185
+ limit: A limit on the number of objects to be returned. Limit can range between 1 and
186
+ 10,000, and the default is 10,000.
187
+
188
+ order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending
189
+ order and `desc` for descending order.
190
+
191
+ purpose: Only return files with the given purpose.
192
+
193
+ extra_headers: Send extra headers
194
+
195
+ extra_query: Add additional query parameters to the request
196
+
197
+ extra_body: Add additional JSON properties to the request
198
+
199
+ timeout: Override the client-level default timeout for this request, in seconds
200
+ """
201
+ return self._get_api_list(
202
+ "/files",
203
+ page=SyncCursorPage[FileObject],
204
+ options=make_request_options(
205
+ extra_headers=extra_headers,
206
+ extra_query=extra_query,
207
+ extra_body=extra_body,
208
+ timeout=timeout,
209
+ query=maybe_transform(
210
+ {
211
+ "after": after,
212
+ "limit": limit,
213
+ "order": order,
214
+ "purpose": purpose,
215
+ },
216
+ file_list_params.FileListParams,
217
+ ),
218
+ ),
219
+ model=FileObject,
220
+ )
221
+
222
+ def delete(
223
+ self,
224
+ file_id: str,
225
+ *,
226
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
227
+ # The extra values given here take precedence over values defined on the client or passed to this method.
228
+ extra_headers: Headers | None = None,
229
+ extra_query: Query | None = None,
230
+ extra_body: Body | None = None,
231
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
232
+ ) -> FileDeleted:
233
+ """
234
+ Delete a file.
235
+
236
+ Args:
237
+ extra_headers: Send extra headers
238
+
239
+ extra_query: Add additional query parameters to the request
240
+
241
+ extra_body: Add additional JSON properties to the request
242
+
243
+ timeout: Override the client-level default timeout for this request, in seconds
244
+ """
245
+ if not file_id:
246
+ raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}")
247
+ return self._delete(
248
+ f"/files/{file_id}",
249
+ options=make_request_options(
250
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
251
+ ),
252
+ cast_to=FileDeleted,
253
+ )
254
+
255
+ def content(
256
+ self,
257
+ file_id: str,
258
+ *,
259
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
260
+ # The extra values given here take precedence over values defined on the client or passed to this method.
261
+ extra_headers: Headers | None = None,
262
+ extra_query: Query | None = None,
263
+ extra_body: Body | None = None,
264
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
265
+ ) -> _legacy_response.HttpxBinaryResponseContent:
266
+ """
267
+ Returns the contents of the specified file.
268
+
269
+ Args:
270
+ extra_headers: Send extra headers
271
+
272
+ extra_query: Add additional query parameters to the request
273
+
274
+ extra_body: Add additional JSON properties to the request
275
+
276
+ timeout: Override the client-level default timeout for this request, in seconds
277
+ """
278
+ if not file_id:
279
+ raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}")
280
+ extra_headers = {"Accept": "application/binary", **(extra_headers or {})}
281
+ return self._get(
282
+ f"/files/{file_id}/content",
283
+ options=make_request_options(
284
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
285
+ ),
286
+ cast_to=_legacy_response.HttpxBinaryResponseContent,
287
+ )
288
+
289
+ @typing_extensions.deprecated("The `.content()` method should be used instead")
290
+ def retrieve_content(
291
+ self,
292
+ file_id: str,
293
+ *,
294
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
295
+ # The extra values given here take precedence over values defined on the client or passed to this method.
296
+ extra_headers: Headers | None = None,
297
+ extra_query: Query | None = None,
298
+ extra_body: Body | None = None,
299
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
300
+ ) -> str:
301
+ """
302
+ Returns the contents of the specified file.
303
+
304
+ Args:
305
+ extra_headers: Send extra headers
306
+
307
+ extra_query: Add additional query parameters to the request
308
+
309
+ extra_body: Add additional JSON properties to the request
310
+
311
+ timeout: Override the client-level default timeout for this request, in seconds
312
+ """
313
+ if not file_id:
314
+ raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}")
315
+ return self._get(
316
+ f"/files/{file_id}/content",
317
+ options=make_request_options(
318
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
319
+ ),
320
+ cast_to=str,
321
+ )
322
+
323
+ def wait_for_processing(
324
+ self,
325
+ id: str,
326
+ *,
327
+ poll_interval: float = 5.0,
328
+ max_wait_seconds: float = 30 * 60,
329
+ ) -> FileObject:
330
+ """Waits for the given file to be processed, default timeout is 30 mins."""
331
+ TERMINAL_STATES = {"processed", "error", "deleted"}
332
+
333
+ start = time.time()
334
+ file = self.retrieve(id)
335
+ while file.status not in TERMINAL_STATES:
336
+ self._sleep(poll_interval)
337
+
338
+ file = self.retrieve(id)
339
+ if time.time() - start > max_wait_seconds:
340
+ raise RuntimeError(
341
+ f"Giving up on waiting for file {id} to finish processing after {max_wait_seconds} seconds."
342
+ )
343
+
344
+ return file
345
+
346
+
347
+ class AsyncFiles(AsyncAPIResource):
348
+ @cached_property
349
+ def with_raw_response(self) -> AsyncFilesWithRawResponse:
350
+ """
351
+ This property can be used as a prefix for any HTTP method call to return
352
+ the raw response object instead of the parsed content.
353
+
354
+ For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
355
+ """
356
+ return AsyncFilesWithRawResponse(self)
357
+
358
+ @cached_property
359
+ def with_streaming_response(self) -> AsyncFilesWithStreamingResponse:
360
+ """
361
+ An alternative to `.with_raw_response` that doesn't eagerly read the response body.
362
+
363
+ For more information, see https://www.github.com/openai/openai-python#with_streaming_response
364
+ """
365
+ return AsyncFilesWithStreamingResponse(self)
366
+
367
+ async def create(
368
+ self,
369
+ *,
370
+ file: FileTypes,
371
+ purpose: FilePurpose,
372
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
373
+ # The extra values given here take precedence over values defined on the client or passed to this method.
374
+ extra_headers: Headers | None = None,
375
+ extra_query: Query | None = None,
376
+ extra_body: Body | None = None,
377
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
378
+ ) -> FileObject:
379
+ """Upload a file that can be used across various endpoints.
380
+
381
+ Individual files can be
382
+ up to 512 MB, and the size of all files uploaded by one organization can be up
383
+ to 100 GB.
384
+
385
+ The Assistants API supports files up to 2 million tokens and of specific file
386
+ types. See the
387
+ [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for
388
+ details.
389
+
390
+ The Fine-tuning API only supports `.jsonl` files. The input also has certain
391
+ required formats for fine-tuning
392
+ [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or
393
+ [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input)
394
+ models.
395
+
396
+ The Batch API only supports `.jsonl` files up to 200 MB in size. The input also
397
+ has a specific required
398
+ [format](https://platform.openai.com/docs/api-reference/batch/request-input).
399
+
400
+ Please [contact us](https://help.openai.com/) if you need to increase these
401
+ storage limits.
402
+
403
+ Args:
404
+ file: The File object (not file name) to be uploaded.
405
+
406
+ purpose: The intended purpose of the uploaded file. One of: - `assistants`: Used in the
407
+ Assistants API - `batch`: Used in the Batch API - `fine-tune`: Used for
408
+ fine-tuning - `vision`: Images used for vision fine-tuning - `user_data`:
409
+ Flexible file type for any purpose - `evals`: Used for eval data sets
410
+
411
+ extra_headers: Send extra headers
412
+
413
+ extra_query: Add additional query parameters to the request
414
+
415
+ extra_body: Add additional JSON properties to the request
416
+
417
+ timeout: Override the client-level default timeout for this request, in seconds
418
+ """
419
+ body = deepcopy_minimal(
420
+ {
421
+ "file": file,
422
+ "purpose": purpose,
423
+ }
424
+ )
425
+ files = extract_files(cast(Mapping[str, object], body), paths=[["file"]])
426
+ # It should be noted that the actual Content-Type header that will be
427
+ # sent to the server will contain a `boundary` parameter, e.g.
428
+ # multipart/form-data; boundary=---abc--
429
+ extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})}
430
+ return await self._post(
431
+ "/files",
432
+ body=await async_maybe_transform(body, file_create_params.FileCreateParams),
433
+ files=files,
434
+ options=make_request_options(
435
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
436
+ ),
437
+ cast_to=FileObject,
438
+ )
439
+
440
+ async def retrieve(
441
+ self,
442
+ file_id: str,
443
+ *,
444
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
445
+ # The extra values given here take precedence over values defined on the client or passed to this method.
446
+ extra_headers: Headers | None = None,
447
+ extra_query: Query | None = None,
448
+ extra_body: Body | None = None,
449
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
450
+ ) -> FileObject:
451
+ """
452
+ Returns information about a specific file.
453
+
454
+ Args:
455
+ extra_headers: Send extra headers
456
+
457
+ extra_query: Add additional query parameters to the request
458
+
459
+ extra_body: Add additional JSON properties to the request
460
+
461
+ timeout: Override the client-level default timeout for this request, in seconds
462
+ """
463
+ if not file_id:
464
+ raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}")
465
+ return await self._get(
466
+ f"/files/{file_id}",
467
+ options=make_request_options(
468
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
469
+ ),
470
+ cast_to=FileObject,
471
+ )
472
+
473
+ def list(
474
+ self,
475
+ *,
476
+ after: str | NotGiven = NOT_GIVEN,
477
+ limit: int | NotGiven = NOT_GIVEN,
478
+ order: Literal["asc", "desc"] | NotGiven = NOT_GIVEN,
479
+ purpose: str | NotGiven = NOT_GIVEN,
480
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
481
+ # The extra values given here take precedence over values defined on the client or passed to this method.
482
+ extra_headers: Headers | None = None,
483
+ extra_query: Query | None = None,
484
+ extra_body: Body | None = None,
485
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
486
+ ) -> AsyncPaginator[FileObject, AsyncCursorPage[FileObject]]:
487
+ """Returns a list of files.
488
+
489
+ Args:
490
+ after: A cursor for use in pagination.
491
+
492
+ `after` is an object ID that defines your place
493
+ in the list. For instance, if you make a list request and receive 100 objects,
494
+ ending with obj_foo, your subsequent call can include after=obj_foo in order to
495
+ fetch the next page of the list.
496
+
497
+ limit: A limit on the number of objects to be returned. Limit can range between 1 and
498
+ 10,000, and the default is 10,000.
499
+
500
+ order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending
501
+ order and `desc` for descending order.
502
+
503
+ purpose: Only return files with the given purpose.
504
+
505
+ extra_headers: Send extra headers
506
+
507
+ extra_query: Add additional query parameters to the request
508
+
509
+ extra_body: Add additional JSON properties to the request
510
+
511
+ timeout: Override the client-level default timeout for this request, in seconds
512
+ """
513
+ return self._get_api_list(
514
+ "/files",
515
+ page=AsyncCursorPage[FileObject],
516
+ options=make_request_options(
517
+ extra_headers=extra_headers,
518
+ extra_query=extra_query,
519
+ extra_body=extra_body,
520
+ timeout=timeout,
521
+ query=maybe_transform(
522
+ {
523
+ "after": after,
524
+ "limit": limit,
525
+ "order": order,
526
+ "purpose": purpose,
527
+ },
528
+ file_list_params.FileListParams,
529
+ ),
530
+ ),
531
+ model=FileObject,
532
+ )
533
+
534
+ async def delete(
535
+ self,
536
+ file_id: str,
537
+ *,
538
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
539
+ # The extra values given here take precedence over values defined on the client or passed to this method.
540
+ extra_headers: Headers | None = None,
541
+ extra_query: Query | None = None,
542
+ extra_body: Body | None = None,
543
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
544
+ ) -> FileDeleted:
545
+ """
546
+ Delete a file.
547
+
548
+ Args:
549
+ extra_headers: Send extra headers
550
+
551
+ extra_query: Add additional query parameters to the request
552
+
553
+ extra_body: Add additional JSON properties to the request
554
+
555
+ timeout: Override the client-level default timeout for this request, in seconds
556
+ """
557
+ if not file_id:
558
+ raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}")
559
+ return await self._delete(
560
+ f"/files/{file_id}",
561
+ options=make_request_options(
562
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
563
+ ),
564
+ cast_to=FileDeleted,
565
+ )
566
+
567
+ async def content(
568
+ self,
569
+ file_id: str,
570
+ *,
571
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
572
+ # The extra values given here take precedence over values defined on the client or passed to this method.
573
+ extra_headers: Headers | None = None,
574
+ extra_query: Query | None = None,
575
+ extra_body: Body | None = None,
576
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
577
+ ) -> _legacy_response.HttpxBinaryResponseContent:
578
+ """
579
+ Returns the contents of the specified file.
580
+
581
+ Args:
582
+ extra_headers: Send extra headers
583
+
584
+ extra_query: Add additional query parameters to the request
585
+
586
+ extra_body: Add additional JSON properties to the request
587
+
588
+ timeout: Override the client-level default timeout for this request, in seconds
589
+ """
590
+ if not file_id:
591
+ raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}")
592
+ extra_headers = {"Accept": "application/binary", **(extra_headers or {})}
593
+ return await self._get(
594
+ f"/files/{file_id}/content",
595
+ options=make_request_options(
596
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
597
+ ),
598
+ cast_to=_legacy_response.HttpxBinaryResponseContent,
599
+ )
600
+
601
+ @typing_extensions.deprecated("The `.content()` method should be used instead")
602
+ async def retrieve_content(
603
+ self,
604
+ file_id: str,
605
+ *,
606
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
607
+ # The extra values given here take precedence over values defined on the client or passed to this method.
608
+ extra_headers: Headers | None = None,
609
+ extra_query: Query | None = None,
610
+ extra_body: Body | None = None,
611
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
612
+ ) -> str:
613
+ """
614
+ Returns the contents of the specified file.
615
+
616
+ Args:
617
+ extra_headers: Send extra headers
618
+
619
+ extra_query: Add additional query parameters to the request
620
+
621
+ extra_body: Add additional JSON properties to the request
622
+
623
+ timeout: Override the client-level default timeout for this request, in seconds
624
+ """
625
+ if not file_id:
626
+ raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}")
627
+ return await self._get(
628
+ f"/files/{file_id}/content",
629
+ options=make_request_options(
630
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
631
+ ),
632
+ cast_to=str,
633
+ )
634
+
635
+ async def wait_for_processing(
636
+ self,
637
+ id: str,
638
+ *,
639
+ poll_interval: float = 5.0,
640
+ max_wait_seconds: float = 30 * 60,
641
+ ) -> FileObject:
642
+ """Waits for the given file to be processed, default timeout is 30 mins."""
643
+ TERMINAL_STATES = {"processed", "error", "deleted"}
644
+
645
+ start = time.time()
646
+ file = await self.retrieve(id)
647
+ while file.status not in TERMINAL_STATES:
648
+ await self._sleep(poll_interval)
649
+
650
+ file = await self.retrieve(id)
651
+ if time.time() - start > max_wait_seconds:
652
+ raise RuntimeError(
653
+ f"Giving up on waiting for file {id} to finish processing after {max_wait_seconds} seconds."
654
+ )
655
+
656
+ return file
657
+
658
+
659
+ class FilesWithRawResponse:
660
+ def __init__(self, files: Files) -> None:
661
+ self._files = files
662
+
663
+ self.create = _legacy_response.to_raw_response_wrapper(
664
+ files.create,
665
+ )
666
+ self.retrieve = _legacy_response.to_raw_response_wrapper(
667
+ files.retrieve,
668
+ )
669
+ self.list = _legacy_response.to_raw_response_wrapper(
670
+ files.list,
671
+ )
672
+ self.delete = _legacy_response.to_raw_response_wrapper(
673
+ files.delete,
674
+ )
675
+ self.content = _legacy_response.to_raw_response_wrapper(
676
+ files.content,
677
+ )
678
+ self.retrieve_content = ( # pyright: ignore[reportDeprecated]
679
+ _legacy_response.to_raw_response_wrapper(
680
+ files.retrieve_content # pyright: ignore[reportDeprecated],
681
+ )
682
+ )
683
+
684
+
685
+ class AsyncFilesWithRawResponse:
686
+ def __init__(self, files: AsyncFiles) -> None:
687
+ self._files = files
688
+
689
+ self.create = _legacy_response.async_to_raw_response_wrapper(
690
+ files.create,
691
+ )
692
+ self.retrieve = _legacy_response.async_to_raw_response_wrapper(
693
+ files.retrieve,
694
+ )
695
+ self.list = _legacy_response.async_to_raw_response_wrapper(
696
+ files.list,
697
+ )
698
+ self.delete = _legacy_response.async_to_raw_response_wrapper(
699
+ files.delete,
700
+ )
701
+ self.content = _legacy_response.async_to_raw_response_wrapper(
702
+ files.content,
703
+ )
704
+ self.retrieve_content = ( # pyright: ignore[reportDeprecated]
705
+ _legacy_response.async_to_raw_response_wrapper(
706
+ files.retrieve_content # pyright: ignore[reportDeprecated],
707
+ )
708
+ )
709
+
710
+
711
+ class FilesWithStreamingResponse:
712
+ def __init__(self, files: Files) -> None:
713
+ self._files = files
714
+
715
+ self.create = to_streamed_response_wrapper(
716
+ files.create,
717
+ )
718
+ self.retrieve = to_streamed_response_wrapper(
719
+ files.retrieve,
720
+ )
721
+ self.list = to_streamed_response_wrapper(
722
+ files.list,
723
+ )
724
+ self.delete = to_streamed_response_wrapper(
725
+ files.delete,
726
+ )
727
+ self.content = to_custom_streamed_response_wrapper(
728
+ files.content,
729
+ StreamedBinaryAPIResponse,
730
+ )
731
+ self.retrieve_content = ( # pyright: ignore[reportDeprecated]
732
+ to_streamed_response_wrapper(
733
+ files.retrieve_content # pyright: ignore[reportDeprecated],
734
+ )
735
+ )
736
+
737
+
738
+ class AsyncFilesWithStreamingResponse:
739
+ def __init__(self, files: AsyncFiles) -> None:
740
+ self._files = files
741
+
742
+ self.create = async_to_streamed_response_wrapper(
743
+ files.create,
744
+ )
745
+ self.retrieve = async_to_streamed_response_wrapper(
746
+ files.retrieve,
747
+ )
748
+ self.list = async_to_streamed_response_wrapper(
749
+ files.list,
750
+ )
751
+ self.delete = async_to_streamed_response_wrapper(
752
+ files.delete,
753
+ )
754
+ self.content = async_to_custom_streamed_response_wrapper(
755
+ files.content,
756
+ AsyncStreamedBinaryAPIResponse,
757
+ )
758
+ self.retrieve_content = ( # pyright: ignore[reportDeprecated]
759
+ async_to_streamed_response_wrapper(
760
+ files.retrieve_content # pyright: ignore[reportDeprecated],
761
+ )
762
+ )
python_embeded/Lib/site-packages/openai/resources/images.py ADDED
@@ -0,0 +1,753 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import List, Union, Mapping, Optional, cast
6
+ from typing_extensions import Literal
7
+
8
+ import httpx
9
+
10
+ from .. import _legacy_response
11
+ from ..types import image_edit_params, image_generate_params, image_create_variation_params
12
+ from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes
13
+ from .._utils import extract_files, maybe_transform, deepcopy_minimal, async_maybe_transform
14
+ from .._compat import cached_property
15
+ from .._resource import SyncAPIResource, AsyncAPIResource
16
+ from .._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper
17
+ from .._base_client import make_request_options
18
+ from ..types.image_model import ImageModel
19
+ from ..types.images_response import ImagesResponse
20
+
21
+ __all__ = ["Images", "AsyncImages"]
22
+
23
+
24
+ class Images(SyncAPIResource):
25
+ @cached_property
26
+ def with_raw_response(self) -> ImagesWithRawResponse:
27
+ """
28
+ This property can be used as a prefix for any HTTP method call to return
29
+ the raw response object instead of the parsed content.
30
+
31
+ For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
32
+ """
33
+ return ImagesWithRawResponse(self)
34
+
35
+ @cached_property
36
+ def with_streaming_response(self) -> ImagesWithStreamingResponse:
37
+ """
38
+ An alternative to `.with_raw_response` that doesn't eagerly read the response body.
39
+
40
+ For more information, see https://www.github.com/openai/openai-python#with_streaming_response
41
+ """
42
+ return ImagesWithStreamingResponse(self)
43
+
44
+ def create_variation(
45
+ self,
46
+ *,
47
+ image: FileTypes,
48
+ model: Union[str, ImageModel, None] | NotGiven = NOT_GIVEN,
49
+ n: Optional[int] | NotGiven = NOT_GIVEN,
50
+ response_format: Optional[Literal["url", "b64_json"]] | NotGiven = NOT_GIVEN,
51
+ size: Optional[Literal["256x256", "512x512", "1024x1024"]] | NotGiven = NOT_GIVEN,
52
+ user: str | NotGiven = NOT_GIVEN,
53
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
54
+ # The extra values given here take precedence over values defined on the client or passed to this method.
55
+ extra_headers: Headers | None = None,
56
+ extra_query: Query | None = None,
57
+ extra_body: Body | None = None,
58
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
59
+ ) -> ImagesResponse:
60
+ """Creates a variation of a given image.
61
+
62
+ This endpoint only supports `dall-e-2`.
63
+
64
+ Args:
65
+ image: The image to use as the basis for the variation(s). Must be a valid PNG file,
66
+ less than 4MB, and square.
67
+
68
+ model: The model to use for image generation. Only `dall-e-2` is supported at this
69
+ time.
70
+
71
+ n: The number of images to generate. Must be between 1 and 10.
72
+
73
+ response_format: The format in which the generated images are returned. Must be one of `url` or
74
+ `b64_json`. URLs are only valid for 60 minutes after the image has been
75
+ generated.
76
+
77
+ size: The size of the generated images. Must be one of `256x256`, `512x512`, or
78
+ `1024x1024`.
79
+
80
+ user: A unique identifier representing your end-user, which can help OpenAI to monitor
81
+ and detect abuse.
82
+ [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).
83
+
84
+ extra_headers: Send extra headers
85
+
86
+ extra_query: Add additional query parameters to the request
87
+
88
+ extra_body: Add additional JSON properties to the request
89
+
90
+ timeout: Override the client-level default timeout for this request, in seconds
91
+ """
92
+ body = deepcopy_minimal(
93
+ {
94
+ "image": image,
95
+ "model": model,
96
+ "n": n,
97
+ "response_format": response_format,
98
+ "size": size,
99
+ "user": user,
100
+ }
101
+ )
102
+ files = extract_files(cast(Mapping[str, object], body), paths=[["image"]])
103
+ # It should be noted that the actual Content-Type header that will be
104
+ # sent to the server will contain a `boundary` parameter, e.g.
105
+ # multipart/form-data; boundary=---abc--
106
+ extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})}
107
+ return self._post(
108
+ "/images/variations",
109
+ body=maybe_transform(body, image_create_variation_params.ImageCreateVariationParams),
110
+ files=files,
111
+ options=make_request_options(
112
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
113
+ ),
114
+ cast_to=ImagesResponse,
115
+ )
116
+
117
+ def edit(
118
+ self,
119
+ *,
120
+ image: Union[FileTypes, List[FileTypes]],
121
+ prompt: str,
122
+ background: Optional[Literal["transparent", "opaque", "auto"]] | NotGiven = NOT_GIVEN,
123
+ mask: FileTypes | NotGiven = NOT_GIVEN,
124
+ model: Union[str, ImageModel, None] | NotGiven = NOT_GIVEN,
125
+ n: Optional[int] | NotGiven = NOT_GIVEN,
126
+ output_compression: Optional[int] | NotGiven = NOT_GIVEN,
127
+ output_format: Optional[Literal["png", "jpeg", "webp"]] | NotGiven = NOT_GIVEN,
128
+ quality: Optional[Literal["standard", "low", "medium", "high", "auto"]] | NotGiven = NOT_GIVEN,
129
+ response_format: Optional[Literal["url", "b64_json"]] | NotGiven = NOT_GIVEN,
130
+ size: Optional[Literal["256x256", "512x512", "1024x1024", "1536x1024", "1024x1536", "auto"]]
131
+ | NotGiven = NOT_GIVEN,
132
+ user: str | NotGiven = NOT_GIVEN,
133
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
134
+ # The extra values given here take precedence over values defined on the client or passed to this method.
135
+ extra_headers: Headers | None = None,
136
+ extra_query: Query | None = None,
137
+ extra_body: Body | None = None,
138
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
139
+ ) -> ImagesResponse:
140
+ """Creates an edited or extended image given one or more source images and a
141
+ prompt.
142
+
143
+ This endpoint only supports `gpt-image-1` and `dall-e-2`.
144
+
145
+ Args:
146
+ image: The image(s) to edit. Must be a supported image file or an array of images.
147
+
148
+ For `gpt-image-1`, each image should be a `png`, `webp`, or `jpg` file less than
149
+ 50MB. You can provide up to 16 images.
150
+
151
+ For `dall-e-2`, you can only provide one image, and it should be a square `png`
152
+ file less than 4MB.
153
+
154
+ prompt: A text description of the desired image(s). The maximum length is 1000
155
+ characters for `dall-e-2`, and 32000 characters for `gpt-image-1`.
156
+
157
+ background: Allows to set transparency for the background of the generated image(s). This
158
+ parameter is only supported for `gpt-image-1`. Must be one of `transparent`,
159
+ `opaque` or `auto` (default value). When `auto` is used, the model will
160
+ automatically determine the best background for the image.
161
+
162
+ If `transparent`, the output format needs to support transparency, so it should
163
+ be set to either `png` (default value) or `webp`.
164
+
165
+ mask: An additional image whose fully transparent areas (e.g. where alpha is zero)
166
+ indicate where `image` should be edited. If there are multiple images provided,
167
+ the mask will be applied on the first image. Must be a valid PNG file, less than
168
+ 4MB, and have the same dimensions as `image`.
169
+
170
+ model: The model to use for image generation. Only `dall-e-2` and `gpt-image-1` are
171
+ supported. Defaults to `dall-e-2` unless a parameter specific to `gpt-image-1`
172
+ is used.
173
+
174
+ n: The number of images to generate. Must be between 1 and 10.
175
+
176
+ output_compression: The compression level (0-100%) for the generated images. This parameter is only
177
+ supported for `gpt-image-1` with the `webp` or `jpeg` output formats, and
178
+ defaults to 100.
179
+
180
+ output_format: The format in which the generated images are returned. This parameter is only
181
+ supported for `gpt-image-1`. Must be one of `png`, `jpeg`, or `webp`. The
182
+ default value is `png`.
183
+
184
+ quality: The quality of the image that will be generated. `high`, `medium` and `low` are
185
+ only supported for `gpt-image-1`. `dall-e-2` only supports `standard` quality.
186
+ Defaults to `auto`.
187
+
188
+ response_format: The format in which the generated images are returned. Must be one of `url` or
189
+ `b64_json`. URLs are only valid for 60 minutes after the image has been
190
+ generated. This parameter is only supported for `dall-e-2`, as `gpt-image-1`
191
+ will always return base64-encoded images.
192
+
193
+ size: The size of the generated images. Must be one of `1024x1024`, `1536x1024`
194
+ (landscape), `1024x1536` (portrait), or `auto` (default value) for
195
+ `gpt-image-1`, and one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`.
196
+
197
+ user: A unique identifier representing your end-user, which can help OpenAI to monitor
198
+ and detect abuse.
199
+ [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).
200
+
201
+ extra_headers: Send extra headers
202
+
203
+ extra_query: Add additional query parameters to the request
204
+
205
+ extra_body: Add additional JSON properties to the request
206
+
207
+ timeout: Override the client-level default timeout for this request, in seconds
208
+ """
209
+ body = deepcopy_minimal(
210
+ {
211
+ "image": image,
212
+ "prompt": prompt,
213
+ "background": background,
214
+ "mask": mask,
215
+ "model": model,
216
+ "n": n,
217
+ "output_compression": output_compression,
218
+ "output_format": output_format,
219
+ "quality": quality,
220
+ "response_format": response_format,
221
+ "size": size,
222
+ "user": user,
223
+ }
224
+ )
225
+ files = extract_files(cast(Mapping[str, object], body), paths=[["image"], ["image", "<array>"], ["mask"]])
226
+ # It should be noted that the actual Content-Type header that will be
227
+ # sent to the server will contain a `boundary` parameter, e.g.
228
+ # multipart/form-data; boundary=---abc--
229
+ extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})}
230
+ return self._post(
231
+ "/images/edits",
232
+ body=maybe_transform(body, image_edit_params.ImageEditParams),
233
+ files=files,
234
+ options=make_request_options(
235
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
236
+ ),
237
+ cast_to=ImagesResponse,
238
+ )
239
+
240
+ def generate(
241
+ self,
242
+ *,
243
+ prompt: str,
244
+ background: Optional[Literal["transparent", "opaque", "auto"]] | NotGiven = NOT_GIVEN,
245
+ model: Union[str, ImageModel, None] | NotGiven = NOT_GIVEN,
246
+ moderation: Optional[Literal["low", "auto"]] | NotGiven = NOT_GIVEN,
247
+ n: Optional[int] | NotGiven = NOT_GIVEN,
248
+ output_compression: Optional[int] | NotGiven = NOT_GIVEN,
249
+ output_format: Optional[Literal["png", "jpeg", "webp"]] | NotGiven = NOT_GIVEN,
250
+ quality: Optional[Literal["standard", "hd", "low", "medium", "high", "auto"]] | NotGiven = NOT_GIVEN,
251
+ response_format: Optional[Literal["url", "b64_json"]] | NotGiven = NOT_GIVEN,
252
+ size: Optional[
253
+ Literal["auto", "1024x1024", "1536x1024", "1024x1536", "256x256", "512x512", "1792x1024", "1024x1792"]
254
+ ]
255
+ | NotGiven = NOT_GIVEN,
256
+ style: Optional[Literal["vivid", "natural"]] | NotGiven = NOT_GIVEN,
257
+ user: str | NotGiven = NOT_GIVEN,
258
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
259
+ # The extra values given here take precedence over values defined on the client or passed to this method.
260
+ extra_headers: Headers | None = None,
261
+ extra_query: Query | None = None,
262
+ extra_body: Body | None = None,
263
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
264
+ ) -> ImagesResponse:
265
+ """
266
+ Creates an image given a prompt.
267
+ [Learn more](https://platform.openai.com/docs/guides/images).
268
+
269
+ Args:
270
+ prompt: A text description of the desired image(s). The maximum length is 32000
271
+ characters for `gpt-image-1`, 1000 characters for `dall-e-2` and 4000 characters
272
+ for `dall-e-3`.
273
+
274
+ background: Allows to set transparency for the background of the generated image(s). This
275
+ parameter is only supported for `gpt-image-1`. Must be one of `transparent`,
276
+ `opaque` or `auto` (default value). When `auto` is used, the model will
277
+ automatically determine the best background for the image.
278
+
279
+ If `transparent`, the output format needs to support transparency, so it should
280
+ be set to either `png` (default value) or `webp`.
281
+
282
+ model: The model to use for image generation. One of `dall-e-2`, `dall-e-3`, or
283
+ `gpt-image-1`. Defaults to `dall-e-2` unless a parameter specific to
284
+ `gpt-image-1` is used.
285
+
286
+ moderation: Control the content-moderation level for images generated by `gpt-image-1`. Must
287
+ be either `low` for less restrictive filtering or `auto` (default value).
288
+
289
+ n: The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only
290
+ `n=1` is supported.
291
+
292
+ output_compression: The compression level (0-100%) for the generated images. This parameter is only
293
+ supported for `gpt-image-1` with the `webp` or `jpeg` output formats, and
294
+ defaults to 100.
295
+
296
+ output_format: The format in which the generated images are returned. This parameter is only
297
+ supported for `gpt-image-1`. Must be one of `png`, `jpeg`, or `webp`.
298
+
299
+ quality: The quality of the image that will be generated.
300
+
301
+ - `auto` (default value) will automatically select the best quality for the
302
+ given model.
303
+ - `high`, `medium` and `low` are supported for `gpt-image-1`.
304
+ - `hd` and `standard` are supported for `dall-e-3`.
305
+ - `standard` is the only option for `dall-e-2`.
306
+
307
+ response_format: The format in which generated images with `dall-e-2` and `dall-e-3` are
308
+ returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes
309
+ after the image has been generated. This parameter isn't supported for
310
+ `gpt-image-1` which will always return base64-encoded images.
311
+
312
+ size: The size of the generated images. Must be one of `1024x1024`, `1536x1024`
313
+ (landscape), `1024x1536` (portrait), or `auto` (default value) for
314
+ `gpt-image-1`, one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`, and
315
+ one of `1024x1024`, `1792x1024`, or `1024x1792` for `dall-e-3`.
316
+
317
+ style: The style of the generated images. This parameter is only supported for
318
+ `dall-e-3`. Must be one of `vivid` or `natural`. Vivid causes the model to lean
319
+ towards generating hyper-real and dramatic images. Natural causes the model to
320
+ produce more natural, less hyper-real looking images.
321
+
322
+ user: A unique identifier representing your end-user, which can help OpenAI to monitor
323
+ and detect abuse.
324
+ [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).
325
+
326
+ extra_headers: Send extra headers
327
+
328
+ extra_query: Add additional query parameters to the request
329
+
330
+ extra_body: Add additional JSON properties to the request
331
+
332
+ timeout: Override the client-level default timeout for this request, in seconds
333
+ """
334
+ return self._post(
335
+ "/images/generations",
336
+ body=maybe_transform(
337
+ {
338
+ "prompt": prompt,
339
+ "background": background,
340
+ "model": model,
341
+ "moderation": moderation,
342
+ "n": n,
343
+ "output_compression": output_compression,
344
+ "output_format": output_format,
345
+ "quality": quality,
346
+ "response_format": response_format,
347
+ "size": size,
348
+ "style": style,
349
+ "user": user,
350
+ },
351
+ image_generate_params.ImageGenerateParams,
352
+ ),
353
+ options=make_request_options(
354
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
355
+ ),
356
+ cast_to=ImagesResponse,
357
+ )
358
+
359
+
360
+ class AsyncImages(AsyncAPIResource):
361
+ @cached_property
362
+ def with_raw_response(self) -> AsyncImagesWithRawResponse:
363
+ """
364
+ This property can be used as a prefix for any HTTP method call to return
365
+ the raw response object instead of the parsed content.
366
+
367
+ For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
368
+ """
369
+ return AsyncImagesWithRawResponse(self)
370
+
371
+ @cached_property
372
+ def with_streaming_response(self) -> AsyncImagesWithStreamingResponse:
373
+ """
374
+ An alternative to `.with_raw_response` that doesn't eagerly read the response body.
375
+
376
+ For more information, see https://www.github.com/openai/openai-python#with_streaming_response
377
+ """
378
+ return AsyncImagesWithStreamingResponse(self)
379
+
380
+ async def create_variation(
381
+ self,
382
+ *,
383
+ image: FileTypes,
384
+ model: Union[str, ImageModel, None] | NotGiven = NOT_GIVEN,
385
+ n: Optional[int] | NotGiven = NOT_GIVEN,
386
+ response_format: Optional[Literal["url", "b64_json"]] | NotGiven = NOT_GIVEN,
387
+ size: Optional[Literal["256x256", "512x512", "1024x1024"]] | NotGiven = NOT_GIVEN,
388
+ user: str | NotGiven = NOT_GIVEN,
389
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
390
+ # The extra values given here take precedence over values defined on the client or passed to this method.
391
+ extra_headers: Headers | None = None,
392
+ extra_query: Query | None = None,
393
+ extra_body: Body | None = None,
394
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
395
+ ) -> ImagesResponse:
396
+ """Creates a variation of a given image.
397
+
398
+ This endpoint only supports `dall-e-2`.
399
+
400
+ Args:
401
+ image: The image to use as the basis for the variation(s). Must be a valid PNG file,
402
+ less than 4MB, and square.
403
+
404
+ model: The model to use for image generation. Only `dall-e-2` is supported at this
405
+ time.
406
+
407
+ n: The number of images to generate. Must be between 1 and 10.
408
+
409
+ response_format: The format in which the generated images are returned. Must be one of `url` or
410
+ `b64_json`. URLs are only valid for 60 minutes after the image has been
411
+ generated.
412
+
413
+ size: The size of the generated images. Must be one of `256x256`, `512x512`, or
414
+ `1024x1024`.
415
+
416
+ user: A unique identifier representing your end-user, which can help OpenAI to monitor
417
+ and detect abuse.
418
+ [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).
419
+
420
+ extra_headers: Send extra headers
421
+
422
+ extra_query: Add additional query parameters to the request
423
+
424
+ extra_body: Add additional JSON properties to the request
425
+
426
+ timeout: Override the client-level default timeout for this request, in seconds
427
+ """
428
+ body = deepcopy_minimal(
429
+ {
430
+ "image": image,
431
+ "model": model,
432
+ "n": n,
433
+ "response_format": response_format,
434
+ "size": size,
435
+ "user": user,
436
+ }
437
+ )
438
+ files = extract_files(cast(Mapping[str, object], body), paths=[["image"]])
439
+ # It should be noted that the actual Content-Type header that will be
440
+ # sent to the server will contain a `boundary` parameter, e.g.
441
+ # multipart/form-data; boundary=---abc--
442
+ extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})}
443
+ return await self._post(
444
+ "/images/variations",
445
+ body=await async_maybe_transform(body, image_create_variation_params.ImageCreateVariationParams),
446
+ files=files,
447
+ options=make_request_options(
448
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
449
+ ),
450
+ cast_to=ImagesResponse,
451
+ )
452
+
453
+ async def edit(
454
+ self,
455
+ *,
456
+ image: Union[FileTypes, List[FileTypes]],
457
+ prompt: str,
458
+ background: Optional[Literal["transparent", "opaque", "auto"]] | NotGiven = NOT_GIVEN,
459
+ mask: FileTypes | NotGiven = NOT_GIVEN,
460
+ model: Union[str, ImageModel, None] | NotGiven = NOT_GIVEN,
461
+ n: Optional[int] | NotGiven = NOT_GIVEN,
462
+ output_compression: Optional[int] | NotGiven = NOT_GIVEN,
463
+ output_format: Optional[Literal["png", "jpeg", "webp"]] | NotGiven = NOT_GIVEN,
464
+ quality: Optional[Literal["standard", "low", "medium", "high", "auto"]] | NotGiven = NOT_GIVEN,
465
+ response_format: Optional[Literal["url", "b64_json"]] | NotGiven = NOT_GIVEN,
466
+ size: Optional[Literal["256x256", "512x512", "1024x1024", "1536x1024", "1024x1536", "auto"]]
467
+ | NotGiven = NOT_GIVEN,
468
+ user: str | NotGiven = NOT_GIVEN,
469
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
470
+ # The extra values given here take precedence over values defined on the client or passed to this method.
471
+ extra_headers: Headers | None = None,
472
+ extra_query: Query | None = None,
473
+ extra_body: Body | None = None,
474
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
475
+ ) -> ImagesResponse:
476
+ """Creates an edited or extended image given one or more source images and a
477
+ prompt.
478
+
479
+ This endpoint only supports `gpt-image-1` and `dall-e-2`.
480
+
481
+ Args:
482
+ image: The image(s) to edit. Must be a supported image file or an array of images.
483
+
484
+ For `gpt-image-1`, each image should be a `png`, `webp`, or `jpg` file less than
485
+ 50MB. You can provide up to 16 images.
486
+
487
+ For `dall-e-2`, you can only provide one image, and it should be a square `png`
488
+ file less than 4MB.
489
+
490
+ prompt: A text description of the desired image(s). The maximum length is 1000
491
+ characters for `dall-e-2`, and 32000 characters for `gpt-image-1`.
492
+
493
+ background: Allows to set transparency for the background of the generated image(s). This
494
+ parameter is only supported for `gpt-image-1`. Must be one of `transparent`,
495
+ `opaque` or `auto` (default value). When `auto` is used, the model will
496
+ automatically determine the best background for the image.
497
+
498
+ If `transparent`, the output format needs to support transparency, so it should
499
+ be set to either `png` (default value) or `webp`.
500
+
501
+ mask: An additional image whose fully transparent areas (e.g. where alpha is zero)
502
+ indicate where `image` should be edited. If there are multiple images provided,
503
+ the mask will be applied on the first image. Must be a valid PNG file, less than
504
+ 4MB, and have the same dimensions as `image`.
505
+
506
+ model: The model to use for image generation. Only `dall-e-2` and `gpt-image-1` are
507
+ supported. Defaults to `dall-e-2` unless a parameter specific to `gpt-image-1`
508
+ is used.
509
+
510
+ n: The number of images to generate. Must be between 1 and 10.
511
+
512
+ output_compression: The compression level (0-100%) for the generated images. This parameter is only
513
+ supported for `gpt-image-1` with the `webp` or `jpeg` output formats, and
514
+ defaults to 100.
515
+
516
+ output_format: The format in which the generated images are returned. This parameter is only
517
+ supported for `gpt-image-1`. Must be one of `png`, `jpeg`, or `webp`. The
518
+ default value is `png`.
519
+
520
+ quality: The quality of the image that will be generated. `high`, `medium` and `low` are
521
+ only supported for `gpt-image-1`. `dall-e-2` only supports `standard` quality.
522
+ Defaults to `auto`.
523
+
524
+ response_format: The format in which the generated images are returned. Must be one of `url` or
525
+ `b64_json`. URLs are only valid for 60 minutes after the image has been
526
+ generated. This parameter is only supported for `dall-e-2`, as `gpt-image-1`
527
+ will always return base64-encoded images.
528
+
529
+ size: The size of the generated images. Must be one of `1024x1024`, `1536x1024`
530
+ (landscape), `1024x1536` (portrait), or `auto` (default value) for
531
+ `gpt-image-1`, and one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`.
532
+
533
+ user: A unique identifier representing your end-user, which can help OpenAI to monitor
534
+ and detect abuse.
535
+ [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).
536
+
537
+ extra_headers: Send extra headers
538
+
539
+ extra_query: Add additional query parameters to the request
540
+
541
+ extra_body: Add additional JSON properties to the request
542
+
543
+ timeout: Override the client-level default timeout for this request, in seconds
544
+ """
545
+ body = deepcopy_minimal(
546
+ {
547
+ "image": image,
548
+ "prompt": prompt,
549
+ "background": background,
550
+ "mask": mask,
551
+ "model": model,
552
+ "n": n,
553
+ "output_compression": output_compression,
554
+ "output_format": output_format,
555
+ "quality": quality,
556
+ "response_format": response_format,
557
+ "size": size,
558
+ "user": user,
559
+ }
560
+ )
561
+ files = extract_files(cast(Mapping[str, object], body), paths=[["image"], ["image", "<array>"], ["mask"]])
562
+ # It should be noted that the actual Content-Type header that will be
563
+ # sent to the server will contain a `boundary` parameter, e.g.
564
+ # multipart/form-data; boundary=---abc--
565
+ extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})}
566
+ return await self._post(
567
+ "/images/edits",
568
+ body=await async_maybe_transform(body, image_edit_params.ImageEditParams),
569
+ files=files,
570
+ options=make_request_options(
571
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
572
+ ),
573
+ cast_to=ImagesResponse,
574
+ )
575
+
576
+ async def generate(
577
+ self,
578
+ *,
579
+ prompt: str,
580
+ background: Optional[Literal["transparent", "opaque", "auto"]] | NotGiven = NOT_GIVEN,
581
+ model: Union[str, ImageModel, None] | NotGiven = NOT_GIVEN,
582
+ moderation: Optional[Literal["low", "auto"]] | NotGiven = NOT_GIVEN,
583
+ n: Optional[int] | NotGiven = NOT_GIVEN,
584
+ output_compression: Optional[int] | NotGiven = NOT_GIVEN,
585
+ output_format: Optional[Literal["png", "jpeg", "webp"]] | NotGiven = NOT_GIVEN,
586
+ quality: Optional[Literal["standard", "hd", "low", "medium", "high", "auto"]] | NotGiven = NOT_GIVEN,
587
+ response_format: Optional[Literal["url", "b64_json"]] | NotGiven = NOT_GIVEN,
588
+ size: Optional[
589
+ Literal["auto", "1024x1024", "1536x1024", "1024x1536", "256x256", "512x512", "1792x1024", "1024x1792"]
590
+ ]
591
+ | NotGiven = NOT_GIVEN,
592
+ style: Optional[Literal["vivid", "natural"]] | NotGiven = NOT_GIVEN,
593
+ user: str | NotGiven = NOT_GIVEN,
594
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
595
+ # The extra values given here take precedence over values defined on the client or passed to this method.
596
+ extra_headers: Headers | None = None,
597
+ extra_query: Query | None = None,
598
+ extra_body: Body | None = None,
599
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
600
+ ) -> ImagesResponse:
601
+ """
602
+ Creates an image given a prompt.
603
+ [Learn more](https://platform.openai.com/docs/guides/images).
604
+
605
+ Args:
606
+ prompt: A text description of the desired image(s). The maximum length is 32000
607
+ characters for `gpt-image-1`, 1000 characters for `dall-e-2` and 4000 characters
608
+ for `dall-e-3`.
609
+
610
+ background: Allows to set transparency for the background of the generated image(s). This
611
+ parameter is only supported for `gpt-image-1`. Must be one of `transparent`,
612
+ `opaque` or `auto` (default value). When `auto` is used, the model will
613
+ automatically determine the best background for the image.
614
+
615
+ If `transparent`, the output format needs to support transparency, so it should
616
+ be set to either `png` (default value) or `webp`.
617
+
618
+ model: The model to use for image generation. One of `dall-e-2`, `dall-e-3`, or
619
+ `gpt-image-1`. Defaults to `dall-e-2` unless a parameter specific to
620
+ `gpt-image-1` is used.
621
+
622
+ moderation: Control the content-moderation level for images generated by `gpt-image-1`. Must
623
+ be either `low` for less restrictive filtering or `auto` (default value).
624
+
625
+ n: The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only
626
+ `n=1` is supported.
627
+
628
+ output_compression: The compression level (0-100%) for the generated images. This parameter is only
629
+ supported for `gpt-image-1` with the `webp` or `jpeg` output formats, and
630
+ defaults to 100.
631
+
632
+ output_format: The format in which the generated images are returned. This parameter is only
633
+ supported for `gpt-image-1`. Must be one of `png`, `jpeg`, or `webp`.
634
+
635
+ quality: The quality of the image that will be generated.
636
+
637
+ - `auto` (default value) will automatically select the best quality for the
638
+ given model.
639
+ - `high`, `medium` and `low` are supported for `gpt-image-1`.
640
+ - `hd` and `standard` are supported for `dall-e-3`.
641
+ - `standard` is the only option for `dall-e-2`.
642
+
643
+ response_format: The format in which generated images with `dall-e-2` and `dall-e-3` are
644
+ returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes
645
+ after the image has been generated. This parameter isn't supported for
646
+ `gpt-image-1` which will always return base64-encoded images.
647
+
648
+ size: The size of the generated images. Must be one of `1024x1024`, `1536x1024`
649
+ (landscape), `1024x1536` (portrait), or `auto` (default value) for
650
+ `gpt-image-1`, one of `256x256`, `512x512`, or `1024x1024` for `dall-e-2`, and
651
+ one of `1024x1024`, `1792x1024`, or `1024x1792` for `dall-e-3`.
652
+
653
+ style: The style of the generated images. This parameter is only supported for
654
+ `dall-e-3`. Must be one of `vivid` or `natural`. Vivid causes the model to lean
655
+ towards generating hyper-real and dramatic images. Natural causes the model to
656
+ produce more natural, less hyper-real looking images.
657
+
658
+ user: A unique identifier representing your end-user, which can help OpenAI to monitor
659
+ and detect abuse.
660
+ [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids).
661
+
662
+ extra_headers: Send extra headers
663
+
664
+ extra_query: Add additional query parameters to the request
665
+
666
+ extra_body: Add additional JSON properties to the request
667
+
668
+ timeout: Override the client-level default timeout for this request, in seconds
669
+ """
670
+ return await self._post(
671
+ "/images/generations",
672
+ body=await async_maybe_transform(
673
+ {
674
+ "prompt": prompt,
675
+ "background": background,
676
+ "model": model,
677
+ "moderation": moderation,
678
+ "n": n,
679
+ "output_compression": output_compression,
680
+ "output_format": output_format,
681
+ "quality": quality,
682
+ "response_format": response_format,
683
+ "size": size,
684
+ "style": style,
685
+ "user": user,
686
+ },
687
+ image_generate_params.ImageGenerateParams,
688
+ ),
689
+ options=make_request_options(
690
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
691
+ ),
692
+ cast_to=ImagesResponse,
693
+ )
694
+
695
+
696
+ class ImagesWithRawResponse:
697
+ def __init__(self, images: Images) -> None:
698
+ self._images = images
699
+
700
+ self.create_variation = _legacy_response.to_raw_response_wrapper(
701
+ images.create_variation,
702
+ )
703
+ self.edit = _legacy_response.to_raw_response_wrapper(
704
+ images.edit,
705
+ )
706
+ self.generate = _legacy_response.to_raw_response_wrapper(
707
+ images.generate,
708
+ )
709
+
710
+
711
+ class AsyncImagesWithRawResponse:
712
+ def __init__(self, images: AsyncImages) -> None:
713
+ self._images = images
714
+
715
+ self.create_variation = _legacy_response.async_to_raw_response_wrapper(
716
+ images.create_variation,
717
+ )
718
+ self.edit = _legacy_response.async_to_raw_response_wrapper(
719
+ images.edit,
720
+ )
721
+ self.generate = _legacy_response.async_to_raw_response_wrapper(
722
+ images.generate,
723
+ )
724
+
725
+
726
+ class ImagesWithStreamingResponse:
727
+ def __init__(self, images: Images) -> None:
728
+ self._images = images
729
+
730
+ self.create_variation = to_streamed_response_wrapper(
731
+ images.create_variation,
732
+ )
733
+ self.edit = to_streamed_response_wrapper(
734
+ images.edit,
735
+ )
736
+ self.generate = to_streamed_response_wrapper(
737
+ images.generate,
738
+ )
739
+
740
+
741
+ class AsyncImagesWithStreamingResponse:
742
+ def __init__(self, images: AsyncImages) -> None:
743
+ self._images = images
744
+
745
+ self.create_variation = async_to_streamed_response_wrapper(
746
+ images.create_variation,
747
+ )
748
+ self.edit = async_to_streamed_response_wrapper(
749
+ images.edit,
750
+ )
751
+ self.generate = async_to_streamed_response_wrapper(
752
+ images.generate,
753
+ )
python_embeded/Lib/site-packages/openai/resources/models.py ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from __future__ import annotations
4
+
5
+ import httpx
6
+
7
+ from .. import _legacy_response
8
+ from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven
9
+ from .._compat import cached_property
10
+ from .._resource import SyncAPIResource, AsyncAPIResource
11
+ from .._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper
12
+ from ..pagination import SyncPage, AsyncPage
13
+ from ..types.model import Model
14
+ from .._base_client import (
15
+ AsyncPaginator,
16
+ make_request_options,
17
+ )
18
+ from ..types.model_deleted import ModelDeleted
19
+
20
+ __all__ = ["Models", "AsyncModels"]
21
+
22
+
23
+ class Models(SyncAPIResource):
24
+ @cached_property
25
+ def with_raw_response(self) -> ModelsWithRawResponse:
26
+ """
27
+ This property can be used as a prefix for any HTTP method call to return
28
+ the raw response object instead of the parsed content.
29
+
30
+ For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
31
+ """
32
+ return ModelsWithRawResponse(self)
33
+
34
+ @cached_property
35
+ def with_streaming_response(self) -> ModelsWithStreamingResponse:
36
+ """
37
+ An alternative to `.with_raw_response` that doesn't eagerly read the response body.
38
+
39
+ For more information, see https://www.github.com/openai/openai-python#with_streaming_response
40
+ """
41
+ return ModelsWithStreamingResponse(self)
42
+
43
+ def retrieve(
44
+ self,
45
+ model: str,
46
+ *,
47
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
48
+ # The extra values given here take precedence over values defined on the client or passed to this method.
49
+ extra_headers: Headers | None = None,
50
+ extra_query: Query | None = None,
51
+ extra_body: Body | None = None,
52
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
53
+ ) -> Model:
54
+ """
55
+ Retrieves a model instance, providing basic information about the model such as
56
+ the owner and permissioning.
57
+
58
+ Args:
59
+ extra_headers: Send extra headers
60
+
61
+ extra_query: Add additional query parameters to the request
62
+
63
+ extra_body: Add additional JSON properties to the request
64
+
65
+ timeout: Override the client-level default timeout for this request, in seconds
66
+ """
67
+ if not model:
68
+ raise ValueError(f"Expected a non-empty value for `model` but received {model!r}")
69
+ return self._get(
70
+ f"/models/{model}",
71
+ options=make_request_options(
72
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
73
+ ),
74
+ cast_to=Model,
75
+ )
76
+
77
+ def list(
78
+ self,
79
+ *,
80
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
81
+ # The extra values given here take precedence over values defined on the client or passed to this method.
82
+ extra_headers: Headers | None = None,
83
+ extra_query: Query | None = None,
84
+ extra_body: Body | None = None,
85
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
86
+ ) -> SyncPage[Model]:
87
+ """
88
+ Lists the currently available models, and provides basic information about each
89
+ one such as the owner and availability.
90
+ """
91
+ return self._get_api_list(
92
+ "/models",
93
+ page=SyncPage[Model],
94
+ options=make_request_options(
95
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
96
+ ),
97
+ model=Model,
98
+ )
99
+
100
+ def delete(
101
+ self,
102
+ model: str,
103
+ *,
104
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
105
+ # The extra values given here take precedence over values defined on the client or passed to this method.
106
+ extra_headers: Headers | None = None,
107
+ extra_query: Query | None = None,
108
+ extra_body: Body | None = None,
109
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
110
+ ) -> ModelDeleted:
111
+ """Delete a fine-tuned model.
112
+
113
+ You must have the Owner role in your organization to
114
+ delete a model.
115
+
116
+ Args:
117
+ extra_headers: Send extra headers
118
+
119
+ extra_query: Add additional query parameters to the request
120
+
121
+ extra_body: Add additional JSON properties to the request
122
+
123
+ timeout: Override the client-level default timeout for this request, in seconds
124
+ """
125
+ if not model:
126
+ raise ValueError(f"Expected a non-empty value for `model` but received {model!r}")
127
+ return self._delete(
128
+ f"/models/{model}",
129
+ options=make_request_options(
130
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
131
+ ),
132
+ cast_to=ModelDeleted,
133
+ )
134
+
135
+
136
+ class AsyncModels(AsyncAPIResource):
137
+ @cached_property
138
+ def with_raw_response(self) -> AsyncModelsWithRawResponse:
139
+ """
140
+ This property can be used as a prefix for any HTTP method call to return
141
+ the raw response object instead of the parsed content.
142
+
143
+ For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
144
+ """
145
+ return AsyncModelsWithRawResponse(self)
146
+
147
+ @cached_property
148
+ def with_streaming_response(self) -> AsyncModelsWithStreamingResponse:
149
+ """
150
+ An alternative to `.with_raw_response` that doesn't eagerly read the response body.
151
+
152
+ For more information, see https://www.github.com/openai/openai-python#with_streaming_response
153
+ """
154
+ return AsyncModelsWithStreamingResponse(self)
155
+
156
+ async def retrieve(
157
+ self,
158
+ model: str,
159
+ *,
160
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
161
+ # The extra values given here take precedence over values defined on the client or passed to this method.
162
+ extra_headers: Headers | None = None,
163
+ extra_query: Query | None = None,
164
+ extra_body: Body | None = None,
165
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
166
+ ) -> Model:
167
+ """
168
+ Retrieves a model instance, providing basic information about the model such as
169
+ the owner and permissioning.
170
+
171
+ Args:
172
+ extra_headers: Send extra headers
173
+
174
+ extra_query: Add additional query parameters to the request
175
+
176
+ extra_body: Add additional JSON properties to the request
177
+
178
+ timeout: Override the client-level default timeout for this request, in seconds
179
+ """
180
+ if not model:
181
+ raise ValueError(f"Expected a non-empty value for `model` but received {model!r}")
182
+ return await self._get(
183
+ f"/models/{model}",
184
+ options=make_request_options(
185
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
186
+ ),
187
+ cast_to=Model,
188
+ )
189
+
190
+ def list(
191
+ self,
192
+ *,
193
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
194
+ # The extra values given here take precedence over values defined on the client or passed to this method.
195
+ extra_headers: Headers | None = None,
196
+ extra_query: Query | None = None,
197
+ extra_body: Body | None = None,
198
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
199
+ ) -> AsyncPaginator[Model, AsyncPage[Model]]:
200
+ """
201
+ Lists the currently available models, and provides basic information about each
202
+ one such as the owner and availability.
203
+ """
204
+ return self._get_api_list(
205
+ "/models",
206
+ page=AsyncPage[Model],
207
+ options=make_request_options(
208
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
209
+ ),
210
+ model=Model,
211
+ )
212
+
213
+ async def delete(
214
+ self,
215
+ model: str,
216
+ *,
217
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
218
+ # The extra values given here take precedence over values defined on the client or passed to this method.
219
+ extra_headers: Headers | None = None,
220
+ extra_query: Query | None = None,
221
+ extra_body: Body | None = None,
222
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
223
+ ) -> ModelDeleted:
224
+ """Delete a fine-tuned model.
225
+
226
+ You must have the Owner role in your organization to
227
+ delete a model.
228
+
229
+ Args:
230
+ extra_headers: Send extra headers
231
+
232
+ extra_query: Add additional query parameters to the request
233
+
234
+ extra_body: Add additional JSON properties to the request
235
+
236
+ timeout: Override the client-level default timeout for this request, in seconds
237
+ """
238
+ if not model:
239
+ raise ValueError(f"Expected a non-empty value for `model` but received {model!r}")
240
+ return await self._delete(
241
+ f"/models/{model}",
242
+ options=make_request_options(
243
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
244
+ ),
245
+ cast_to=ModelDeleted,
246
+ )
247
+
248
+
249
+ class ModelsWithRawResponse:
250
+ def __init__(self, models: Models) -> None:
251
+ self._models = models
252
+
253
+ self.retrieve = _legacy_response.to_raw_response_wrapper(
254
+ models.retrieve,
255
+ )
256
+ self.list = _legacy_response.to_raw_response_wrapper(
257
+ models.list,
258
+ )
259
+ self.delete = _legacy_response.to_raw_response_wrapper(
260
+ models.delete,
261
+ )
262
+
263
+
264
+ class AsyncModelsWithRawResponse:
265
+ def __init__(self, models: AsyncModels) -> None:
266
+ self._models = models
267
+
268
+ self.retrieve = _legacy_response.async_to_raw_response_wrapper(
269
+ models.retrieve,
270
+ )
271
+ self.list = _legacy_response.async_to_raw_response_wrapper(
272
+ models.list,
273
+ )
274
+ self.delete = _legacy_response.async_to_raw_response_wrapper(
275
+ models.delete,
276
+ )
277
+
278
+
279
+ class ModelsWithStreamingResponse:
280
+ def __init__(self, models: Models) -> None:
281
+ self._models = models
282
+
283
+ self.retrieve = to_streamed_response_wrapper(
284
+ models.retrieve,
285
+ )
286
+ self.list = to_streamed_response_wrapper(
287
+ models.list,
288
+ )
289
+ self.delete = to_streamed_response_wrapper(
290
+ models.delete,
291
+ )
292
+
293
+
294
+ class AsyncModelsWithStreamingResponse:
295
+ def __init__(self, models: AsyncModels) -> None:
296
+ self._models = models
297
+
298
+ self.retrieve = async_to_streamed_response_wrapper(
299
+ models.retrieve,
300
+ )
301
+ self.list = async_to_streamed_response_wrapper(
302
+ models.list,
303
+ )
304
+ self.delete = async_to_streamed_response_wrapper(
305
+ models.delete,
306
+ )
python_embeded/Lib/site-packages/openai/resources/moderations.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import List, Union, Iterable
6
+
7
+ import httpx
8
+
9
+ from .. import _legacy_response
10
+ from ..types import moderation_create_params
11
+ from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven
12
+ from .._utils import maybe_transform, async_maybe_transform
13
+ from .._compat import cached_property
14
+ from .._resource import SyncAPIResource, AsyncAPIResource
15
+ from .._response import to_streamed_response_wrapper, async_to_streamed_response_wrapper
16
+ from .._base_client import make_request_options
17
+ from ..types.moderation_model import ModerationModel
18
+ from ..types.moderation_create_response import ModerationCreateResponse
19
+ from ..types.moderation_multi_modal_input_param import ModerationMultiModalInputParam
20
+
21
+ __all__ = ["Moderations", "AsyncModerations"]
22
+
23
+
24
+ class Moderations(SyncAPIResource):
25
+ @cached_property
26
+ def with_raw_response(self) -> ModerationsWithRawResponse:
27
+ """
28
+ This property can be used as a prefix for any HTTP method call to return
29
+ the raw response object instead of the parsed content.
30
+
31
+ For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
32
+ """
33
+ return ModerationsWithRawResponse(self)
34
+
35
+ @cached_property
36
+ def with_streaming_response(self) -> ModerationsWithStreamingResponse:
37
+ """
38
+ An alternative to `.with_raw_response` that doesn't eagerly read the response body.
39
+
40
+ For more information, see https://www.github.com/openai/openai-python#with_streaming_response
41
+ """
42
+ return ModerationsWithStreamingResponse(self)
43
+
44
+ def create(
45
+ self,
46
+ *,
47
+ input: Union[str, List[str], Iterable[ModerationMultiModalInputParam]],
48
+ model: Union[str, ModerationModel] | NotGiven = NOT_GIVEN,
49
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
50
+ # The extra values given here take precedence over values defined on the client or passed to this method.
51
+ extra_headers: Headers | None = None,
52
+ extra_query: Query | None = None,
53
+ extra_body: Body | None = None,
54
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
55
+ ) -> ModerationCreateResponse:
56
+ """Classifies if text and/or image inputs are potentially harmful.
57
+
58
+ Learn more in
59
+ the [moderation guide](https://platform.openai.com/docs/guides/moderation).
60
+
61
+ Args:
62
+ input: Input (or inputs) to classify. Can be a single string, an array of strings, or
63
+ an array of multi-modal input objects similar to other models.
64
+
65
+ model: The content moderation model you would like to use. Learn more in
66
+ [the moderation guide](https://platform.openai.com/docs/guides/moderation), and
67
+ learn about available models
68
+ [here](https://platform.openai.com/docs/models#moderation).
69
+
70
+ extra_headers: Send extra headers
71
+
72
+ extra_query: Add additional query parameters to the request
73
+
74
+ extra_body: Add additional JSON properties to the request
75
+
76
+ timeout: Override the client-level default timeout for this request, in seconds
77
+ """
78
+ return self._post(
79
+ "/moderations",
80
+ body=maybe_transform(
81
+ {
82
+ "input": input,
83
+ "model": model,
84
+ },
85
+ moderation_create_params.ModerationCreateParams,
86
+ ),
87
+ options=make_request_options(
88
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
89
+ ),
90
+ cast_to=ModerationCreateResponse,
91
+ )
92
+
93
+
94
+ class AsyncModerations(AsyncAPIResource):
95
+ @cached_property
96
+ def with_raw_response(self) -> AsyncModerationsWithRawResponse:
97
+ """
98
+ This property can be used as a prefix for any HTTP method call to return
99
+ the raw response object instead of the parsed content.
100
+
101
+ For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
102
+ """
103
+ return AsyncModerationsWithRawResponse(self)
104
+
105
+ @cached_property
106
+ def with_streaming_response(self) -> AsyncModerationsWithStreamingResponse:
107
+ """
108
+ An alternative to `.with_raw_response` that doesn't eagerly read the response body.
109
+
110
+ For more information, see https://www.github.com/openai/openai-python#with_streaming_response
111
+ """
112
+ return AsyncModerationsWithStreamingResponse(self)
113
+
114
+ async def create(
115
+ self,
116
+ *,
117
+ input: Union[str, List[str], Iterable[ModerationMultiModalInputParam]],
118
+ model: Union[str, ModerationModel] | NotGiven = NOT_GIVEN,
119
+ # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
120
+ # The extra values given here take precedence over values defined on the client or passed to this method.
121
+ extra_headers: Headers | None = None,
122
+ extra_query: Query | None = None,
123
+ extra_body: Body | None = None,
124
+ timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
125
+ ) -> ModerationCreateResponse:
126
+ """Classifies if text and/or image inputs are potentially harmful.
127
+
128
+ Learn more in
129
+ the [moderation guide](https://platform.openai.com/docs/guides/moderation).
130
+
131
+ Args:
132
+ input: Input (or inputs) to classify. Can be a single string, an array of strings, or
133
+ an array of multi-modal input objects similar to other models.
134
+
135
+ model: The content moderation model you would like to use. Learn more in
136
+ [the moderation guide](https://platform.openai.com/docs/guides/moderation), and
137
+ learn about available models
138
+ [here](https://platform.openai.com/docs/models#moderation).
139
+
140
+ extra_headers: Send extra headers
141
+
142
+ extra_query: Add additional query parameters to the request
143
+
144
+ extra_body: Add additional JSON properties to the request
145
+
146
+ timeout: Override the client-level default timeout for this request, in seconds
147
+ """
148
+ return await self._post(
149
+ "/moderations",
150
+ body=await async_maybe_transform(
151
+ {
152
+ "input": input,
153
+ "model": model,
154
+ },
155
+ moderation_create_params.ModerationCreateParams,
156
+ ),
157
+ options=make_request_options(
158
+ extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
159
+ ),
160
+ cast_to=ModerationCreateResponse,
161
+ )
162
+
163
+
164
+ class ModerationsWithRawResponse:
165
+ def __init__(self, moderations: Moderations) -> None:
166
+ self._moderations = moderations
167
+
168
+ self.create = _legacy_response.to_raw_response_wrapper(
169
+ moderations.create,
170
+ )
171
+
172
+
173
+ class AsyncModerationsWithRawResponse:
174
+ def __init__(self, moderations: AsyncModerations) -> None:
175
+ self._moderations = moderations
176
+
177
+ self.create = _legacy_response.async_to_raw_response_wrapper(
178
+ moderations.create,
179
+ )
180
+
181
+
182
+ class ModerationsWithStreamingResponse:
183
+ def __init__(self, moderations: Moderations) -> None:
184
+ self._moderations = moderations
185
+
186
+ self.create = to_streamed_response_wrapper(
187
+ moderations.create,
188
+ )
189
+
190
+
191
+ class AsyncModerationsWithStreamingResponse:
192
+ def __init__(self, moderations: AsyncModerations) -> None:
193
+ self._moderations = moderations
194
+
195
+ self.create = async_to_streamed_response_wrapper(
196
+ moderations.create,
197
+ )
python_embeded/Lib/site-packages/openai/resources/webhooks.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from __future__ import annotations
4
+
5
+ import hmac
6
+ import json
7
+ import time
8
+ import base64
9
+ import hashlib
10
+ from typing import cast
11
+
12
+ from .._types import HeadersLike
13
+ from .._utils import get_required_header
14
+ from .._models import construct_type
15
+ from .._resource import SyncAPIResource, AsyncAPIResource
16
+ from .._exceptions import InvalidWebhookSignatureError
17
+ from ..types.webhooks.unwrap_webhook_event import UnwrapWebhookEvent
18
+
19
+ __all__ = ["Webhooks", "AsyncWebhooks"]
20
+
21
+
22
+ class Webhooks(SyncAPIResource):
23
+ def unwrap(
24
+ self,
25
+ payload: str | bytes,
26
+ headers: HeadersLike,
27
+ *,
28
+ secret: str | None = None,
29
+ ) -> UnwrapWebhookEvent:
30
+ """Validates that the given payload was sent by OpenAI and parses the payload."""
31
+ if secret is None:
32
+ secret = self._client.webhook_secret
33
+
34
+ self.verify_signature(payload=payload, headers=headers, secret=secret)
35
+
36
+ return cast(
37
+ UnwrapWebhookEvent,
38
+ construct_type(
39
+ type_=UnwrapWebhookEvent,
40
+ value=json.loads(payload),
41
+ ),
42
+ )
43
+
44
+ def verify_signature(
45
+ self,
46
+ payload: str | bytes,
47
+ headers: HeadersLike,
48
+ *,
49
+ secret: str | None = None,
50
+ tolerance: int = 300,
51
+ ) -> None:
52
+ """Validates whether or not the webhook payload was sent by OpenAI.
53
+
54
+ Args:
55
+ payload: The webhook payload
56
+ headers: The webhook headers
57
+ secret: The webhook secret (optional, will use client secret if not provided)
58
+ tolerance: Maximum age of the webhook in seconds (default: 300 = 5 minutes)
59
+ """
60
+ if secret is None:
61
+ secret = self._client.webhook_secret
62
+
63
+ if secret is None:
64
+ raise ValueError(
65
+ "The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, "
66
+ "on the client class, OpenAI(webhook_secret='123'), or passed to this function"
67
+ )
68
+
69
+ signature_header = get_required_header(headers, "webhook-signature")
70
+ timestamp = get_required_header(headers, "webhook-timestamp")
71
+ webhook_id = get_required_header(headers, "webhook-id")
72
+
73
+ # Validate timestamp to prevent replay attacks
74
+ try:
75
+ timestamp_seconds = int(timestamp)
76
+ except ValueError:
77
+ raise InvalidWebhookSignatureError("Invalid webhook timestamp format") from None
78
+
79
+ now = int(time.time())
80
+
81
+ if now - timestamp_seconds > tolerance:
82
+ raise InvalidWebhookSignatureError("Webhook timestamp is too old") from None
83
+
84
+ if timestamp_seconds > now + tolerance:
85
+ raise InvalidWebhookSignatureError("Webhook timestamp is too new") from None
86
+
87
+ # Extract signatures from v1,<base64> format
88
+ # The signature header can have multiple values, separated by spaces.
89
+ # Each value is in the format v1,<base64>. We should accept if any match.
90
+ signatures: list[str] = []
91
+ for part in signature_header.split():
92
+ if part.startswith("v1,"):
93
+ signatures.append(part[3:])
94
+ else:
95
+ signatures.append(part)
96
+
97
+ # Decode the secret if it starts with whsec_
98
+ if secret.startswith("whsec_"):
99
+ decoded_secret = base64.b64decode(secret[6:])
100
+ else:
101
+ decoded_secret = secret.encode()
102
+
103
+ body = payload.decode("utf-8") if isinstance(payload, bytes) else payload
104
+
105
+ # Prepare the signed payload (OpenAI uses webhookId.timestamp.payload format)
106
+ signed_payload = f"{webhook_id}.{timestamp}.{body}"
107
+ expected_signature = base64.b64encode(
108
+ hmac.new(decoded_secret, signed_payload.encode(), hashlib.sha256).digest()
109
+ ).decode()
110
+
111
+ # Accept if any signature matches
112
+ if not any(hmac.compare_digest(expected_signature, sig) for sig in signatures):
113
+ raise InvalidWebhookSignatureError(
114
+ "The given webhook signature does not match the expected signature"
115
+ ) from None
116
+
117
+
118
+ class AsyncWebhooks(AsyncAPIResource):
119
+ def unwrap(
120
+ self,
121
+ payload: str | bytes,
122
+ headers: HeadersLike,
123
+ *,
124
+ secret: str | None = None,
125
+ ) -> UnwrapWebhookEvent:
126
+ """Validates that the given payload was sent by OpenAI and parses the payload."""
127
+ if secret is None:
128
+ secret = self._client.webhook_secret
129
+
130
+ self.verify_signature(payload=payload, headers=headers, secret=secret)
131
+
132
+ body = payload.decode("utf-8") if isinstance(payload, bytes) else payload
133
+ return cast(
134
+ UnwrapWebhookEvent,
135
+ construct_type(
136
+ type_=UnwrapWebhookEvent,
137
+ value=json.loads(body),
138
+ ),
139
+ )
140
+
141
+ def verify_signature(
142
+ self,
143
+ payload: str | bytes,
144
+ headers: HeadersLike,
145
+ *,
146
+ secret: str | None = None,
147
+ tolerance: int = 300,
148
+ ) -> None:
149
+ """Validates whether or not the webhook payload was sent by OpenAI.
150
+
151
+ Args:
152
+ payload: The webhook payload
153
+ headers: The webhook headers
154
+ secret: The webhook secret (optional, will use client secret if not provided)
155
+ tolerance: Maximum age of the webhook in seconds (default: 300 = 5 minutes)
156
+ """
157
+ if secret is None:
158
+ secret = self._client.webhook_secret
159
+
160
+ if secret is None:
161
+ raise ValueError(
162
+ "The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, "
163
+ "on the client class, OpenAI(webhook_secret='123'), or passed to this function"
164
+ ) from None
165
+
166
+ signature_header = get_required_header(headers, "webhook-signature")
167
+ timestamp = get_required_header(headers, "webhook-timestamp")
168
+ webhook_id = get_required_header(headers, "webhook-id")
169
+
170
+ # Validate timestamp to prevent replay attacks
171
+ try:
172
+ timestamp_seconds = int(timestamp)
173
+ except ValueError:
174
+ raise InvalidWebhookSignatureError("Invalid webhook timestamp format") from None
175
+
176
+ now = int(time.time())
177
+
178
+ if now - timestamp_seconds > tolerance:
179
+ raise InvalidWebhookSignatureError("Webhook timestamp is too old") from None
180
+
181
+ if timestamp_seconds > now + tolerance:
182
+ raise InvalidWebhookSignatureError("Webhook timestamp is too new") from None
183
+
184
+ # Extract signatures from v1,<base64> format
185
+ # The signature header can have multiple values, separated by spaces.
186
+ # Each value is in the format v1,<base64>. We should accept if any match.
187
+ signatures: list[str] = []
188
+ for part in signature_header.split():
189
+ if part.startswith("v1,"):
190
+ signatures.append(part[3:])
191
+ else:
192
+ signatures.append(part)
193
+
194
+ # Decode the secret if it starts with whsec_
195
+ if secret.startswith("whsec_"):
196
+ decoded_secret = base64.b64decode(secret[6:])
197
+ else:
198
+ decoded_secret = secret.encode()
199
+
200
+ body = payload.decode("utf-8") if isinstance(payload, bytes) else payload
201
+
202
+ # Prepare the signed payload (OpenAI uses webhookId.timestamp.payload format)
203
+ signed_payload = f"{webhook_id}.{timestamp}.{body}"
204
+ expected_signature = base64.b64encode(
205
+ hmac.new(decoded_secret, signed_payload.encode(), hashlib.sha256).digest()
206
+ ).decode()
207
+
208
+ # Accept if any signature matches
209
+ if not any(hmac.compare_digest(expected_signature, sig) for sig in signatures):
210
+ raise InvalidWebhookSignatureError("The given webhook signature does not match the expected signature")
python_embeded/Lib/site-packages/openai/types/__init__.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from __future__ import annotations
4
+
5
+ from .batch import Batch as Batch
6
+ from .image import Image as Image
7
+ from .model import Model as Model
8
+ from .shared import (
9
+ Metadata as Metadata,
10
+ AllModels as AllModels,
11
+ ChatModel as ChatModel,
12
+ Reasoning as Reasoning,
13
+ ErrorObject as ErrorObject,
14
+ CompoundFilter as CompoundFilter,
15
+ ResponsesModel as ResponsesModel,
16
+ ReasoningEffort as ReasoningEffort,
17
+ ComparisonFilter as ComparisonFilter,
18
+ FunctionDefinition as FunctionDefinition,
19
+ FunctionParameters as FunctionParameters,
20
+ ResponseFormatText as ResponseFormatText,
21
+ ResponseFormatJSONObject as ResponseFormatJSONObject,
22
+ ResponseFormatJSONSchema as ResponseFormatJSONSchema,
23
+ )
24
+ from .upload import Upload as Upload
25
+ from .embedding import Embedding as Embedding
26
+ from .chat_model import ChatModel as ChatModel
27
+ from .completion import Completion as Completion
28
+ from .moderation import Moderation as Moderation
29
+ from .audio_model import AudioModel as AudioModel
30
+ from .batch_error import BatchError as BatchError
31
+ from .file_object import FileObject as FileObject
32
+ from .image_model import ImageModel as ImageModel
33
+ from .file_content import FileContent as FileContent
34
+ from .file_deleted import FileDeleted as FileDeleted
35
+ from .file_purpose import FilePurpose as FilePurpose
36
+ from .vector_store import VectorStore as VectorStore
37
+ from .model_deleted import ModelDeleted as ModelDeleted
38
+ from .embedding_model import EmbeddingModel as EmbeddingModel
39
+ from .images_response import ImagesResponse as ImagesResponse
40
+ from .completion_usage import CompletionUsage as CompletionUsage
41
+ from .eval_list_params import EvalListParams as EvalListParams
42
+ from .file_list_params import FileListParams as FileListParams
43
+ from .moderation_model import ModerationModel as ModerationModel
44
+ from .batch_list_params import BatchListParams as BatchListParams
45
+ from .completion_choice import CompletionChoice as CompletionChoice
46
+ from .image_edit_params import ImageEditParams as ImageEditParams
47
+ from .eval_create_params import EvalCreateParams as EvalCreateParams
48
+ from .eval_list_response import EvalListResponse as EvalListResponse
49
+ from .eval_update_params import EvalUpdateParams as EvalUpdateParams
50
+ from .file_create_params import FileCreateParams as FileCreateParams
51
+ from .batch_create_params import BatchCreateParams as BatchCreateParams
52
+ from .batch_request_counts import BatchRequestCounts as BatchRequestCounts
53
+ from .eval_create_response import EvalCreateResponse as EvalCreateResponse
54
+ from .eval_delete_response import EvalDeleteResponse as EvalDeleteResponse
55
+ from .eval_update_response import EvalUpdateResponse as EvalUpdateResponse
56
+ from .upload_create_params import UploadCreateParams as UploadCreateParams
57
+ from .vector_store_deleted import VectorStoreDeleted as VectorStoreDeleted
58
+ from .audio_response_format import AudioResponseFormat as AudioResponseFormat
59
+ from .container_list_params import ContainerListParams as ContainerListParams
60
+ from .image_generate_params import ImageGenerateParams as ImageGenerateParams
61
+ from .eval_retrieve_response import EvalRetrieveResponse as EvalRetrieveResponse
62
+ from .file_chunking_strategy import FileChunkingStrategy as FileChunkingStrategy
63
+ from .upload_complete_params import UploadCompleteParams as UploadCompleteParams
64
+ from .container_create_params import ContainerCreateParams as ContainerCreateParams
65
+ from .container_list_response import ContainerListResponse as ContainerListResponse
66
+ from .embedding_create_params import EmbeddingCreateParams as EmbeddingCreateParams
67
+ from .completion_create_params import CompletionCreateParams as CompletionCreateParams
68
+ from .moderation_create_params import ModerationCreateParams as ModerationCreateParams
69
+ from .vector_store_list_params import VectorStoreListParams as VectorStoreListParams
70
+ from .container_create_response import ContainerCreateResponse as ContainerCreateResponse
71
+ from .create_embedding_response import CreateEmbeddingResponse as CreateEmbeddingResponse
72
+ from .moderation_create_response import ModerationCreateResponse as ModerationCreateResponse
73
+ from .vector_store_create_params import VectorStoreCreateParams as VectorStoreCreateParams
74
+ from .vector_store_search_params import VectorStoreSearchParams as VectorStoreSearchParams
75
+ from .vector_store_update_params import VectorStoreUpdateParams as VectorStoreUpdateParams
76
+ from .container_retrieve_response import ContainerRetrieveResponse as ContainerRetrieveResponse
77
+ from .moderation_text_input_param import ModerationTextInputParam as ModerationTextInputParam
78
+ from .file_chunking_strategy_param import FileChunkingStrategyParam as FileChunkingStrategyParam
79
+ from .vector_store_search_response import VectorStoreSearchResponse as VectorStoreSearchResponse
80
+ from .websocket_connection_options import WebsocketConnectionOptions as WebsocketConnectionOptions
81
+ from .image_create_variation_params import ImageCreateVariationParams as ImageCreateVariationParams
82
+ from .static_file_chunking_strategy import StaticFileChunkingStrategy as StaticFileChunkingStrategy
83
+ from .eval_custom_data_source_config import EvalCustomDataSourceConfig as EvalCustomDataSourceConfig
84
+ from .moderation_image_url_input_param import ModerationImageURLInputParam as ModerationImageURLInputParam
85
+ from .auto_file_chunking_strategy_param import AutoFileChunkingStrategyParam as AutoFileChunkingStrategyParam
86
+ from .moderation_multi_modal_input_param import ModerationMultiModalInputParam as ModerationMultiModalInputParam
87
+ from .other_file_chunking_strategy_object import OtherFileChunkingStrategyObject as OtherFileChunkingStrategyObject
88
+ from .static_file_chunking_strategy_param import StaticFileChunkingStrategyParam as StaticFileChunkingStrategyParam
89
+ from .static_file_chunking_strategy_object import StaticFileChunkingStrategyObject as StaticFileChunkingStrategyObject
90
+ from .eval_stored_completions_data_source_config import (
91
+ EvalStoredCompletionsDataSourceConfig as EvalStoredCompletionsDataSourceConfig,
92
+ )
93
+ from .static_file_chunking_strategy_object_param import (
94
+ StaticFileChunkingStrategyObjectParam as StaticFileChunkingStrategyObjectParam,
95
+ )
python_embeded/Lib/site-packages/openai/types/audio/__init__.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from __future__ import annotations
4
+
5
+ from .translation import Translation as Translation
6
+ from .speech_model import SpeechModel as SpeechModel
7
+ from .transcription import Transcription as Transcription
8
+ from .transcription_word import TranscriptionWord as TranscriptionWord
9
+ from .translation_verbose import TranslationVerbose as TranslationVerbose
10
+ from .speech_create_params import SpeechCreateParams as SpeechCreateParams
11
+ from .transcription_include import TranscriptionInclude as TranscriptionInclude
12
+ from .transcription_segment import TranscriptionSegment as TranscriptionSegment
13
+ from .transcription_verbose import TranscriptionVerbose as TranscriptionVerbose
14
+ from .translation_create_params import TranslationCreateParams as TranslationCreateParams
15
+ from .transcription_stream_event import TranscriptionStreamEvent as TranscriptionStreamEvent
16
+ from .transcription_create_params import TranscriptionCreateParams as TranscriptionCreateParams
17
+ from .translation_create_response import TranslationCreateResponse as TranslationCreateResponse
18
+ from .transcription_create_response import TranscriptionCreateResponse as TranscriptionCreateResponse
19
+ from .transcription_text_done_event import TranscriptionTextDoneEvent as TranscriptionTextDoneEvent
20
+ from .transcription_text_delta_event import TranscriptionTextDeltaEvent as TranscriptionTextDeltaEvent
python_embeded/Lib/site-packages/openai/types/audio/speech_create_params.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Union
6
+ from typing_extensions import Literal, Required, TypedDict
7
+
8
+ from .speech_model import SpeechModel
9
+
10
+ __all__ = ["SpeechCreateParams"]
11
+
12
+
13
+ class SpeechCreateParams(TypedDict, total=False):
14
+ input: Required[str]
15
+ """The text to generate audio for. The maximum length is 4096 characters."""
16
+
17
+ model: Required[Union[str, SpeechModel]]
18
+ """
19
+ One of the available [TTS models](https://platform.openai.com/docs/models#tts):
20
+ `tts-1`, `tts-1-hd` or `gpt-4o-mini-tts`.
21
+ """
22
+
23
+ voice: Required[
24
+ Union[
25
+ str, Literal["alloy", "ash", "ballad", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer", "verse"]
26
+ ]
27
+ ]
28
+ """The voice to use when generating the audio.
29
+
30
+ Supported voices are `alloy`, `ash`, `ballad`, `coral`, `echo`, `fable`, `onyx`,
31
+ `nova`, `sage`, `shimmer`, and `verse`. Previews of the voices are available in
32
+ the
33
+ [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech#voice-options).
34
+ """
35
+
36
+ instructions: str
37
+ """Control the voice of your generated audio with additional instructions.
38
+
39
+ Does not work with `tts-1` or `tts-1-hd`.
40
+ """
41
+
42
+ response_format: Literal["mp3", "opus", "aac", "flac", "wav", "pcm"]
43
+ """The format to audio in.
44
+
45
+ Supported formats are `mp3`, `opus`, `aac`, `flac`, `wav`, and `pcm`.
46
+ """
47
+
48
+ speed: float
49
+ """The speed of the generated audio.
50
+
51
+ Select a value from `0.25` to `4.0`. `1.0` is the default.
52
+ """
53
+
54
+ stream_format: Literal["sse", "audio"]
55
+ """The format to stream the audio in.
56
+
57
+ Supported formats are `sse` and `audio`. `sse` is not supported for `tts-1` or
58
+ `tts-1-hd`.
59
+ """
python_embeded/Lib/site-packages/openai/types/audio/speech_model.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from typing_extensions import Literal, TypeAlias
4
+
5
+ __all__ = ["SpeechModel"]
6
+
7
+ SpeechModel: TypeAlias = Literal["tts-1", "tts-1-hd", "gpt-4o-mini-tts"]
python_embeded/Lib/site-packages/openai/types/audio/transcription.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from typing import List, Union, Optional
4
+ from typing_extensions import Literal, Annotated, TypeAlias
5
+
6
+ from ..._utils import PropertyInfo
7
+ from ..._models import BaseModel
8
+
9
+ __all__ = ["Transcription", "Logprob", "Usage", "UsageTokens", "UsageTokensInputTokenDetails", "UsageDuration"]
10
+
11
+
12
+ class Logprob(BaseModel):
13
+ token: Optional[str] = None
14
+ """The token in the transcription."""
15
+
16
+ bytes: Optional[List[float]] = None
17
+ """The bytes of the token."""
18
+
19
+ logprob: Optional[float] = None
20
+ """The log probability of the token."""
21
+
22
+
23
+ class UsageTokensInputTokenDetails(BaseModel):
24
+ audio_tokens: Optional[int] = None
25
+ """Number of audio tokens billed for this request."""
26
+
27
+ text_tokens: Optional[int] = None
28
+ """Number of text tokens billed for this request."""
29
+
30
+
31
+ class UsageTokens(BaseModel):
32
+ input_tokens: int
33
+ """Number of input tokens billed for this request."""
34
+
35
+ output_tokens: int
36
+ """Number of output tokens generated."""
37
+
38
+ total_tokens: int
39
+ """Total number of tokens used (input + output)."""
40
+
41
+ type: Literal["tokens"]
42
+ """The type of the usage object. Always `tokens` for this variant."""
43
+
44
+ input_token_details: Optional[UsageTokensInputTokenDetails] = None
45
+ """Details about the input tokens billed for this request."""
46
+
47
+
48
+ class UsageDuration(BaseModel):
49
+ duration: float
50
+ """Duration of the input audio in seconds."""
51
+
52
+ type: Literal["duration"]
53
+ """The type of the usage object. Always `duration` for this variant."""
54
+
55
+
56
+ Usage: TypeAlias = Annotated[Union[UsageTokens, UsageDuration], PropertyInfo(discriminator="type")]
57
+
58
+
59
+ class Transcription(BaseModel):
60
+ text: str
61
+ """The transcribed text."""
62
+
63
+ logprobs: Optional[List[Logprob]] = None
64
+ """The log probabilities of the tokens in the transcription.
65
+
66
+ Only returned with the models `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`
67
+ if `logprobs` is added to the `include` array.
68
+ """
69
+
70
+ usage: Optional[Usage] = None
71
+ """Token usage statistics for the request."""
python_embeded/Lib/site-packages/openai/types/audio/transcription_create_params.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import List, Union, Optional
6
+ from typing_extensions import Literal, Required, TypeAlias, TypedDict
7
+
8
+ from ..._types import FileTypes
9
+ from ..audio_model import AudioModel
10
+ from .transcription_include import TranscriptionInclude
11
+ from ..audio_response_format import AudioResponseFormat
12
+
13
+ __all__ = [
14
+ "TranscriptionCreateParamsBase",
15
+ "ChunkingStrategy",
16
+ "ChunkingStrategyVadConfig",
17
+ "TranscriptionCreateParamsNonStreaming",
18
+ "TranscriptionCreateParamsStreaming",
19
+ ]
20
+
21
+
22
+ class TranscriptionCreateParamsBase(TypedDict, total=False):
23
+ file: Required[FileTypes]
24
+ """
25
+ The audio file object (not file name) to transcribe, in one of these formats:
26
+ flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm.
27
+ """
28
+
29
+ model: Required[Union[str, AudioModel]]
30
+ """ID of the model to use.
31
+
32
+ The options are `gpt-4o-transcribe`, `gpt-4o-mini-transcribe`, and `whisper-1`
33
+ (which is powered by our open source Whisper V2 model).
34
+ """
35
+
36
+ chunking_strategy: Optional[ChunkingStrategy]
37
+ """Controls how the audio is cut into chunks.
38
+
39
+ When set to `"auto"`, the server first normalizes loudness and then uses voice
40
+ activity detection (VAD) to choose boundaries. `server_vad` object can be
41
+ provided to tweak VAD detection parameters manually. If unset, the audio is
42
+ transcribed as a single block.
43
+ """
44
+
45
+ include: List[TranscriptionInclude]
46
+ """Additional information to include in the transcription response.
47
+
48
+ `logprobs` will return the log probabilities of the tokens in the response to
49
+ understand the model's confidence in the transcription. `logprobs` only works
50
+ with response_format set to `json` and only with the models `gpt-4o-transcribe`
51
+ and `gpt-4o-mini-transcribe`.
52
+ """
53
+
54
+ language: str
55
+ """The language of the input audio.
56
+
57
+ Supplying the input language in
58
+ [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`)
59
+ format will improve accuracy and latency.
60
+ """
61
+
62
+ prompt: str
63
+ """An optional text to guide the model's style or continue a previous audio
64
+ segment.
65
+
66
+ The [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting)
67
+ should match the audio language.
68
+ """
69
+
70
+ response_format: AudioResponseFormat
71
+ """
72
+ The format of the output, in one of these options: `json`, `text`, `srt`,
73
+ `verbose_json`, or `vtt`. For `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`,
74
+ the only supported format is `json`.
75
+ """
76
+
77
+ temperature: float
78
+ """The sampling temperature, between 0 and 1.
79
+
80
+ Higher values like 0.8 will make the output more random, while lower values like
81
+ 0.2 will make it more focused and deterministic. If set to 0, the model will use
82
+ [log probability](https://en.wikipedia.org/wiki/Log_probability) to
83
+ automatically increase the temperature until certain thresholds are hit.
84
+ """
85
+
86
+ timestamp_granularities: List[Literal["word", "segment"]]
87
+ """The timestamp granularities to populate for this transcription.
88
+
89
+ `response_format` must be set `verbose_json` to use timestamp granularities.
90
+ Either or both of these options are supported: `word`, or `segment`. Note: There
91
+ is no additional latency for segment timestamps, but generating word timestamps
92
+ incurs additional latency.
93
+ """
94
+
95
+
96
+ class ChunkingStrategyVadConfig(TypedDict, total=False):
97
+ type: Required[Literal["server_vad"]]
98
+ """Must be set to `server_vad` to enable manual chunking using server side VAD."""
99
+
100
+ prefix_padding_ms: int
101
+ """Amount of audio to include before the VAD detected speech (in milliseconds)."""
102
+
103
+ silence_duration_ms: int
104
+ """
105
+ Duration of silence to detect speech stop (in milliseconds). With shorter values
106
+ the model will respond more quickly, but may jump in on short pauses from the
107
+ user.
108
+ """
109
+
110
+ threshold: float
111
+ """Sensitivity threshold (0.0 to 1.0) for voice activity detection.
112
+
113
+ A higher threshold will require louder audio to activate the model, and thus
114
+ might perform better in noisy environments.
115
+ """
116
+
117
+
118
+ ChunkingStrategy: TypeAlias = Union[Literal["auto"], ChunkingStrategyVadConfig]
119
+
120
+
121
+ class TranscriptionCreateParamsNonStreaming(TranscriptionCreateParamsBase, total=False):
122
+ stream: Optional[Literal[False]]
123
+ """
124
+ If set to true, the model response data will be streamed to the client as it is
125
+ generated using
126
+ [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).
127
+ See the
128
+ [Streaming section of the Speech-to-Text guide](https://platform.openai.com/docs/guides/speech-to-text?lang=curl#streaming-transcriptions)
129
+ for more information.
130
+
131
+ Note: Streaming is not supported for the `whisper-1` model and will be ignored.
132
+ """
133
+
134
+
135
+ class TranscriptionCreateParamsStreaming(TranscriptionCreateParamsBase):
136
+ stream: Required[Literal[True]]
137
+ """
138
+ If set to true, the model response data will be streamed to the client as it is
139
+ generated using
140
+ [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).
141
+ See the
142
+ [Streaming section of the Speech-to-Text guide](https://platform.openai.com/docs/guides/speech-to-text?lang=curl#streaming-transcriptions)
143
+ for more information.
144
+
145
+ Note: Streaming is not supported for the `whisper-1` model and will be ignored.
146
+ """
147
+
148
+
149
+ TranscriptionCreateParams = Union[TranscriptionCreateParamsNonStreaming, TranscriptionCreateParamsStreaming]
python_embeded/Lib/site-packages/openai/types/audio/transcription_create_response.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from typing import Union
4
+ from typing_extensions import TypeAlias
5
+
6
+ from .transcription import Transcription
7
+ from .transcription_verbose import TranscriptionVerbose
8
+
9
+ __all__ = ["TranscriptionCreateResponse"]
10
+
11
+ TranscriptionCreateResponse: TypeAlias = Union[Transcription, TranscriptionVerbose]
python_embeded/Lib/site-packages/openai/types/audio/transcription_include.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from typing_extensions import Literal, TypeAlias
4
+
5
+ __all__ = ["TranscriptionInclude"]
6
+
7
+ TranscriptionInclude: TypeAlias = Literal["logprobs"]