MCPcopy
hub / github.com/anthropics/anthropic-sdk-python / _parse

Method _parse

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

Source from the content-addressed store, hash-verified

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

Callers 2

parseMethod · 0.45
parseMethod · 0.45

Calls 14

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
iter_bytesMethod · 0.45
aiter_bytesMethod · 0.45

Tested by

no test coverage detected