MCPcopy
hub / github.com/openai/openai-python / _parse

Method _parse

src/openai/_response.py:128–274  ·  view source on GitHub ↗
(self, *, to: type[_T] | None = None)

Source from the content-addressed store, hash-verified

126 )
127
128 def _parse(self, *, to: type[_T] | None = None) -> R | _T:
129 cast_to = to if to is not None else self._cast_to
130
131 # unwrap `TypeAlias('Name', T)` -> `T`
132 if is_type_alias_type(cast_to):
133 cast_to = cast_to.__value__ # type: ignore[unreachable]
134
135 # unwrap `Annotated[T, ...]` -> `T`
136 if cast_to and is_annotated_type(cast_to):
137 cast_to = extract_type_arg(cast_to, 0)
138
139 origin = get_origin(cast_to) or cast_to
140
141 if self._is_sse_stream:
142 if to:
143 if not is_stream_class_type(to):
144 raise TypeError(f"Expected custom parse type to be a subclass of {Stream} or {AsyncStream}")
145
146 return cast(
147 _T,
148 to(
149 cast_to=extract_stream_chunk_type(
150 to,
151 failure_message="Expected custom stream type to be passed with a type argument, e.g. Stream[ChunkType]",
152 ),
153 response=self.http_response,
154 client=cast(Any, self._client),
155 options=self._options,
156 ),
157 )
158
159 if self._stream_cls:
160 return cast(
161 R,
162 self._stream_cls(
163 cast_to=extract_stream_chunk_type(self._stream_cls),
164 response=self.http_response,
165 client=cast(Any, self._client),
166 options=self._options,
167 ),
168 )
169
170 stream_cls = cast("type[Stream[Any]] | type[AsyncStream[Any]] | None", self._client._default_stream_cls)
171 if stream_cls is None:
172 raise MissingStreamClassError()
173
174 return cast(
175 R,
176 stream_cls(
177 cast_to=cast_to,
178 response=self.http_response,
179 client=cast(Any, self._client),
180 options=self._options,
181 ),
182 )
183
184 if cast_to is NoneType:
185 return cast(R, None)

Callers 2

parseMethod · 0.45
parseMethod · 0.45

Calls 12

is_type_alias_typeFunction · 0.85
is_annotated_typeFunction · 0.85
extract_type_argFunction · 0.85
is_stream_class_typeFunction · 0.85
is_basemodelFunction · 0.85
get_originFunction · 0.70
getMethod · 0.45
jsonMethod · 0.45

Tested by

no test coverage detected