file-batches.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. "use strict";
  2. // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
  3. Object.defineProperty(exports, "__esModule", { value: true });
  4. exports.FileBatches = void 0;
  5. const resource_1 = require("../../core/resource.js");
  6. const pagination_1 = require("../../core/pagination.js");
  7. const headers_1 = require("../../internal/headers.js");
  8. const sleep_1 = require("../../internal/utils/sleep.js");
  9. const Util_1 = require("../../lib/Util.js");
  10. const path_1 = require("../../internal/utils/path.js");
  11. class FileBatches extends resource_1.APIResource {
  12. /**
  13. * Create a vector store file batch.
  14. */
  15. create(vectorStoreID, body, options) {
  16. return this._client.post((0, path_1.path) `/vector_stores/${vectorStoreID}/file_batches`, {
  17. body,
  18. ...options,
  19. headers: (0, headers_1.buildHeaders)([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),
  20. });
  21. }
  22. /**
  23. * Retrieves a vector store file batch.
  24. */
  25. retrieve(batchID, params, options) {
  26. const { vector_store_id } = params;
  27. return this._client.get((0, path_1.path) `/vector_stores/${vector_store_id}/file_batches/${batchID}`, {
  28. ...options,
  29. headers: (0, headers_1.buildHeaders)([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),
  30. });
  31. }
  32. /**
  33. * Cancel a vector store file batch. This attempts to cancel the processing of
  34. * files in this batch as soon as possible.
  35. */
  36. cancel(batchID, params, options) {
  37. const { vector_store_id } = params;
  38. return this._client.post((0, path_1.path) `/vector_stores/${vector_store_id}/file_batches/${batchID}/cancel`, {
  39. ...options,
  40. headers: (0, headers_1.buildHeaders)([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]),
  41. });
  42. }
  43. /**
  44. * Create a vector store batch and poll until all files have been processed.
  45. */
  46. async createAndPoll(vectorStoreId, body, options) {
  47. const batch = await this.create(vectorStoreId, body);
  48. return await this.poll(vectorStoreId, batch.id, options);
  49. }
  50. /**
  51. * Returns a list of vector store files in a batch.
  52. */
  53. listFiles(batchID, params, options) {
  54. const { vector_store_id, ...query } = params;
  55. return this._client.getAPIList((0, path_1.path) `/vector_stores/${vector_store_id}/file_batches/${batchID}/files`, (pagination_1.CursorPage), { query, ...options, headers: (0, headers_1.buildHeaders)([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]) });
  56. }
  57. /**
  58. * Wait for the given file batch to be processed.
  59. *
  60. * Note: this will return even if one of the files failed to process, you need to
  61. * check batch.file_counts.failed_count to handle this case.
  62. */
  63. async poll(vectorStoreID, batchID, options) {
  64. const headers = (0, headers_1.buildHeaders)([
  65. options?.headers,
  66. {
  67. 'X-Stainless-Poll-Helper': 'true',
  68. 'X-Stainless-Custom-Poll-Interval': options?.pollIntervalMs?.toString() ?? undefined,
  69. },
  70. ]);
  71. while (true) {
  72. const { data: batch, response } = await this.retrieve(batchID, { vector_store_id: vectorStoreID }, {
  73. ...options,
  74. headers,
  75. }).withResponse();
  76. switch (batch.status) {
  77. case 'in_progress':
  78. let sleepInterval = 5000;
  79. if (options?.pollIntervalMs) {
  80. sleepInterval = options.pollIntervalMs;
  81. }
  82. else {
  83. const headerInterval = response.headers.get('openai-poll-after-ms');
  84. if (headerInterval) {
  85. const headerIntervalMs = parseInt(headerInterval);
  86. if (!isNaN(headerIntervalMs)) {
  87. sleepInterval = headerIntervalMs;
  88. }
  89. }
  90. }
  91. await (0, sleep_1.sleep)(sleepInterval);
  92. break;
  93. case 'failed':
  94. case 'cancelled':
  95. case 'completed':
  96. return batch;
  97. }
  98. }
  99. }
  100. /**
  101. * Uploads the given files concurrently and then creates a vector store file batch.
  102. *
  103. * The concurrency limit is configurable using the `maxConcurrency` parameter.
  104. */
  105. async uploadAndPoll(vectorStoreId, { files, fileIds = [] }, options) {
  106. if (files == null || files.length == 0) {
  107. throw new Error(`No \`files\` provided to process. If you've already uploaded files you should use \`.createAndPoll()\` instead`);
  108. }
  109. const configuredConcurrency = options?.maxConcurrency ?? 5;
  110. // We cap the number of workers at the number of files (so we don't start any unnecessary workers)
  111. const concurrencyLimit = Math.min(configuredConcurrency, files.length);
  112. const client = this._client;
  113. const fileIterator = files.values();
  114. const allFileIds = [...fileIds];
  115. // This code is based on this design. The libraries don't accommodate our environment limits.
  116. // https://stackoverflow.com/questions/40639432/what-is-the-best-way-to-limit-concurrency-when-using-es6s-promise-all
  117. async function processFiles(iterator) {
  118. for (let item of iterator) {
  119. const fileObj = await client.files.create({ file: item, purpose: 'assistants' }, options);
  120. allFileIds.push(fileObj.id);
  121. }
  122. }
  123. // Start workers to process results
  124. const workers = Array(concurrencyLimit).fill(fileIterator).map(processFiles);
  125. // Wait for all processing to complete.
  126. await (0, Util_1.allSettledWithThrow)(workers);
  127. return await this.createAndPoll(vectorStoreId, {
  128. file_ids: allFileIds,
  129. });
  130. }
  131. }
  132. exports.FileBatches = FileBatches;
  133. //# sourceMappingURL=file-batches.js.map