openresponses-impl-client-openai 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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 [yyyy] [name of copyright owner]
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.
@@ -0,0 +1,35 @@
1
+ Metadata-Version: 2.4
2
+ Name: openresponses-impl-client-openai
3
+ Version: 0.1.0
4
+ Summary: Python Client library implementing the OpenResponses specification
5
+ Author-email: rsato <satookok@gmail.com>
6
+ Project-URL: Homepage, https://github.com/post-class/openresponses-impl-client-openai
7
+ Project-URL: Repository, https://github.com/post-class/openresponses-impl-client-openai
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
15
+ Requires-Python: >=3.12
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: openai>=2.29.0
19
+ Requires-Dist: openresponses-impl-core>=0.1.0
20
+ Dynamic: license-file
21
+
22
+ # openresponses-impl-client-openai
23
+
24
+ Python client library for OpenAI/Azure OpenAI implementing the OpenResponses specification
25
+
26
+ ## Overview
27
+
28
+ This library provides an interface compliant with the OpenResponses specification for OpenAI API and Azure OpenAI Service.
29
+
30
+ ## Features
31
+
32
+ - Supports both OpenAI API and Azure OpenAI Service
33
+ - Handles streaming and non-streaming responses
34
+ - Uses type-safe Pydantic models
35
+ - Supports asynchronous processing (async/await)
@@ -0,0 +1,14 @@
1
+ # openresponses-impl-client-openai
2
+
3
+ Python client library for OpenAI/Azure OpenAI implementing the OpenResponses specification
4
+
5
+ ## Overview
6
+
7
+ This library provides an interface compliant with the OpenResponses specification for OpenAI API and Azure OpenAI Service.
8
+
9
+ ## Features
10
+
11
+ - Supports both OpenAI API and Azure OpenAI Service
12
+ - Handles streaming and non-streaming responses
13
+ - Uses type-safe Pydantic models
14
+ - Supports asynchronous processing (async/await)
@@ -0,0 +1,44 @@
1
+ [build-system]
2
+ requires = ["setuptools>=64", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "openresponses-impl-client-openai"
7
+ version = "0.1.0"
8
+ description = "Python Client library implementing the OpenResponses specification"
9
+ readme = "README.md"
10
+ requires-python = ">=3.12"
11
+ authors = [
12
+ { name = "rsato", email = "satookok@gmail.com" }
13
+ ]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: Apache Software License",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Operating System :: OS Independent",
21
+ "Topic :: Software Development :: Libraries :: Python Modules"
22
+ ]
23
+ dependencies = [
24
+ "openai>=2.29.0",
25
+ "openresponses-impl-core>=0.1.0",
26
+ ]
27
+
28
+ [project.urls]
29
+ Homepage = "https://github.com/post-class/openresponses-impl-client-openai"
30
+ Repository = "https://github.com/post-class/openresponses-impl-client-openai"
31
+
32
+ [dependency-groups]
33
+ dev = [
34
+ "build>=1.4.0",
35
+ "pytest>=8.3.0",
36
+ "pytest-asyncio>=1.3.0",
37
+ "pytest-cov>=7.1.0",
38
+ "ruff>=0.15.7",
39
+ "twine>=6.2.0",
40
+ ]
41
+
42
+ [tool.pytest.ini_options]
43
+ pythonpath = ["src"]
44
+ testpaths = ["test"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,207 @@
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ from collections.abc import AsyncIterator
5
+ from typing import Any, Literal, override
6
+
7
+ from openai import AsyncOpenAI
8
+ from openresponses_impl_core.client.base_responses_client import BaseResponsesClient
9
+ from openresponses_impl_core.models.openresponses_models import (
10
+ CreateResponseBody,
11
+ ResponseResource,
12
+ )
13
+ from openresponses_impl_core.models.response_event_types import ResponseStreamingEvent
14
+
15
+ from openresponses_impl_client_openai.utils.copy_util import CopyUtil
16
+ from openresponses_impl_client_openai.utils.openai_response_model_util import (
17
+ OpenAIResponseModelUtil,
18
+ )
19
+
20
+
21
+ class OpenAIResponsesClient(BaseResponsesClient):
22
+ """Responses client for OpenAI/Azure OpenAI"""
23
+
24
+ def __init__(
25
+ self,
26
+ *,
27
+ vendor: Literal["openai", "azure"],
28
+ model: str,
29
+ openai_api_key: str | None = None,
30
+ azure_openai_endpoint: str | None = None,
31
+ azure_openai_api_key: str | None = None,
32
+ azure_openai_api_version: str = "2024-10-21",
33
+ ) -> None:
34
+ """Responses client for OpenAI/Azure OpenAI
35
+
36
+ Args:
37
+ vendor: Specify "openai" or "azure"
38
+ model: Model name (e.g., "gpt-4", "gpt-5-mini")
39
+ openai_api_key: OpenAI API key (required when vendor="openai")
40
+ azure_openai_endpoint: Azure OpenAI endpoint (required when vendor="azure")
41
+ azure_openai_api_key: Azure OpenAI API key (required when vendor="azure")
42
+ azure_openai_api_version: Azure OpenAI API version (default: "2024-10-21" when vendor="azure")
43
+
44
+ Raises:
45
+ ValueError: When required parameters are missing
46
+
47
+ """
48
+ self._provider = vendor
49
+ self._model = model
50
+ self._api_key = openai_api_key
51
+ self._azure_endpoint = azure_openai_endpoint
52
+ self._azure_api_key = azure_openai_api_key
53
+ self._azure_api_version = azure_openai_api_version
54
+
55
+ # Validation
56
+ if not model:
57
+ raise ValueError("model is required.")
58
+ if vendor == "openai" and not openai_api_key:
59
+ raise ValueError("openai_api_key is required when vendor='openai'.")
60
+ if vendor == "azure":
61
+ if not azure_openai_endpoint or not azure_openai_api_key:
62
+ raise ValueError(
63
+ "azure_openai_endpoint and azure_openai_api_key are required when vendor='azure'."
64
+ )
65
+
66
+ # Create and store client
67
+ self._client = self._create_client()
68
+
69
+ @override
70
+ async def create_response(
71
+ self, payload: CreateResponseBody, **kwargs: Any
72
+ ) -> ResponseResource | AsyncIterator[ResponseStreamingEvent]:
73
+ """Create a response based on the stream field in the payload
74
+
75
+ Args:
76
+ payload: Request payload (CreateResponseBody type)
77
+ **kwargs: Additional parameters (passed to extra_body)
78
+
79
+ Returns:
80
+ payload.stream=False/None: ResponseResource
81
+ payload.stream=True: AsyncIterator[ResponseStreamingEvent]
82
+
83
+ """
84
+ # Branch based on payload.stream value
85
+ if payload.stream:
86
+ return await self._create_response_stream(payload=payload, extra_params=kwargs)
87
+ return await self._create_response_non_stream(payload=payload, extra_params=kwargs)
88
+
89
+ async def _create_response_non_stream(
90
+ self, payload: CreateResponseBody, extra_params: dict[str, Any] | None = None
91
+ ) -> ResponseResource:
92
+ """Generate response in non-streaming mode"""
93
+ request_payload = payload.model_copy(deep=True)
94
+ # Use payload.stream value as-is (False or unset)
95
+
96
+ request_kwargs = self._build_create_kwargs(
97
+ client=self._client, payload=request_payload, extra_params=extra_params
98
+ )
99
+ response = await self._client.responses.create(**request_kwargs)
100
+ return OpenAIResponseModelUtil.parse_response(payload=response)
101
+
102
+ async def _create_response_stream(
103
+ self, payload: CreateResponseBody, extra_params: dict[str, Any] | None = None
104
+ ) -> AsyncIterator[ResponseStreamingEvent]:
105
+ """Generate response in streaming mode"""
106
+ request_payload = payload.model_copy(deep=True)
107
+ # Use payload.stream value as-is (True)
108
+ request_kwargs = self._build_create_kwargs(
109
+ client=self._client, payload=request_payload, extra_params=extra_params
110
+ )
111
+ return self._iter_stream_events(client=self._client, request_kwargs=request_kwargs)
112
+
113
+ def _build_create_kwargs(
114
+ self,
115
+ *,
116
+ client: AsyncOpenAI,
117
+ payload: CreateResponseBody,
118
+ extra_params: dict[str, Any] | None = None,
119
+ ) -> dict[str, Any]:
120
+ """Build kwargs for OpenAI API request"""
121
+ signature = inspect.signature(client.responses.create)
122
+ supported_keys = set(signature.parameters.keys())
123
+
124
+ # Convert CreateResponseBody to dictionary
125
+ payload_dict = payload.model_dump(mode="json", exclude_none=True)
126
+
127
+ request_kwargs: dict[str, Any] = {}
128
+ passthrough_extra_body: dict[str, Any] = {}
129
+
130
+ for key, value in payload_dict.items():
131
+ if key in supported_keys:
132
+ # Use instance variable model name for model key
133
+ if key == "model":
134
+ request_kwargs[key] = self._model
135
+ else:
136
+ request_kwargs[key] = value
137
+ continue
138
+ passthrough_extra_body[key] = value
139
+
140
+ # Avoid provider-side validation error when stream is not enabled.
141
+ if request_kwargs.get("stream") is not True:
142
+ request_kwargs.pop("stream_options", None)
143
+
144
+ # Merge extra_params into passthrough_extra_body if present
145
+ if extra_params:
146
+ passthrough_extra_body.update(extra_params)
147
+
148
+ # Bundle fields in CreateResponseBody that don't exist in OpenAI API's official signature as extra_body parameter
149
+ if passthrough_extra_body:
150
+ existing_extra_body = request_kwargs.get("extra_body")
151
+ if isinstance(existing_extra_body, dict):
152
+ merged_extra_body = CopyUtil.deep_copy(existing_extra_body)
153
+ merged_extra_body.update(passthrough_extra_body)
154
+ request_kwargs["extra_body"] = merged_extra_body
155
+ else:
156
+ request_kwargs["extra_body"] = passthrough_extra_body
157
+
158
+ return request_kwargs
159
+
160
+ async def _close_stream(self, stream: Any) -> None:
161
+ """Close the stream"""
162
+ aclose_method = getattr(stream, "aclose", None)
163
+ if callable(aclose_method):
164
+ result = aclose_method()
165
+ if inspect.isawaitable(result):
166
+ await result
167
+ return
168
+
169
+ close_method = getattr(stream, "close", None)
170
+ if callable(close_method):
171
+ result = close_method()
172
+ if inspect.isawaitable(result):
173
+ await result
174
+
175
+ async def _iter_stream_events(
176
+ self, *, client: AsyncOpenAI, request_kwargs: dict[str, Any]
177
+ ) -> AsyncIterator[ResponseStreamingEvent]:
178
+ """Generate streaming events"""
179
+ stream = await client.responses.create(**request_kwargs)
180
+ try:
181
+ async for event in stream:
182
+ yield OpenAIResponseModelUtil.parse_stream_event(payload=event)
183
+ finally:
184
+ await self._close_stream(stream)
185
+
186
+ def _create_client(self) -> AsyncOpenAI:
187
+ """Create OpenAI/Azure OpenAI client"""
188
+ if self._provider == "azure":
189
+ # Create client for Azure OpenAI
190
+ # Validation already performed in __init__
191
+ assert self._azure_endpoint is not None
192
+ assert self._azure_api_key is not None
193
+ azure_endpoint = self._azure_endpoint.rstrip("/")
194
+ return AsyncOpenAI(
195
+ api_key="",
196
+ base_url=f"{azure_endpoint}/openai",
197
+ default_headers={"api-key": self._azure_api_key},
198
+ default_query={"api-version": self._azure_api_version},
199
+ )
200
+ if self._provider == "openai":
201
+ # Create client for OpenAI
202
+ # Validation already performed in __init__
203
+ assert self._api_key is not None
204
+ return AsyncOpenAI(
205
+ api_key=self._api_key,
206
+ )
207
+ raise ValueError(f"Unsupported provider: {self._provider}")
@@ -0,0 +1,49 @@
1
+ from __future__ import annotations
2
+
3
+ from copy import deepcopy
4
+ from typing import TypeVar
5
+
6
+ from pydantic import BaseModel
7
+
8
+ T = TypeVar("T")
9
+
10
+
11
+ class CopyUtil:
12
+ """Utility class for copy operations.
13
+
14
+ Provides deep copy functionality for both Pydantic models and regular Python objects.
15
+ """
16
+
17
+ @staticmethod
18
+ def deep_copy(obj: T) -> T:
19
+ """Create a deep copy of an object.
20
+
21
+ Uses model_copy(deep=True) for Pydantic models,
22
+ and copy.deepcopy for other objects.
23
+
24
+ Args:
25
+ obj: Object to be copied
26
+
27
+ Returns:
28
+ Deep copied object
29
+
30
+ Examples:
31
+ >>> # Deep copy of a dictionary
32
+ >>> original = {"key": {"nested": "value"}}
33
+ >>> copied = CopyUtil.deep_copy(original)
34
+ >>> copied["key"]["nested"] = "modified"
35
+ >>> original["key"]["nested"] # "value" (original data is unchanged)
36
+
37
+ >>> # Deep copy of a Pydantic model
38
+ >>> from pydantic import BaseModel
39
+ >>> class MyModel(BaseModel):
40
+ ... data: dict
41
+ >>> original_model = MyModel(data={"nested": "value"})
42
+ >>> copied_model = CopyUtil.deep_copy(original_model)
43
+ >>> copied_model.data["nested"] = "modified"
44
+ >>> original_model.data["nested"] # "value" (original data is unchanged)
45
+
46
+ """
47
+ if isinstance(obj, BaseModel):
48
+ return obj.model_copy(deep=True)
49
+ return deepcopy(obj)
@@ -0,0 +1,121 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+ from openresponses_impl_core.models.openresponses_models import (
6
+ ErrorPayload,
7
+ ErrorStreamingEvent,
8
+ ResponseResource,
9
+ )
10
+ from openresponses_impl_core.models.response_event_types import ResponseStreamingEvent
11
+ from pydantic import TypeAdapter, ValidationError
12
+
13
+
14
+ class OpenAIResponseModelUtil:
15
+ """Utility class for converting OpenAI API responses to OpenResponses models.
16
+
17
+ This class provides functionality to convert responses and streaming events
18
+ returned from the OpenAI API into OpenResponses standard model format.
19
+ """
20
+
21
+ @staticmethod
22
+ def parse_response(*, payload: Any) -> ResponseResource:
23
+ """Convert response payload to ResponseResource model.
24
+
25
+ Args:
26
+ payload: Payload to be converted. Accepts ResponseResource instance,
27
+ Pydantic model, or dictionary.
28
+
29
+ Returns:
30
+ ResponseResource: Converted response resource.
31
+
32
+ Raises:
33
+ ValueError: When payload is neither a dictionary nor a Pydantic model.
34
+ ValidationError: When payload validation fails.
35
+
36
+ """
37
+ if isinstance(payload, ResponseResource):
38
+ return payload
39
+ normalized = OpenAIResponseModelUtil._normalize_payload(payload=payload)
40
+ return ResponseResource.model_validate(normalized)
41
+
42
+ @staticmethod
43
+ def parse_stream_event(*, payload: Any) -> ResponseStreamingEvent:
44
+ """Convert streaming event payload to ResponseStreamingEvent model.
45
+
46
+ Returns an ErrorStreamingEvent containing error information if conversion fails.
47
+
48
+ Args:
49
+ payload: Streaming event payload to be converted.
50
+
51
+ Returns:
52
+ ResponseStreamingEvent: Converted streaming event.
53
+ ErrorStreamingEvent if conversion fails.
54
+
55
+ """
56
+ normalized = OpenAIResponseModelUtil._normalize_payload(
57
+ payload=payload, allow_non_dict=True
58
+ )
59
+ if not isinstance(normalized, dict):
60
+ message = f"unsupported streaming event payload: {type(payload).__name__}"
61
+ return OpenAIResponseModelUtil._build_error_event(payload={}, message=message)
62
+
63
+ adapter = TypeAdapter(ResponseStreamingEvent)
64
+ try:
65
+ return adapter.validate_python(normalized)
66
+ except ValidationError as exc:
67
+ message = f"invalid streaming event: {exc}"
68
+ return OpenAIResponseModelUtil._build_error_event(payload=normalized, message=message)
69
+
70
+ @staticmethod
71
+ def _normalize_payload(*, payload: Any, allow_non_dict: bool = False) -> Any:
72
+ """Normalize the payload.
73
+
74
+ Converts Pydantic models to dictionaries using model_dump.
75
+
76
+ Args:
77
+ payload: Payload to be normalized.
78
+ allow_non_dict: Whether to allow non-dictionary types. Default is False.
79
+
80
+ Returns:
81
+ Any: Normalized payload. Usually a dictionary.
82
+
83
+ Raises:
84
+ ValueError: When allow_non_dict is False and payload is neither a dictionary nor a Pydantic model.
85
+
86
+ """
87
+ if hasattr(payload, "model_dump"):
88
+ payload = payload.model_dump(mode="json")
89
+ if isinstance(payload, dict):
90
+ return payload
91
+ if allow_non_dict:
92
+ return payload
93
+ raise ValueError("payload must be a dict or model")
94
+
95
+ @staticmethod
96
+ def _build_error_event(*, payload: dict[str, Any], message: str) -> ErrorStreamingEvent:
97
+ """Build an error streaming event.
98
+
99
+ Args:
100
+ payload: Payload that caused the error. Used to retrieve sequence_number.
101
+ message: Error message.
102
+
103
+ Returns:
104
+ ErrorStreamingEvent: Constructed error streaming event.
105
+
106
+ """
107
+ sequence_number = payload.get("sequence_number")
108
+ if not isinstance(sequence_number, int):
109
+ sequence_number = 0
110
+ error = ErrorPayload(
111
+ type="invalid_stream_event",
112
+ code=None,
113
+ message=message,
114
+ param=None,
115
+ headers=None,
116
+ )
117
+ return ErrorStreamingEvent(
118
+ type="error",
119
+ sequence_number=sequence_number,
120
+ error=error,
121
+ )
@@ -0,0 +1,35 @@
1
+ Metadata-Version: 2.4
2
+ Name: openresponses-impl-client-openai
3
+ Version: 0.1.0
4
+ Summary: Python Client library implementing the OpenResponses specification
5
+ Author-email: rsato <satookok@gmail.com>
6
+ Project-URL: Homepage, https://github.com/post-class/openresponses-impl-client-openai
7
+ Project-URL: Repository, https://github.com/post-class/openresponses-impl-client-openai
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
15
+ Requires-Python: >=3.12
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: openai>=2.29.0
19
+ Requires-Dist: openresponses-impl-core>=0.1.0
20
+ Dynamic: license-file
21
+
22
+ # openresponses-impl-client-openai
23
+
24
+ Python client library for OpenAI/Azure OpenAI implementing the OpenResponses specification
25
+
26
+ ## Overview
27
+
28
+ This library provides an interface compliant with the OpenResponses specification for OpenAI API and Azure OpenAI Service.
29
+
30
+ ## Features
31
+
32
+ - Supports both OpenAI API and Azure OpenAI Service
33
+ - Handles streaming and non-streaming responses
34
+ - Uses type-safe Pydantic models
35
+ - Supports asynchronous processing (async/await)
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/openresponses_impl_client_openai/__init__.py
5
+ src/openresponses_impl_client_openai.egg-info/PKG-INFO
6
+ src/openresponses_impl_client_openai.egg-info/SOURCES.txt
7
+ src/openresponses_impl_client_openai.egg-info/dependency_links.txt
8
+ src/openresponses_impl_client_openai.egg-info/requires.txt
9
+ src/openresponses_impl_client_openai.egg-info/top_level.txt
10
+ src/openresponses_impl_client_openai/client/__init__.py
11
+ src/openresponses_impl_client_openai/client/openai_responses_client.py
12
+ src/openresponses_impl_client_openai/utils/__init__.py
13
+ src/openresponses_impl_client_openai/utils/copy_util.py
14
+ src/openresponses_impl_client_openai/utils/openai_response_model_util.py
@@ -0,0 +1,2 @@
1
+ openai>=2.29.0
2
+ openresponses-impl-core>=0.1.0