files.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  1. # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
  2. from __future__ import annotations
  3. import time
  4. import typing_extensions
  5. from typing import Mapping, cast
  6. from typing_extensions import Literal
  7. import httpx
  8. from .. import _legacy_response
  9. from ..types import FilePurpose, file_list_params, file_create_params
  10. from .._types import Body, Omit, Query, Headers, NotGiven, FileTypes, omit, not_given
  11. from .._utils import extract_files, maybe_transform, deepcopy_minimal, async_maybe_transform
  12. from .._compat import cached_property
  13. from .._resource import SyncAPIResource, AsyncAPIResource
  14. from .._response import (
  15. StreamedBinaryAPIResponse,
  16. AsyncStreamedBinaryAPIResponse,
  17. to_streamed_response_wrapper,
  18. async_to_streamed_response_wrapper,
  19. to_custom_streamed_response_wrapper,
  20. async_to_custom_streamed_response_wrapper,
  21. )
  22. from ..pagination import SyncCursorPage, AsyncCursorPage
  23. from .._base_client import AsyncPaginator, make_request_options
  24. from ..types.file_object import FileObject
  25. from ..types.file_deleted import FileDeleted
  26. from ..types.file_purpose import FilePurpose
  27. __all__ = ["Files", "AsyncFiles"]
  28. class Files(SyncAPIResource):
  29. @cached_property
  30. def with_raw_response(self) -> FilesWithRawResponse:
  31. """
  32. This property can be used as a prefix for any HTTP method call to return
  33. the raw response object instead of the parsed content.
  34. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
  35. """
  36. return FilesWithRawResponse(self)
  37. @cached_property
  38. def with_streaming_response(self) -> FilesWithStreamingResponse:
  39. """
  40. An alternative to `.with_raw_response` that doesn't eagerly read the response body.
  41. For more information, see https://www.github.com/openai/openai-python#with_streaming_response
  42. """
  43. return FilesWithStreamingResponse(self)
  44. def create(
  45. self,
  46. *,
  47. file: FileTypes,
  48. purpose: FilePurpose,
  49. expires_after: file_create_params.ExpiresAfter | Omit = omit,
  50. # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
  51. # The extra values given here take precedence over values defined on the client or passed to this method.
  52. extra_headers: Headers | None = None,
  53. extra_query: Query | None = None,
  54. extra_body: Body | None = None,
  55. timeout: float | httpx.Timeout | None | NotGiven = not_given,
  56. ) -> FileObject:
  57. """Upload a file that can be used across various endpoints.
  58. Individual files can be
  59. up to 512 MB, and the size of all files uploaded by one organization can be up
  60. to 1 TB.
  61. - The Assistants API supports files up to 2 million tokens and of specific file
  62. types. See the
  63. [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools)
  64. for details.
  65. - The Fine-tuning API only supports `.jsonl` files. The input also has certain
  66. required formats for fine-tuning
  67. [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input)
  68. or
  69. [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input)
  70. models.
  71. - The Batch API only supports `.jsonl` files up to 200 MB in size. The input
  72. also has a specific required
  73. [format](https://platform.openai.com/docs/api-reference/batch/request-input).
  74. Please [contact us](https://help.openai.com/) if you need to increase these
  75. storage limits.
  76. Args:
  77. file: The File object (not file name) to be uploaded.
  78. purpose: The intended purpose of the uploaded file. One of: - `assistants`: Used in the
  79. Assistants API - `batch`: Used in the Batch API - `fine-tune`: Used for
  80. fine-tuning - `vision`: Images used for vision fine-tuning - `user_data`:
  81. Flexible file type for any purpose - `evals`: Used for eval data sets
  82. expires_after: The expiration policy for a file. By default, files with `purpose=batch` expire
  83. after 30 days and all other files are persisted until they are manually deleted.
  84. extra_headers: Send extra headers
  85. extra_query: Add additional query parameters to the request
  86. extra_body: Add additional JSON properties to the request
  87. timeout: Override the client-level default timeout for this request, in seconds
  88. """
  89. body = deepcopy_minimal(
  90. {
  91. "file": file,
  92. "purpose": purpose,
  93. "expires_after": expires_after,
  94. }
  95. )
  96. files = extract_files(cast(Mapping[str, object], body), paths=[["file"]])
  97. # It should be noted that the actual Content-Type header that will be
  98. # sent to the server will contain a `boundary` parameter, e.g.
  99. # multipart/form-data; boundary=---abc--
  100. extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})}
  101. return self._post(
  102. "/files",
  103. body=maybe_transform(body, file_create_params.FileCreateParams),
  104. files=files,
  105. options=make_request_options(
  106. extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
  107. ),
  108. cast_to=FileObject,
  109. )
  110. def retrieve(
  111. self,
  112. file_id: str,
  113. *,
  114. # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
  115. # The extra values given here take precedence over values defined on the client or passed to this method.
  116. extra_headers: Headers | None = None,
  117. extra_query: Query | None = None,
  118. extra_body: Body | None = None,
  119. timeout: float | httpx.Timeout | None | NotGiven = not_given,
  120. ) -> FileObject:
  121. """
  122. Returns information about a specific file.
  123. Args:
  124. extra_headers: Send extra headers
  125. extra_query: Add additional query parameters to the request
  126. extra_body: Add additional JSON properties to the request
  127. timeout: Override the client-level default timeout for this request, in seconds
  128. """
  129. if not file_id:
  130. raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}")
  131. return self._get(
  132. f"/files/{file_id}",
  133. options=make_request_options(
  134. extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
  135. ),
  136. cast_to=FileObject,
  137. )
  138. def list(
  139. self,
  140. *,
  141. after: str | Omit = omit,
  142. limit: int | Omit = omit,
  143. order: Literal["asc", "desc"] | Omit = omit,
  144. purpose: str | Omit = omit,
  145. # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
  146. # The extra values given here take precedence over values defined on the client or passed to this method.
  147. extra_headers: Headers | None = None,
  148. extra_query: Query | None = None,
  149. extra_body: Body | None = None,
  150. timeout: float | httpx.Timeout | None | NotGiven = not_given,
  151. ) -> SyncCursorPage[FileObject]:
  152. """Returns a list of files.
  153. Args:
  154. after: A cursor for use in pagination.
  155. `after` is an object ID that defines your place
  156. in the list. For instance, if you make a list request and receive 100 objects,
  157. ending with obj_foo, your subsequent call can include after=obj_foo in order to
  158. fetch the next page of the list.
  159. limit: A limit on the number of objects to be returned. Limit can range between 1 and
  160. 10,000, and the default is 10,000.
  161. order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending
  162. order and `desc` for descending order.
  163. purpose: Only return files with the given purpose.
  164. extra_headers: Send extra headers
  165. extra_query: Add additional query parameters to the request
  166. extra_body: Add additional JSON properties to the request
  167. timeout: Override the client-level default timeout for this request, in seconds
  168. """
  169. return self._get_api_list(
  170. "/files",
  171. page=SyncCursorPage[FileObject],
  172. options=make_request_options(
  173. extra_headers=extra_headers,
  174. extra_query=extra_query,
  175. extra_body=extra_body,
  176. timeout=timeout,
  177. query=maybe_transform(
  178. {
  179. "after": after,
  180. "limit": limit,
  181. "order": order,
  182. "purpose": purpose,
  183. },
  184. file_list_params.FileListParams,
  185. ),
  186. ),
  187. model=FileObject,
  188. )
  189. def delete(
  190. self,
  191. file_id: str,
  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. ) -> FileDeleted:
  200. """
  201. Delete a file and remove it from all vector stores.
  202. Args:
  203. extra_headers: Send extra headers
  204. extra_query: Add additional query parameters to the request
  205. extra_body: Add additional JSON properties to the request
  206. timeout: Override the client-level default timeout for this request, in seconds
  207. """
  208. if not file_id:
  209. raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}")
  210. return self._delete(
  211. f"/files/{file_id}",
  212. options=make_request_options(
  213. extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
  214. ),
  215. cast_to=FileDeleted,
  216. )
  217. def content(
  218. self,
  219. file_id: str,
  220. *,
  221. # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
  222. # The extra values given here take precedence over values defined on the client or passed to this method.
  223. extra_headers: Headers | None = None,
  224. extra_query: Query | None = None,
  225. extra_body: Body | None = None,
  226. timeout: float | httpx.Timeout | None | NotGiven = not_given,
  227. ) -> _legacy_response.HttpxBinaryResponseContent:
  228. """
  229. Returns the contents of the specified file.
  230. Args:
  231. extra_headers: Send extra headers
  232. extra_query: Add additional query parameters to the request
  233. extra_body: Add additional JSON properties to the request
  234. timeout: Override the client-level default timeout for this request, in seconds
  235. """
  236. if not file_id:
  237. raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}")
  238. extra_headers = {"Accept": "application/binary", **(extra_headers or {})}
  239. return self._get(
  240. f"/files/{file_id}/content",
  241. options=make_request_options(
  242. extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
  243. ),
  244. cast_to=_legacy_response.HttpxBinaryResponseContent,
  245. )
  246. @typing_extensions.deprecated("The `.content()` method should be used instead")
  247. def retrieve_content(
  248. self,
  249. file_id: str,
  250. *,
  251. # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
  252. # The extra values given here take precedence over values defined on the client or passed to this method.
  253. extra_headers: Headers | None = None,
  254. extra_query: Query | None = None,
  255. extra_body: Body | None = None,
  256. timeout: float | httpx.Timeout | None | NotGiven = not_given,
  257. ) -> str:
  258. """
  259. Returns the contents of the specified file.
  260. Args:
  261. extra_headers: Send extra headers
  262. extra_query: Add additional query parameters to the request
  263. extra_body: Add additional JSON properties to the request
  264. timeout: Override the client-level default timeout for this request, in seconds
  265. """
  266. if not file_id:
  267. raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}")
  268. return self._get(
  269. f"/files/{file_id}/content",
  270. options=make_request_options(
  271. extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
  272. ),
  273. cast_to=str,
  274. )
  275. def wait_for_processing(
  276. self,
  277. id: str,
  278. *,
  279. poll_interval: float = 5.0,
  280. max_wait_seconds: float = 30 * 60,
  281. ) -> FileObject:
  282. """Waits for the given file to be processed, default timeout is 30 mins."""
  283. TERMINAL_STATES = {"processed", "error", "deleted"}
  284. start = time.time()
  285. file = self.retrieve(id)
  286. while file.status not in TERMINAL_STATES:
  287. self._sleep(poll_interval)
  288. file = self.retrieve(id)
  289. if time.time() - start > max_wait_seconds:
  290. raise RuntimeError(
  291. f"Giving up on waiting for file {id} to finish processing after {max_wait_seconds} seconds."
  292. )
  293. return file
  294. class AsyncFiles(AsyncAPIResource):
  295. @cached_property
  296. def with_raw_response(self) -> AsyncFilesWithRawResponse:
  297. """
  298. This property can be used as a prefix for any HTTP method call to return
  299. the raw response object instead of the parsed content.
  300. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
  301. """
  302. return AsyncFilesWithRawResponse(self)
  303. @cached_property
  304. def with_streaming_response(self) -> AsyncFilesWithStreamingResponse:
  305. """
  306. An alternative to `.with_raw_response` that doesn't eagerly read the response body.
  307. For more information, see https://www.github.com/openai/openai-python#with_streaming_response
  308. """
  309. return AsyncFilesWithStreamingResponse(self)
  310. async def create(
  311. self,
  312. *,
  313. file: FileTypes,
  314. purpose: FilePurpose,
  315. expires_after: file_create_params.ExpiresAfter | Omit = omit,
  316. # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
  317. # The extra values given here take precedence over values defined on the client or passed to this method.
  318. extra_headers: Headers | None = None,
  319. extra_query: Query | None = None,
  320. extra_body: Body | None = None,
  321. timeout: float | httpx.Timeout | None | NotGiven = not_given,
  322. ) -> FileObject:
  323. """Upload a file that can be used across various endpoints.
  324. Individual files can be
  325. up to 512 MB, and the size of all files uploaded by one organization can be up
  326. to 1 TB.
  327. - The Assistants API supports files up to 2 million tokens and of specific file
  328. types. See the
  329. [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools)
  330. for details.
  331. - The Fine-tuning API only supports `.jsonl` files. The input also has certain
  332. required formats for fine-tuning
  333. [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input)
  334. or
  335. [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input)
  336. models.
  337. - The Batch API only supports `.jsonl` files up to 200 MB in size. The input
  338. also has a specific required
  339. [format](https://platform.openai.com/docs/api-reference/batch/request-input).
  340. Please [contact us](https://help.openai.com/) if you need to increase these
  341. storage limits.
  342. Args:
  343. file: The File object (not file name) to be uploaded.
  344. purpose: The intended purpose of the uploaded file. One of: - `assistants`: Used in the
  345. Assistants API - `batch`: Used in the Batch API - `fine-tune`: Used for
  346. fine-tuning - `vision`: Images used for vision fine-tuning - `user_data`:
  347. Flexible file type for any purpose - `evals`: Used for eval data sets
  348. expires_after: The expiration policy for a file. By default, files with `purpose=batch` expire
  349. after 30 days and all other files are persisted until they are manually deleted.
  350. extra_headers: Send extra headers
  351. extra_query: Add additional query parameters to the request
  352. extra_body: Add additional JSON properties to the request
  353. timeout: Override the client-level default timeout for this request, in seconds
  354. """
  355. body = deepcopy_minimal(
  356. {
  357. "file": file,
  358. "purpose": purpose,
  359. "expires_after": expires_after,
  360. }
  361. )
  362. files = extract_files(cast(Mapping[str, object], body), paths=[["file"]])
  363. # It should be noted that the actual Content-Type header that will be
  364. # sent to the server will contain a `boundary` parameter, e.g.
  365. # multipart/form-data; boundary=---abc--
  366. extra_headers = {"Content-Type": "multipart/form-data", **(extra_headers or {})}
  367. return await self._post(
  368. "/files",
  369. body=await async_maybe_transform(body, file_create_params.FileCreateParams),
  370. files=files,
  371. options=make_request_options(
  372. extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
  373. ),
  374. cast_to=FileObject,
  375. )
  376. async def retrieve(
  377. self,
  378. file_id: str,
  379. *,
  380. # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
  381. # The extra values given here take precedence over values defined on the client or passed to this method.
  382. extra_headers: Headers | None = None,
  383. extra_query: Query | None = None,
  384. extra_body: Body | None = None,
  385. timeout: float | httpx.Timeout | None | NotGiven = not_given,
  386. ) -> FileObject:
  387. """
  388. Returns information about a specific file.
  389. Args:
  390. extra_headers: Send extra headers
  391. extra_query: Add additional query parameters to the request
  392. extra_body: Add additional JSON properties to the request
  393. timeout: Override the client-level default timeout for this request, in seconds
  394. """
  395. if not file_id:
  396. raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}")
  397. return await self._get(
  398. f"/files/{file_id}",
  399. options=make_request_options(
  400. extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
  401. ),
  402. cast_to=FileObject,
  403. )
  404. def list(
  405. self,
  406. *,
  407. after: str | Omit = omit,
  408. limit: int | Omit = omit,
  409. order: Literal["asc", "desc"] | Omit = omit,
  410. purpose: str | Omit = omit,
  411. # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
  412. # The extra values given here take precedence over values defined on the client or passed to this method.
  413. extra_headers: Headers | None = None,
  414. extra_query: Query | None = None,
  415. extra_body: Body | None = None,
  416. timeout: float | httpx.Timeout | None | NotGiven = not_given,
  417. ) -> AsyncPaginator[FileObject, AsyncCursorPage[FileObject]]:
  418. """Returns a list of files.
  419. Args:
  420. after: A cursor for use in pagination.
  421. `after` is an object ID that defines your place
  422. in the list. For instance, if you make a list request and receive 100 objects,
  423. ending with obj_foo, your subsequent call can include after=obj_foo in order to
  424. fetch the next page of the list.
  425. limit: A limit on the number of objects to be returned. Limit can range between 1 and
  426. 10,000, and the default is 10,000.
  427. order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending
  428. order and `desc` for descending order.
  429. purpose: Only return files with the given purpose.
  430. extra_headers: Send extra headers
  431. extra_query: Add additional query parameters to the request
  432. extra_body: Add additional JSON properties to the request
  433. timeout: Override the client-level default timeout for this request, in seconds
  434. """
  435. return self._get_api_list(
  436. "/files",
  437. page=AsyncCursorPage[FileObject],
  438. options=make_request_options(
  439. extra_headers=extra_headers,
  440. extra_query=extra_query,
  441. extra_body=extra_body,
  442. timeout=timeout,
  443. query=maybe_transform(
  444. {
  445. "after": after,
  446. "limit": limit,
  447. "order": order,
  448. "purpose": purpose,
  449. },
  450. file_list_params.FileListParams,
  451. ),
  452. ),
  453. model=FileObject,
  454. )
  455. async def delete(
  456. self,
  457. file_id: str,
  458. *,
  459. # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
  460. # The extra values given here take precedence over values defined on the client or passed to this method.
  461. extra_headers: Headers | None = None,
  462. extra_query: Query | None = None,
  463. extra_body: Body | None = None,
  464. timeout: float | httpx.Timeout | None | NotGiven = not_given,
  465. ) -> FileDeleted:
  466. """
  467. Delete a file and remove it from all vector stores.
  468. Args:
  469. extra_headers: Send extra headers
  470. extra_query: Add additional query parameters to the request
  471. extra_body: Add additional JSON properties to the request
  472. timeout: Override the client-level default timeout for this request, in seconds
  473. """
  474. if not file_id:
  475. raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}")
  476. return await self._delete(
  477. f"/files/{file_id}",
  478. options=make_request_options(
  479. extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
  480. ),
  481. cast_to=FileDeleted,
  482. )
  483. async def content(
  484. self,
  485. file_id: str,
  486. *,
  487. # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
  488. # The extra values given here take precedence over values defined on the client or passed to this method.
  489. extra_headers: Headers | None = None,
  490. extra_query: Query | None = None,
  491. extra_body: Body | None = None,
  492. timeout: float | httpx.Timeout | None | NotGiven = not_given,
  493. ) -> _legacy_response.HttpxBinaryResponseContent:
  494. """
  495. Returns the contents of the specified file.
  496. Args:
  497. extra_headers: Send extra headers
  498. extra_query: Add additional query parameters to the request
  499. extra_body: Add additional JSON properties to the request
  500. timeout: Override the client-level default timeout for this request, in seconds
  501. """
  502. if not file_id:
  503. raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}")
  504. extra_headers = {"Accept": "application/binary", **(extra_headers or {})}
  505. return await self._get(
  506. f"/files/{file_id}/content",
  507. options=make_request_options(
  508. extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
  509. ),
  510. cast_to=_legacy_response.HttpxBinaryResponseContent,
  511. )
  512. @typing_extensions.deprecated("The `.content()` method should be used instead")
  513. async def retrieve_content(
  514. self,
  515. file_id: str,
  516. *,
  517. # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
  518. # The extra values given here take precedence over values defined on the client or passed to this method.
  519. extra_headers: Headers | None = None,
  520. extra_query: Query | None = None,
  521. extra_body: Body | None = None,
  522. timeout: float | httpx.Timeout | None | NotGiven = not_given,
  523. ) -> str:
  524. """
  525. Returns the contents of the specified file.
  526. Args:
  527. extra_headers: Send extra headers
  528. extra_query: Add additional query parameters to the request
  529. extra_body: Add additional JSON properties to the request
  530. timeout: Override the client-level default timeout for this request, in seconds
  531. """
  532. if not file_id:
  533. raise ValueError(f"Expected a non-empty value for `file_id` but received {file_id!r}")
  534. return await self._get(
  535. f"/files/{file_id}/content",
  536. options=make_request_options(
  537. extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
  538. ),
  539. cast_to=str,
  540. )
  541. async def wait_for_processing(
  542. self,
  543. id: str,
  544. *,
  545. poll_interval: float = 5.0,
  546. max_wait_seconds: float = 30 * 60,
  547. ) -> FileObject:
  548. """Waits for the given file to be processed, default timeout is 30 mins."""
  549. TERMINAL_STATES = {"processed", "error", "deleted"}
  550. start = time.time()
  551. file = await self.retrieve(id)
  552. while file.status not in TERMINAL_STATES:
  553. await self._sleep(poll_interval)
  554. file = await self.retrieve(id)
  555. if time.time() - start > max_wait_seconds:
  556. raise RuntimeError(
  557. f"Giving up on waiting for file {id} to finish processing after {max_wait_seconds} seconds."
  558. )
  559. return file
  560. class FilesWithRawResponse:
  561. def __init__(self, files: Files) -> None:
  562. self._files = files
  563. self.create = _legacy_response.to_raw_response_wrapper(
  564. files.create,
  565. )
  566. self.retrieve = _legacy_response.to_raw_response_wrapper(
  567. files.retrieve,
  568. )
  569. self.list = _legacy_response.to_raw_response_wrapper(
  570. files.list,
  571. )
  572. self.delete = _legacy_response.to_raw_response_wrapper(
  573. files.delete,
  574. )
  575. self.content = _legacy_response.to_raw_response_wrapper(
  576. files.content,
  577. )
  578. self.retrieve_content = ( # pyright: ignore[reportDeprecated]
  579. _legacy_response.to_raw_response_wrapper(
  580. files.retrieve_content, # pyright: ignore[reportDeprecated],
  581. )
  582. )
  583. class AsyncFilesWithRawResponse:
  584. def __init__(self, files: AsyncFiles) -> None:
  585. self._files = files
  586. self.create = _legacy_response.async_to_raw_response_wrapper(
  587. files.create,
  588. )
  589. self.retrieve = _legacy_response.async_to_raw_response_wrapper(
  590. files.retrieve,
  591. )
  592. self.list = _legacy_response.async_to_raw_response_wrapper(
  593. files.list,
  594. )
  595. self.delete = _legacy_response.async_to_raw_response_wrapper(
  596. files.delete,
  597. )
  598. self.content = _legacy_response.async_to_raw_response_wrapper(
  599. files.content,
  600. )
  601. self.retrieve_content = ( # pyright: ignore[reportDeprecated]
  602. _legacy_response.async_to_raw_response_wrapper(
  603. files.retrieve_content, # pyright: ignore[reportDeprecated],
  604. )
  605. )
  606. class FilesWithStreamingResponse:
  607. def __init__(self, files: Files) -> None:
  608. self._files = files
  609. self.create = to_streamed_response_wrapper(
  610. files.create,
  611. )
  612. self.retrieve = to_streamed_response_wrapper(
  613. files.retrieve,
  614. )
  615. self.list = to_streamed_response_wrapper(
  616. files.list,
  617. )
  618. self.delete = to_streamed_response_wrapper(
  619. files.delete,
  620. )
  621. self.content = to_custom_streamed_response_wrapper(
  622. files.content,
  623. StreamedBinaryAPIResponse,
  624. )
  625. self.retrieve_content = ( # pyright: ignore[reportDeprecated]
  626. to_streamed_response_wrapper(
  627. files.retrieve_content, # pyright: ignore[reportDeprecated],
  628. )
  629. )
  630. class AsyncFilesWithStreamingResponse:
  631. def __init__(self, files: AsyncFiles) -> None:
  632. self._files = files
  633. self.create = async_to_streamed_response_wrapper(
  634. files.create,
  635. )
  636. self.retrieve = async_to_streamed_response_wrapper(
  637. files.retrieve,
  638. )
  639. self.list = async_to_streamed_response_wrapper(
  640. files.list,
  641. )
  642. self.delete = async_to_streamed_response_wrapper(
  643. files.delete,
  644. )
  645. self.content = async_to_custom_streamed_response_wrapper(
  646. files.content,
  647. AsyncStreamedBinaryAPIResponse,
  648. )
  649. self.retrieve_content = ( # pyright: ignore[reportDeprecated]
  650. async_to_streamed_response_wrapper(
  651. files.retrieve_content, # pyright: ignore[reportDeprecated],
  652. )
  653. )